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)
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’.
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.
Here is an example of saving a figure to a new file:
#import libraryimport pandas as pdfrom matplotlib import pyplot as pltfrom matplotlib.backends.backend_pdf import PdfPages#add csv file to dataframedf = pd.read_csv('dataset.csv')#create boxplotwith PdfPages('temp.pdf') as pdf:boxplot = df.boxplot(figsize = (5,5), rot = 90, fontsize= '8', grid = False)pdf.savefig()
Free Resources