Matplotlib figure to PDF without saving

前端 未结 3 2167
独厮守ぢ
独厮守ぢ 2021-02-11 04:10

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

相关标签:
3条回答
  • 2021-02-11 04:42

    I think you can save the figure into a buffer using io.BytessIO and use that in platypus. Something like this perhaps?

    import io
    import matplotlib.pylab as plt
    from reportlab.platypus import BaseDocTemplate, Image
    
    buffers = []
    
    for index, row in myDataFrame.iterrows():
        fig = plt.figure()
        plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')
    
        mybuffer = io.BytesIO()
        fig.savefig(mybuffer, format = 'pdf')
        mybuffer.seek(0)
        buffers.append(mybuffer)
        plt.close(fig)
    
    text = []
    doc = BaseDocTemplate(pageName, pagesize=landscape(A4))
    
    doc.build(buffers)
    
    0 讨论(0)
  • 2021-02-11 04:56

    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

    0 讨论(0)
  • 2021-02-11 05:07

    using my package autobasedoc https://pypi.org/project/autobasedoc/ your example would look like that:

    from autobasedoc import autorpt as ar
    from autobasedoc import autoplot as ap
    
    @ap.autoPdfImg
    def my_plot(index, row, canvaswidth=5): #[inch]
        fig, ax = ap.plt.subplots(figsize=(canvaswidth,canvaswidth))
        fig.suptitle(f"My simple plot {index}", fontproperties=fontprop)
        ax.plot(row['Xvalues'], row['Yvalues'],label=f"legendlabel{index}")
        return fig
    
    doc = ar.AutoDocTemplate(pageName)
    
    content = []
    
    for index, row in myDataFrame.iterrows():
        content.append(my_plot(index, row))
    
    doc.build(content)
    
    0 讨论(0)
提交回复
热议问题