Saving Visuals in Matplotlib
In this lesson, you will learn how to save Matplotlib charts and figures in different file formats. You will explore savefig(), image resolution, transparency, file formats, and export settings.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand why saving Matplotlib visualizations is important.
- Save a Figure using the savefig() method.
- Understand common image and document formats.
- Configure the output file name and location.
- Control the resolution of saved images using DPI.
- Save transparent backgrounds.
- Use bbox_inches and pad_inches options.
- Export charts for reports, presentations, and documents.
2. Why Save Matplotlib Visuals?
Matplotlib allows us to create charts and visualizations using Python. After creating a chart, we may need to save it for future use, share it with others, or include it in reports and presentations.
The savefig() method provides a way to export a Figure to a file. It supports several formats, including PNG, JPG, SVG, and PDF.
Example: Student Performance Report
Suppose Omkar creates a student performance chart using Matplotlib. He wants to include that chart in a project report. Instead of taking a screenshot, he can save the Figure as an image file and use it in his document.
This approach gives better control over image dimensions, resolution, and output format.
3. Saving a Figure Using savefig()
Matplotlib provides the savefig() method to save a Figure to a file. It can be called directly on a Figure object.
Basic Syntax
fig.savefig("filename.png")
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("My First Chart")
fig.savefig("my_chart.png")
plt.show()
Explanation:
- fig: Represents the Figure object.
- savefig(): Saves the Figure to a file.
- my_chart.png: Specifies the output file name.
- plt.show(): Displays the chart.
4. Supported File Formats
Matplotlib supports multiple output formats. The format is generally determined from the file extension or can be specified explicitly using the format parameter.
| Format | Extension | Common Usage |
|---|---|---|
| PNG | .png | Web images, reports, and presentations. |
| JPEG | .jpg / .jpeg | Compressed photographic-style images. |
| SVG | .svg | Scalable vector graphics for web and design. |
| Reports and document publishing. | ||
| EPS | .eps | Vector graphics and publishing workflows. |
| PS | .ps | PostScript document output. |
Example: Saving in Different Formats
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Sales Report")
fig.savefig("sales_report.png")
fig.savefig("sales_report.pdf")
fig.savefig("sales_report.svg")
plt.show()
5. Saving a Figure to a Specific Location
We can provide a complete file path to save a Figure in a particular folder instead of the current working directory.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Monthly Report")
fig.savefig(
"C:/Users/Omkar/Pictures/monthly_report.png"
)
plt.show()
The chart will be saved in the specified folder if the directory exists and the application has permission to write there.
6. Controlling Image Resolution Using DPI
DPI stands for Dots Per Inch. It controls the raster resolution used when saving an image. A higher DPI generally creates an image with more pixels for the same physical Figure size.
Example: Saving at 300 DPI
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("High Resolution Chart")
fig.savefig(
"high_resolution_chart.png",
dpi=300
)
plt.show()
In this example, the Figure is saved as a PNG image using 300 DPI.
| DPI | Typical Purpose | Output Characteristics |
|---|---|---|
| 72 | Some screen-oriented workflows. | Lower pixel density. |
| 100 | Basic charts and examples. | Standard pixel dimensions. |
| 150 | Presentation and report images. | More pixels than 100 DPI. |
| 300 | High-resolution raster export. | Higher pixel density. |
7. Saving Transparent Backgrounds
Sometimes we need a chart without a solid background. Matplotlib supports transparent export using the transparent parameter of savefig().
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Transparent Chart")
fig.savefig(
"transparent_chart.png",
transparent=True
)
plt.show()
The transparent parameter requests a transparent Figure background in the saved output where the selected format supports transparency.
8. Understanding bbox_inches and pad_inches
Matplotlib provides additional savefig() options to control the saved Figure boundaries and surrounding padding.
bbox_inches
The bbox_inches parameter controls the bounding box used when saving a Figure. Setting it to "tight" crops the output around the Figure contents.
fig.savefig(
"tight_chart.png",
bbox_inches="tight"
)
pad_inches
The pad_inches parameter specifies the amount of padding around the saved content when using a tight bounding box.
fig.savefig(
"padded_chart.png",
bbox_inches="tight",
pad_inches=0.2
)
9. Saving Figures Using format Parameter
Matplotlib can also save a Figure by specifying the output format explicitly using the format parameter.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
fig.savefig(
"student_report",
format="png"
)
plt.show()
In this example, the format parameter specifies PNG output. When format is specified, Matplotlib uses that format; the filename does not have to include the extension.
10. Saving Multiple Figures
We can create multiple Figure objects and save each one separately. This is useful when a project contains different charts for different reports.
Example
import matplotlib.pyplot as plt
# First Figure
fig1, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [10, 20, 30])
ax1.set_title("Line Chart")
fig1.savefig("line_chart.png")
# Second Figure
fig2, ax2 = plt.subplots()
ax2.bar(["A", "B", "C"], [15, 25, 20])
ax2.set_title("Bar Chart")
fig2.savefig("bar_chart.png")
plt.show()
Each Figure is saved separately using its own Figure reference.
11. Complete Example: Create and Export a Report
Let's create a complete student performance chart and save it in PNG and PDF formats.
Student Performance Report
import matplotlib.pyplot as plt
# Sample data
students = ["Amit", "Rahul", "Priya", "Sneha", "Om"]
marks = [75, 82, 90, 68, 95]
# Create Figure and Axes
fig, ax = plt.subplots(
figsize=(10, 5),
dpi=100
)
# Create bar chart
ax.bar(
students,
marks,
color="steelblue",
label="Student Marks"
)
# Configure chart
ax.set_title("Student Performance Report")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")
ax.set_ylim(0, 100)
ax.grid(axis="y", linestyle="--", alpha=0.5)
ax.legend()
# Adjust layout
fig.tight_layout()
# Save as PNG
fig.savefig(
"student_performance.png",
dpi=300,
bbox_inches="tight"
)
# Save as PDF
fig.savefig(
"student_performance.pdf",
bbox_inches="tight"
)
# Display Figure
plt.show()
This example creates one Figure and exports it into two different formats. The PNG file uses 300 DPI, while the PDF file is saved as a document format.
12. Common Mistakes While Saving Visuals
| Common Mistake | Correct Approach |
|---|---|
| Using an unsupported file extension. | Use a format supported by the active Matplotlib backend. |
| Saving to a folder that does not exist. | Create the destination directory before saving. |
| Saving a low-resolution image. | Configure a suitable DPI for raster output. |
| Expecting JPEG to support transparency. | Use PNG when a transparent background is required. |
| Cutting off titles or labels. | Use tight_layout() or bbox_inches="tight" when appropriate. |
| Using the wrong Figure reference. | Call savefig() on the Figure you want to export. |
| Assuming format and filename extension always match. | Specify a matching extension or use the format parameter carefully. |
13. Classroom Practical Activity
Activity: Save a Sales Report in Multiple Formats
Create a Matplotlib visualization using the following sample data:
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120, 150, 180, 140, 220]
Complete the following tasks:
- Import Matplotlib using pyplot.
- Create a Figure with figsize=(10, 5).
- Plot monthly sales data using a line chart.
- Add a title, X-axis label, and Y-axis label.
- Configure the grid and legend.
- Save the Figure as a PNG image.
- Save the same Figure as a PDF file.
- Save another PNG image using 300 DPI.
- Try saving a transparent PNG image.
- Use bbox_inches="tight" and compare the output.
Practice Questions
- Which method is used to save a Matplotlib Figure?
- What is the purpose of savefig()?
- Which file format is commonly used for raster images?
- What is the difference between PNG and SVG?
- How can you save a Figure at 300 DPI?
- How can you save a Figure with a transparent background?
- What is the purpose of bbox_inches="tight"?
- What does pad_inches control?
- How can you save one Figure in multiple formats?
Summary
In this lesson, you learned how to save Matplotlib visualizations using the savefig() method. You explored common output formats, file paths, image resolution, transparent backgrounds, and export configuration options.
You also learned how to save charts in PNG, JPEG, SVG, and PDF formats and how to control the exported image using DPI, bbox_inches, and pad_inches.
- fig.savefig() exports a Figure to a file.
- PNG and JPEG are raster image formats.
- SVG and PDF can preserve vector graphics.
- DPI controls raster output resolution.
- transparent=True requests a transparent background.
- bbox_inches="tight" crops the saved output around its contents.
- pad_inches controls padding with a tight bounding box.
- A single Figure can be saved in multiple formats.
You have now completed the Figure Anatomy section. In the next section, we will learn about basic plotting techniques in Matplotlib.