Matplotlib

Chapter 11 – Saving and Exporting Plots in Matplotlib

Once you’ve created beautiful visualizations, the next step is to save and export them for use in reports, presentations, or websites. Matplotlib provides flexible tools for saving plots in multiple file formats with precise control over resolution, size, and quality.

✅ Why Saving Plots Matters

Visualizations are often used in research papers, dashboards, and web reports. Saving your plots ensures they can be shared, reused, or embedded anywhere with consistent quality.

✅ What You’ll Learn

  • How to save plots in different image formats
  • How to adjust resolution (DPI) and figure size
  • How to control transparent backgrounds and bounding boxes
  • How to export vector graphics for print and high-quality reports

✅ 1. Basic Saving with savefig()

Matplotlib’s savefig() function saves the current figure to an image file. You can specify the file name and format.


import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 20, 25, 30], label="Growth")
plt.title("Simple Line Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.legend()

# Save the figure
plt.savefig("plot.png")
plt.show()

By default, savefig() uses 100 DPI and saves the entire figure area.

✅ 2. Saving in Different File Formats

You can export your plots in several formats, including:

  • PNG – Raster image (best for web)
  • JPG – Compressed image (good for sharing)
  • PDF – Vector image (best for printing)
  • SVG – Scalable vector graphic (ideal for web and design tools)

Example:


plt.savefig("chart.pdf")   # Save as PDF
plt.savefig("chart.svg")   # Save as SVG
plt.savefig("chart.jpg")   # Save as JPG

✅ 3. Adjusting Resolution (DPI)

DPI (dots per inch) controls the image’s resolution.
Higher DPI produces sharper images, especially for printing.


plt.savefig("high_res_plot.png", dpi=300)

A DPI of 300–600 is recommended for print, while 100–150 works well for web.

✅ 4. Controlling Figure Size

You can set the figure’s size using the figsize parameter while creating it.


fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [2, 4, 6, 8])
ax.set_title("Custom Figure Size Example")

plt.savefig("figure_size.png", dpi=200)
plt.show()

✅ 5. Saving with Transparent Background

When placing plots on colored or patterned backgrounds (like websites), transparency helps blend them seamlessly.


plt.savefig("transparent_plot.png", transparent=True)

✅ 6. Tight Layout for Clean Margins

Sometimes labels or titles get cut off when saving.
Use bbox_inches='tight' to include all content neatly.


plt.savefig("tight_layout.png", bbox_inches='tight')

You can combine it with DPI and transparency:


plt.savefig("final_chart.png", dpi=300, bbox_inches='tight', transparent=True)

✅ 7. Exporting Vector Graphics

Vector formats like PDF and SVG maintain perfect quality at any zoom level — ideal for reports or design software.


plt.savefig("vector_output.pdf", format="pdf")
plt.savefig("vector_output.svg", format="svg")

✅ 8. Saving from Figure Object

If you’re using the object-oriented approach, call fig.savefig() instead of plt.savefig().


fig, ax = plt.subplots()
ax.plot([10, 20, 30], [3, 6, 9])
ax.set_title("Object-Oriented Save Example")

fig.savefig("oo_save.png", dpi=200, bbox_inches='tight')
plt.show()

✅ 9. File Paths and Automatic Folders

You can specify a full file path to save your plots into organized directories.


plt.savefig("C:/Projects/Plots/sales_chart.png", dpi=300)

Matplotlib will create the file if the directory exists.

✅ 10. Checking Supported Formats

To see which output formats Matplotlib supports:


import matplotlib.pyplot as plt
print(plt.gcf().canvas.get_supported_filetypes())

This prints a dictionary of all available formats such as PNG, PDF, EPS, JPG, SVG, and more.

✅ Best Practices

  • Use vector formats (PDF/SVG) for high-quality publications.
  • Always set dpi=300 or higher for professional reports.
  • Include bbox_inches='tight' to avoid cutoff edges.
  • Use descriptive filenames for better organization.
  • Keep consistent figure sizes for multi-plot reports.

✅ Summary

In this chapter, you learned how to save and export Matplotlib plots in multiple formats, control their resolution and size, and ensure high-quality, publication-ready output. These tools make your visualizations ready for professional use.

In the next chapter, we’ll explore Interactive and Live Plots — learning how to make dynamic visualizations that update in real time.

Leave a Reply

Your email address will not be published. Required fields are marked *