Matplotlib save to pdf not showing hatch marks in bar plot -- potential bug?
Asked Answered
C

1

6

I am using matplotlib version 3.1.1 on an ubuntu 18.04 machine and have tried this code in both python 3.6.8 and 3.7.4 on 2 different boxes.

The problem is that when there are more than 10 items the color repeats itself and I made a quick change to make hatch marks to differentiate. While this works well in display, the hatches do not show up when I savefig("*.pdf"). savefig("*.png") seems to work fine as seen in the figures below.

I have searched for this issue in multiple places but can't seem to find a solution that works. I have also tried PdfPages.

Simple code and output are attached below. I appreciate any suggestions.

Code:

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd

matplotlib.__version__  #3.1.1
df=pd.DataFrame({'A':[0.1]*12, 'B':[0.1]*12}).T
tit='title'

ax=df.plot.bar(figsize=(11,8.5),stacked=True,title=tit)
nrows=len(df)
bars = ax.patches
hatches=['','-', '+', 'x','/','//','O','o','\\','\\\\']*nrows*10 #times rows*colors
#
hatches.sort()
hatches=hatches[0:len(bars)]
i=0 
for bar in bars:# goes down a column with same color,  then next with diff color and so on.  
    bar.set_hatch(hatches[i])
    #bar.text('1')
    #print(bar)
    i+=1    
ax.legend(#loc='lower center', loc='upper center',bbox_to_anchor=(0.5, -.05,0,0),fancybox=True, shadow=True, ncol=5,fontsize=5.5)

#plt.savefig('barhatch.png')   

plt.savefig('barhatch.pdf')   

screenshot of actual plot:

screenshot of actual plot

savefig("out.png"):

savefig("out.png")

screenshot of the pdf as I can't seem to attach:

screenshot of the pdf as I can't seem to attach

Catima answered 25/12, 2019 at 17:48 Comment(0)
J
2

Try to use different facecolor for the filled space and edgecolor for the hatch.

I suppose the hatches are there but shown in the same color as the filled space below. I have experienced something similar with fill_between and found a solution in this GitHub discussion.

Judaic answered 30/6, 2021 at 10:32 Comment(1)
Nice! By simply putting edgecolor='k' as a parameter of the Patch, this was fixed!Vladamir

© 2022 - 2024 — McMap. All rights reserved.