Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python3
pdf

How to save plots to pdf in Python

Educative Answers Team

There may be many cases when the charts plotted need to be saved into a pdf file. This can be done using the matplotlib library.

To use the library, type:

from matplotlib.backends.backend_pdf import PdfPages

The default implementation of PdfPages is:

PdfPages(filename = None, keep_empty:bool = True, metadata= None)

Parameters

  • filename: string - The name you want to save the file as.

  • keep_empty: bool - If False, the empty Pdf files are automatically deleted.

  • metadata: dict - Information dictionary object. The standard keys are ‘Title’, ‘Author’, ‘Subject’, ‘Keywords’, ‘Creator’, ‘Producer’, ‘CreationDate’, ‘ModDate’, and ‘Trapped’. Values have been predefined for ‘Creator’, ‘Producer’, and ‘CreationDate’.

Functions

Since PdfPages creates an object of a class. The following functions are applicable:

  • get_pagecount(self) - Returns the number of pages in the pdf.

  • close(self) - Finalizes and closes the object.

  • attach_note(self, text, positionRect=[-100, -100, 0, 0]) - Adds a new note to the page that will be saved next. The optional positionRect specifies the position on the page.

  • infodict(self) - Returns a modifiable information dictionary object.

  • savefig(self, figure = None, **kwargs) - Saves a figure to the file. figure specifies the image saved to the file. By default, it saves the current image.

Code

Here is an example of saving a figure to a new file:

main.py
dataset.csv
#import library
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
#add csv file to dataframe
df = pd.read_csv('dataset.csv')

#create boxplot
with PdfPages('temp.pdf') as pdf:
    boxplot = df.boxplot(figsize = (5,5), rot = 90, fontsize= '8', grid = False)
    pdf.savefig()

RELATED TAGS

python3
pdf
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring