Matplotlib is a powerful Python library for creating visualizations. Saving your plots as PDFs is essential for sharing and archiving your work. PDFs offer portability, high-quality rendering, and broad compatibility. This guide covers saving single and multiple plots, along with customization options.
Table of Contents
- Saving a Single Plot as a PDF
- Saving Multiple Plots in a Single PDF File
- Customizing PDF Output
- Conclusion
- FAQ
Saving a Single Plot as a PDF
Saving a single plot is straightforward using savefig()
:
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 3, 5]
# Create the plot
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("My Plot")
# Save the plot as a PDF
plt.savefig("my_plot.pdf")
plt.show() # Optional: Displays the plot
To control resolution, use the dpi
parameter:
plt.savefig("my_plot_highres.pdf", dpi=300)
Saving Multiple Plots in a Single PDF File
Saving multiple plots requires more care. While you can sequentially save to the same file, this overwrites previous plots:
import matplotlib.pyplot as plt
# Plot 1
plt.figure(1)
plt.plot([1,2,3],[4,5,6])
plt.savefig("multiple_plots.pdf", bbox_inches='tight')
#Plot 2 (overwrites)
plt.figure(2)
plt.plot([1,2,3],[6,5,4])
plt.savefig("multiple_plots.pdf", bbox_inches='tight')
plt.show()
For better control, use libraries like ReportLab or PyPDF2 for more advanced PDF manipulation. These provide precise control over plot placement.
Customizing PDF Output
The savefig()
function offers numerous customization options:
facecolor
andedgecolor
: Control figure background color.orientation
: Set to “portrait” or “landscape”.transparent
: Create a PDF with a transparent background (True
orFalse
).bbox_inches
: Control the bounding box;'tight'
is useful to include all elements.
plt.savefig("customized_plot.pdf", facecolor='lightgray', edgecolor='black', orientation='landscape', transparent=False, bbox_inches='tight')
Conclusion
Saving Matplotlib plots as PDFs is crucial for sharing your work. This guide provided methods for single and multiple plots, as well as customization options. For complex layouts, consider advanced PDF libraries for greater control.
FAQ
- Q: My PDF is blank. A: Ensure
plt.savefig()
is called *after* creating the plot and verify the file path. - Q: How to save multiple plots on different pages? A: Use ReportLab or similar libraries.
- Q: My plot is cut off. A: Use
bbox_inches='tight'
. - Q: What DPI should I use? A: 300 DPI is a good balance between quality and file size.