Saving all open matplotlib shapes in one file at a time

I am trying to save an arbitrary number of matplotlib digits that I have already created in 1 file (PDF?). Is there a way to do this with a single command?

+7
python matplotlib
source share
1 answer

MatPlotLib currently supports storing multiple shapes in a single PDF file . An implementation using this function will be as follows:

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

Usage example

First create some numbers,

 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 print all open shapes,

 multipage('multipage.pdf') 

The only thing you got is that all the shapes are displayed as vector (pdf) graphics. If you want your shape to use bitmap graphics (i.e. if the files are too large as vectors), you can use the rasterized=True option when plotting a quantity with many dots. In this case, the dpi parameter that I turned on 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 only selected fig2 and fig3 .

+14
source share

All Articles