Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving all open matplotlib figures in one file at once

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?

like image 252
user1830663 Avatar asked Oct 14 '14 19:10

user1830663


People also ask

How do I save multiple graphs in the same PDF in Python?

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.

How do I save multiple plots from a Jupyter notebook?

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.

How do I save my matplotlib data?

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.

Is there something better than matplotlib?

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.


1 Answers

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

Example Usage

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.

like image 163
farenorth Avatar answered Sep 21 '22 12:09

farenorth