4

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?

1 Answers1

2

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

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74