Save Matplotlib plots to PDF with PdfPages changes my plots

22 Views Asked by At

I'm generating multiple figures in a for loop and then I want to save these figures in 1 pdf file. Therefore I use this code:

from matplotlib.backends.backend_pdf import PdfPages

save_image(filename_results)
plt.close('all')

def save_image(filename):
    #save image in pdf format, one page per plot
    p = PdfPages(filename)
    fig_nums = plt.get_fignums()
    figs = [plt.figure(n) for n in fig_nums]
    for fig in figs: 
        fig.savefig(p, format='pdf')
        fig.clf()
    p.close()

This code works but in the file generated, my heatmap get tilted by 45degrees (see here). When I save the figures in another format (png, jpeg) or just do plt.show(), this doesn't happen. Therefore I assume that it's the save_image function the issue. Weirdly enough the code was not doing this for weeks, now suddently it does this.

I'm using Python 3.1.9 and matplotlib 3.8.3.

Can you please help me fix this issue? I need to same in the pdf format to ensure a high resolution image.

0

There are 0 best solutions below