Python ModulesMatplotlib TutorialSaving and Exporting Plots

Exporting and Saving Plots in Matplotlib

Matplotlib provides versatile options to save plots in different formats, resolutions, and styles, making it easy to integrate visualizations into reports and presentations.


Saving Plots in Various Formats

You can save plots using the savefig() function. Matplotlib supports several formats such as PNG, JPG, SVG, PDF, and more.

Example: Saving a Plot in PNG Format

import matplotlib.pyplot as plt
 
# Create a simple plot
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y, label="Example Plot")
 
# Add labels and title
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Sample Plot")
plt.legend()
 
# Save the plot as a PNG file
plt.savefig("sample_plot.png")
 
# Display the plot
plt.show()

Adjusting Resolution (DPI)

The dpi parameter in savefig() adjusts the resolution of the saved plot. Higher DPI values produce better-quality images.

Example: High-Resolution Plot

# Save the plot with high resolution (300 DPI)
plt.savefig("high_res_plot.png", dpi=300)

Adding Transparency to Plots

The transparent parameter in savefig() allows you to save plots with a transparent background, which is useful for overlays or custom backgrounds.

Example: Transparent Background

# Save the plot with a transparent background
plt.savefig("transparent_plot.png", transparent=True)

Combining Options: Format, DPI, and Transparency

You can combine multiple options in a single savefig() call.

Example: PDF with High Resolution and Transparency

# Save the plot as a PDF with high resolution and transparent background
plt.savefig("custom_plot.pdf", format="pdf", dpi=300, transparent=True)

Practical Tips for Exporting Plots

  1. File Naming: Use descriptive and unique file names for better organization.
  2. File Path: Specify the full file path if you want to save plots in a specific directory.
  3. Preview Before Saving: Use plt.show() to ensure the plot looks as expected.
  4. Formats for Different Uses:
    • Use PNG or JPG for web or presentations.
    • Use PDF or SVG for print-quality or vector graphics.

Example: Saving in a Specific Directory

# Save the plot in a custom directory
plt.savefig("/path/to/directory/custom_plot.png")

With Matplotlib’s savefig() function, you can easily tailor the output to your needs, whether for web, print, or other professional applications.