Save multiple matplotlib plots into a pdf file

matplotlib_pdf

Skill - Save matplotlib plots into a pdf file

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Matplotlib is a plotting library tn the scipy ecosystem of libraries.

Please make sure that you covered thepost on basics


In some cases we might want to create a single document that contains all the plots so that it can be easy shared with our friends.
Using PdfPages object of the matplotlib.backends.backend_pdf sub-module, mulitple figures can be inserted into a single pdf file

Example

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import random

# create a pdf file object
pdfFile = PdfPages("output.pdf")

for pltItr in range(10):
    # create data for plot
    xVals = [x for x in range(1, 11)]
    yVals = [random.randint(50, 100) for x in xVals]

    # create a plot
    fig, ax = plt.subplots(figsize=(11,6))
    la, = ax.plot(xVals, yVals)
    ax.set_title("Plot number {0}".format(pltItr+1))
    ax.set_xlabel("X Values")
    ax.set_ylabel("Y Values")
    fig.tight_layout(pad=4)

    # add figure to pdf file
    pdfFile.savefig(fig)

# close the pdf file
pdfFile.close()

Video

You can the video on this post here


References

Table of Contents

Comments