Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a stacked bar plot in seaborn with hatching

I am trying to plot a stacked bar plot using seaborn/matplotlib with hatching. But the hatching is not proper. Its coming as shown in image

enter image description here

My code is as below:

 sc_bar=sns.barplot(x='Salt Concentration',y='EPS 
             Produced',data=df_salt_conc_mod,hue='Strain',fill=False,edgecolor='black')
 bars = sc_bar.patches
 pattern=['//','..','xx','*']
 hatches=np.tile(pattern,7)

i=0

for bar in bars:
bar.set_hatch(pattern[i])
i+=1
count+=1
if(i>3):
    i=0

sc_bar.legend()

What am i doing wrong?

like image 612
Avnish Jain Avatar asked Sep 18 '25 02:09

Avnish Jain


1 Answers

Let's try zip:

df = sns.load_dataset('tips')
sc_bar = sns.barplot(data=df, x='tip', y='sex', hue='day', fill=False)
bars = sc_bar.patches
pattern=['//','..','xx','*']

# replace 2 with 7 in your code
hatches=np.repeat(pattern,2)

for pat,bar in zip(hatches,bars):
    bar.set_hatch(pat)

sc_bar.legend()

Output:

enter image description here

like image 137
Quang Hoang Avatar answered Sep 19 '25 16:09

Quang Hoang