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
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)
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
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)