Search code examples
pythonpandasmatplotlibreportlab

Matplotlib figure to PDF without saving


I have to create a group of matplotlib figures, which I would like to directly present in a PDF report without saving them as a file.

The data for my plots is stored in a Pandas DataFrame:

Right now I do not know other better option than first save the image and use it later.

I am doing something like that:

import matplotlib.pylab as plt
from reportlab.platypus import BaseDocTemplate, Image

for index, row in myDataFrame.iterrows():
    fig = plt.figure()
    plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')
    fig.savefig('figure_%s.png' % (row['ID']))
    plt.close(fig)

text = []
doc = BaseDocTemplate(pageName, pagesize=landscape(A4))

for f in listdir(myFolder):
    if f.endswith('png'):
        image1 = Image(f)
        text.append(image1)

doc.build(text)

Solution

  • Here is the best solution provided by matplotlib itself:

    from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt
    
    with PdfPages('foo.pdf') as pdf:
        #As many times as you like, create a figure fig and save it:
        fig = plt.figure()
        pdf.savefig(fig)
    
        ....
        fig = plt.figure()
        pdf.savefig(fig) 
    

    Voilà

    Find a full example here: multipage pdf matplotlib