Chapter 16 – Saving and Exporting Plots
After creating a beautiful visualization, the next important step is to save or export it for use in reports, presentations, publications, or web applications.
Matplotlib provides multiple ways to save figures — from simple image formats like PNG to scalable vector formats like PDF and SVG.
In this chapter, we’ll explore the full range of exporting options, including file formats, resolutions, transparency, and advanced figure handling.
✅ 1. Saving Plots Using savefig()
The simplest way to save a Matplotlib plot is by using the savefig() function.
import matplotlib.pyplot as plt
# Create sample data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot
plt.plot(x, y, color='blue', marker='o')
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
# Save the figure
plt.savefig("line_plot.png")
plt.show()
✅ This will save the figure as a **PNG file** in the current working directory.
—
✅ 2. Supported File Formats
Matplotlib supports multiple output formats for flexibility and quality.
| Format | Extension | Use Case |
|---|---|---|
| PNG | .png |
Common for web, screenshots, and general usage |
| JPG / JPEG | .jpg |
Compressed image format, good for web |
.pdf |
Best for high-quality print and publications | |
| SVG | .svg |
Vector graphics format, scalable without quality loss |
| EPS | .eps |
Encapsulated PostScript (used in LaTeX, print media) |
| TIFF | .tiff |
High-resolution raster format for scientific publishing |
Example:
plt.savefig("chart.pdf") # Save as PDF
plt.savefig("chart.svg") # Save as SVG
plt.savefig("chart.jpg") # Save as JPEG
—
✅ 3. Controlling Image Resolution (DPI)
**DPI (Dots Per Inch)** defines the quality or resolution of your saved plot.
Higher DPI = clearer images (especially for print or large displays).
plt.savefig("high_res_plot.png", dpi=300) # 300 DPI for publications
Common DPI settings:
- 72 DPI → Web or on-screen use
- 150 DPI → Presentations
- 300 DPI → Print quality
—
✅ 4. Saving Transparent Plots
Sometimes, you may want to overlay your chart on a background image or design.
In that case, use a **transparent background**.
plt.plot(x, y, color='purple', marker='o')
plt.title("Transparent Background Example")
plt.savefig("transparent_plot.png", transparent=True, dpi=300)
plt.show()
This saves the figure with no white background — ideal for web overlays.
—
✅ 5. Adjusting Figure Size Before Saving
You can customize the plot’s size before saving to maintain layout consistency.
plt.figure(figsize=(8, 5))
plt.plot(x, y, color='green', linewidth=2)
plt.title("Custom Figure Size Example")
plt.savefig("custom_size_plot.png", dpi=200)
plt.show()
The figsize=(width, height) argument defines size in inches.
—
✅ 6. Automatic Layout Adjustment
To ensure that labels, titles, and legends are not cut off, use tight_layout() before saving.
plt.figure(figsize=(7,4))
plt.plot(x, y, label="Data")
plt.title("Proper Layout Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.legend()
plt.tight_layout()
plt.savefig("tight_layout_plot.png", dpi=300)
plt.show()
Without tight_layout(), parts of the figure may get cropped in the saved image.
—
✅ 7. Saving Multiple Plots in One File (PDF)
You can save several figures in a **single multi-page PDF** using PdfPages from matplotlib.backends.backend_pdf.
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
with PdfPages('multi_plots.pdf') as pdf:
for i in range(3):
x = np.linspace(0, 10, 100)
y = np.sin(x + i)
plt.plot(x, y)
plt.title(f"Plot {i+1}")
pdf.savefig() # Save the current figure
plt.close()
✅ This will create a single PDF with three pages — each containing a different sine curve.
—
✅ 8. Exporting Vector Graphics (SVG, PDF, EPS)
Vector graphics are essential for **scientific journals, publications, and design**.
They remain sharp at any zoom level because they store paths instead of pixels.
plt.plot(x, y, color='orange', linewidth=3)
plt.title("Vector Export Example")
plt.savefig("vector_output.svg", format='svg')
plt.show()
You can also use:
plt.savefig("vector_output.pdf", format='pdf')
These formats are ideal for Adobe Illustrator, LaTeX, or Inkscape editing.
—
✅ 9. Adding Metadata to Exported Files
You can embed information such as author name, title, and description directly inside exported files.
metadata = {
'Title': 'Sales Report Visualization',
'Author': 'Data Analyst',
'Description': 'Quarterly sales trends generated using Matplotlib'
}
plt.plot(x, y, color='darkblue')
plt.title("Sales Data 2025")
plt.savefig("sales_plot.pdf", dpi=300, metadata=metadata)
This helps maintain documentation and credit within publication files.
—
✅ 10. Exporting Plots Automatically via Loops
If you’re generating many charts (e.g., one per dataset), automate the saving process.
import numpy as np
for i in range(1, 4):
x = np.linspace(0, 10, 100)
y = np.sin(x * i)
plt.plot(x, y)
plt.title(f"Sine Wave x{i}")
plt.savefig(f"sine_wave_{i}.png", dpi=200)
plt.close()
✅ Each plot will be saved as:
– sine_wave_1.png
– sine_wave_2.png
– sine_wave_3.png
—
✅ 11. Interactive vs Static Saving
When using interactive environments (like Jupyter or Colab):
– plt.show() displays the figure on screen.
– plt.savefig() saves it directly to disk.
You can use both together safely — just ensure that savefig() is called **before** plt.show().
—
✅ 12. Using Object-Oriented Interface for Saving
If you’re using the OO approach (Figure and Axes objects), you can save via the Figure object directly.
fig, ax = plt.subplots()
ax.plot(x, y, color='darkgreen', marker='o')
ax.set_title("Saving via OO Interface")
fig.savefig("oo_interface_plot.png", dpi=250)
plt.show()
This is useful when handling multiple figures or layouts.
—
✅ 13. Exporting Transparent Legends and Backgrounds
Sometimes you need transparency only for the **background**, not the data or text.
plt.plot(x, y, color='crimson', label="Signal")
plt.legend(facecolor='white', framealpha=0.5)
plt.savefig("transparent_legend.png", transparent=True)
plt.show()
✅ This keeps your chart’s contents clear while removing the white box behind it.
—
✅ 14. Exporting Plots for Web and Social Media
When preparing charts for websites or social posts:
- Use
dpi=150(optimized size vs clarity) - Use
bbox_inches='tight'to remove extra borders - Save as
.pngor.jpg
Example:
plt.plot(x, y, color='magenta')
plt.title("Ready for Web Post")
plt.savefig("web_ready_plot.png", dpi=150, bbox_inches='tight')
—
✅ 15. Exporting for PowerPoint or Reports
For business presentations or academic submissions, save in **high-resolution PNG or PDF**.
plt.plot(x, y, color='royalblue', linewidth=3)
plt.title("Annual Performance Summary")
plt.savefig("report_chart.pdf", dpi=300, bbox_inches='tight')
Use vector formats (PDF, SVG) for editable figures; raster formats (PNG, JPG) for static inclusion.
—
✅ 16. Summary
In this chapter, you learned everything about saving and exporting plots:
- Using
savefig()for different formats (PNG, JPG, PDF, SVG, EPS, TIFF) - Adjusting DPI and figure size for clarity
- Adding metadata and using transparency
- Exporting multiple plots into one PDF
- Automating chart exports using loops
By mastering these techniques, your visualizations will be ready for professional reports, websites, and publications.
—
✅ Coming Up Next
In the next chapter, we’ll explore **Matplotlib + Seaborn Integration** — combining Matplotlib’s flexibility with Seaborn’s statistical power for modern, elegant data visualizations.
