Exporting Plots to PDF - Matplotlib
When working with visualizations in Matplotlib, we often need to save plots in PDF format for reports, presentations, or printing. Matplotlib provides a simple way to export high-quality plots using the savefig() function, ensuring clear and professional-looking outputs. Let’s explore the best methods to export plots to PDF.
Using savefig() to Export a Single Plot
The easiest way to export a Matplotlib plot as a PDF is by using the savefig() function. This method allows us to save our figure with high quality in just one line.
import matplotlib.pyplot as plt
# Create a simple plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], marker='o', linestyle='--', color='b')
plt.title("Sample Plot")
# Save the plot as a PDF
plt.savefig("plot.pdf", format="pdf")
# Show the plot
plt.show()
Output:

Explanation:
- plt.plot(...) creates a simple line plot with markers.
- plt.title(...) adds a title to the plot.
- plt.savefig("plot.pdf", format="pdf") saves the figure as a PDF file.
- plt.show() displays the plot.
By default, the file is saved in the directory where the script is running. If you want to save it in a specific location, provide the full path:
plt.savefig("C:/Users/YourName/Documents/plot.pdf", format="pdf")
Exporting Multiple Plots to a Single PDF
If we need to save multiple plots in a single PDF file, Matplotlib provides PdfPages, which allows us to store multiple figures in one document.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# Create a PDF file to store multiple plots
with PdfPages("multiple_plots.pdf") as pdf:
# First plot
plt.figure()
plt.plot([1, 2, 3], [4, 5, 6], marker='o', linestyle='--', color='r')
plt.title("Plot 1")
pdf.savefig() # Save the first plot
plt.close() # Close the figure
# Second plot
plt.figure()
plt.bar(["A", "B", "C"], [10, 20, 30], color="g")
plt.title("Plot 2")
pdf.savefig() # Save the second plot
plt.close() # Close the figure
Explanation:
- PdfPages("multiple_plots.pdf") creates a PDF file to store multiple plots.
- plt.figure() initializes a new figure for each plot.
- pdf.savefig() saves the current figure into the PDF.
- plt.close() closes the figure to free memory.
By default, the file is saved in the directory where the script is running. To save it elsewhere, provide the full path:
with PdfPages("C:/Users/YourName/Documents/multiple_plots.pdf") as pdf:
