I am trying to save an arbitrary number of matplotlib figures that I have already created into 1 file(PDF?). Is there a way to do it with one command?
If we wish to plot multiple plots in a single, we can use the savefig() method of the PdfPages class. This saves 4 generated figures in Matplotlib in a single PDF file with the file name as Save multiple plots as PDF. pdf in the current working directory.
You can output each plot as an image, maybe into a new, separate directory, in the course of running your notebook and then at the end of the notebook code a section in using ReportLab or Pillow to iterate on the images in your directory to composite them together as you wish.
Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
Plotly has several advantages over matplotlib. One of the main advantages is that only a few lines of codes are necessary to create aesthetically pleasing, interactive plots. The interactivity also offers a number of advantages over static matplotlib plots: Saves time when initially exploring your dataset.
MatPlotLib currently supports saving multiple figures to a single pdf file. An implementation that uses this functionality would be:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
def multipage(filename, figs=None, dpi=200):
pp = PdfPages(filename)
if figs is None:
figs = [plt.figure(n) for n in plt.get_fignums()]
for fig in figs:
fig.savefig(pp, format='pdf')
pp.close()
First create some figures,
import matplotlib.pyplot as plt
import numpy as np
fig1 = plt.figure()
plt.plot(np.arange(10))
fig2 = plt.figure()
plt.plot(-np.arange(3, 50), 'r-')
By default multipage
will print all of the open figures,
multipage('multipage.pdf')
The only gotcha here is that all figures are rendered as vector (pdf) graphics. If you want your figure to utilize raster graphics (i.e. if the files are too large as vectors), you could use the rasterized=True
option when plotting quantities with many points. In that case the dpi
option that I included might be useful, for example:
fig3 = plt.figure()
plt.plot(np.random.randn(10000), 'g-', rasterized=True)
multipage('multipage_w_raster.pdf', [fig2, fig3], dpi=250)
In this example I have chosen to only print fig2
and fig3
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With