134

plotting module

def plotGraph(X,Y):
    fignum = random.randint(0,sys.maxint)
    plt.figure(fignum)
    ### Plotting arrangements ###
    return fignum

main module

import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()

I want to save all the graphs plot1, plot2, plot3 to a single PDF file. Is there any way to achieve it? I can't include the plotGraph function in the main module.

There's a function named pyplot.savefig but that seems to work only with a single figure. Is there any other way to accomplish it?

Hari
  • 1,561
  • 4
  • 17
  • 26
VoodooChild92
  • 1,993
  • 3
  • 19
  • 24
  • I provide a solution to essentially an identical question here: https://stackoverflow.com/questions/38938454/python-saving-multiple-subplot-figures-to-pdf/38943527#38943527 fyi to all; it may be of interest, provides versatile template code with lots of demonstrated customization of number of subplots per page, the spacing between them, overall style, etc., using PdfPages from `matplotlib` and optionally a more advanced code template leveraging `seaborn` – John Collins Nov 23 '21 at 08:39

4 Answers4

268

If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):

import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')
Clement T.
  • 2,993
  • 1
  • 11
  • 13
166

For multiple plots in a single pdf file you can use PdfPages

In the plotGraph function you should return the figure and than call savefig of the figure object.

------ plotting module ------

def plotGraph(X,Y):
      fig = plt.figure()
      ### Plotting arrangements ###
      return fig

------ plotting module ------

----- mainModule ----

from matplotlib.backends.backend_pdf import PdfPages

plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)

pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
Mike T
  • 41,085
  • 18
  • 152
  • 203
arjenve
  • 2,313
  • 1
  • 12
  • 7
  • 4
    "Plotting Arrangements" deserves an example to explain how to actually add plots to figures! – user2127595 Sep 13 '18 at 21:42
  • 1
    @user2127595 This works for me: def plot_graph(x, y1, y2): fig = plt.figure() axes1 = fig.add_subplot(2, 1, 1) axes2 = fig.add_subplot(2, 1, 2) axes1.plot(x, y1) axes2.plot(x, y2) return fig – DeanM Oct 01 '19 at 22:09
  • I am not sure why this answer didn't get the deserved attention: it answers the question straight to the point. – Cotta Sep 05 '22 at 13:50
38

Here is the canonical example provided by the matplotlib documentation site:

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Victor Juliet
  • 1,052
  • 11
  • 21
-39

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

VoodooChild92
  • 1,993
  • 3
  • 19
  • 24
  • 25
    Wait, I thought you wanted to save the plots into a single PDF file. Your solution saves the images into three separate PNG files, which seems like the answer to a different question. – DSM Jul 04 '12 at 12:36
  • 2
    Extremely sorry. I was conentrating more on saving the file somehow. I knew about the backend pdf thing..but got on with my work and neglected to add it. Anyway, thanks for pointing it out. – VoodooChild92 Jul 05 '12 at 06:11
  • 11
    Seeing the number of downvotes, you may think about deleting this answer to leave "room" for the other answers. – PatrickT Apr 15 '18 at 09:40