简体   繁体   中英

Matplotlib not showing histogram correctly when saving figure

Using matplotlib, I am plotting 2 histograms in one figure. The goal is to add them to a Latex document later. I am interested in the difference between the two, so I use a low transparency and plot them on top of each other. In Spyder, when I plot inline, the image looks fine. See wanted plot

通缉

When I export the image as a PNG using plt.savefig() , the image looks like this. However, this does not work well in Latex documents as the scaling gets ruined. When I try to export it as a PDF file, the bars of the histogram seem to overlap, making it seem like it has edges, like in ugly plot .

丑陋的

I think the cause of the problem is due to the vector format, when zooming in and out of the PDF, the overlap changes. When zoomed in completely, it looks identical to the PNG, when zoomed out the overlap becomes much larger. I would be very grateful if anyone knew the solution to this.

Things I have tried already:

  • changing linewidth/edgecolor
  • changing the matplotlibrc file
  • changing the distance of the bins using rwidth

Code I am using:

    binwidth = (np.max(prediction) - np.min(prediction)) / (2*I**(1/3))
    kwargs = dict(alpha=0.5, bins=np.arange(min(prediction), max(prediction) + binwidth, binwidth))
    
    fig_path = '***.pdf'

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.hist(prediction.flatten(), **kwargs, label = 'NN')
    ax.hist(hedging_error, **kwargs, label = 'BS')
    ax.set_xlim((-3,3))
    ax.set_xlabel('Hedging error')
    ax.set_ylabel('Count')
    ax.legend()
    fig.savefig(fig_path)

To remove the bin edges use plt.hist(..., histtype='stepfilled')

https://matplotlib.org/stable/gallery/statistics/histogram_histtypes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM