How to Save Plots as PDF File in Matplotlib

  1. Saving a Single Plot as a PDF
  2. Saving Multiple Plots in a Single PDF File
  3. Customizing PDF Output
  4. Conclusion
  5. FAQ
How to Save Plots as PDF File in Matplotlib

Creating visualizations is an essential part of data analysis, and Matplotlib is one of the most popular libraries for this purpose in Python. One of the great features of Matplotlib is the ability to save your plots in various formats, including PDF. This capability is particularly useful when you want to share or print your visualizations while maintaining high quality.

In this article, we’ll explore how to save plots as PDF files using the savefig() function. Additionally, we will discuss how to save multiple plots into a single PDF file using the PdfPages class. Whether you are preparing a report or simply want to archive your visualizations, these techniques will enhance your workflow.

Saving a Single Plot as a PDF

The simplest way to save a plot in Matplotlib is by using the savefig() function. This function allows you to specify the filename and the format you want to save your plot in. When saving as a PDF, the file extension should be .pdf. Here’s a quick example to demonstrate this.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('Simple Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

plt.savefig('simple_plot.pdf')

In this code, we first import the Matplotlib library and create a simple line plot. The savefig() function is then called with the filename ‘simple_plot.pdf’. This saves the plot in PDF format. The advantage of saving in PDF is that it retains the quality of the graphics, making it ideal for printing or sharing with others. You can easily open the resulting PDF file in any PDF viewer to see your plot.

Saving Multiple Plots in a Single PDF File

If you have multiple plots that you want to save in a single PDF file, the PdfPages class from Matplotlib is a great tool. This class allows you to create a multi-page PDF document, where each page can contain a different plot. Here’s how you can use it:

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

pdf_filename = 'multiple_plots.pdf'
with PdfPages(pdf_filename) as pdf:
    for i in range(1, 4):
        plt.figure()
        plt.plot([1, 2, 3, 4], [i, i**2, i**3, i**4])
        plt.title(f'Plot for i = {i}')
        plt.xlabel('X-axis')
        plt.ylabel('Y-axis')
        pdf.savefig()  
        plt.close()

In this example, we first import PdfPages and create a new PDF file named ‘multiple_plots.pdf’. Using a for loop, we generate three different plots, each corresponding to different values of i. After plotting, we call pdf.savefig() to save each plot to the PDF. Finally, we close the plot with plt.close() to avoid displaying it on the screen. The result is a single PDF file containing all three plots, making it easy to share or present your findings.

Customizing PDF Output

When saving plots as PDFs, you may want to customize the output further. Matplotlib provides parameters in the savefig() function to control aspects like the DPI (dots per inch), orientation, and bounding box. Here’s an example that demonstrates how to customize the output:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 5))
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('Customized Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

plt.savefig('customized_plot.pdf', dpi=300, bbox_inches='tight')

In this code, we set the figure size to 10x5 inches, which can help in making the plot more readable. The dpi parameter is set to 300 for higher resolution, which is particularly useful for printing. The bbox_inches='tight' argument ensures that the bounding box of the plot is tight, trimming any unnecessary whitespace. This level of customization can significantly enhance the presentation quality of your visualizations.

Conclusion

Saving plots as PDF files in Matplotlib is a straightforward process that can greatly enhance your data visualization workflow. Whether you are saving a single plot or multiple plots in one document, the savefig() function and PdfPages class provide the flexibility and quality needed for professional presentations and reports. By customizing your PDF outputs, you can ensure that your visualizations are not only informative but also visually appealing. So, go ahead and start saving your plots as PDFs to share your insights effectively!

FAQ

  1. How do I save a plot as a PDF in Matplotlib?
    You can save a plot as a PDF using the savefig() function with the filename ending in .pdf.

  2. Can I save multiple plots in one PDF file?
    Yes, you can use the PdfPages class to save multiple plots in a single PDF file.

  3. What is the advantage of saving plots as PDF?
    PDF files maintain high quality and are suitable for printing and sharing.

  4. How can I customize the PDF output?
    You can customize the output by adjusting parameters like DPI and bounding box in the savefig() function.

  5. Is there a way to control the size of the saved plot?
    Yes, you can set the figure size using the figsize parameter when creating the plot.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Related Article - Matplotlib Save