Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

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.

Matplotlib savefig() Export Figure Output Files chart.png chart.svg chart.pdf Create a visualization and export it into a file.
Figure 1: A basic workflow for exporting Matplotlib visualizations.

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.
Tip: Using fig.savefig() is recommended when working with the object-oriented Matplotlib API because it clearly identifies which Figure should be saved.

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.
PDF .pdf 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()
Tip: PNG and JPEG are raster formats. SVG and PDF can preserve vector graphics, which can be scaled without the same pixelation as raster images.

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.

Warning: Make sure that the destination folder exists before saving. Matplotlib does not automatically create missing parent directories.

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.

Normal Background Solid background Transparent background concept
Figure 2: Conceptual comparison of solid and transparent backgrounds.
Tip: PNG supports transparency. JPEG does not support transparent backgrounds.

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
)
Remember: pad_inches is primarily relevant when using bbox_inches="tight". It controls the extra space around the cropped content.

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.

Tip: When using the format parameter, provide a suitable filename and remember that the format argument determines the output format.

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.

Student Performance Report Amit Rahul Priya Sneha Om PNG Image output PDF Document output
Figure 3: One Matplotlib visualization exported into PNG and PDF formats.

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:

  1. Import Matplotlib using pyplot.
  2. Create a Figure with figsize=(10, 5).
  3. Plot monthly sales data using a line chart.
  4. Add a title, X-axis label, and Y-axis label.
  5. Configure the grid and legend.
  6. Save the Figure as a PNG image.
  7. Save the same Figure as a PDF file.
  8. Save another PNG image using 300 DPI.
  9. Try saving a transparent PNG image.
  10. Use bbox_inches="tight" and compare the output.

Practice Questions

  1. Which method is used to save a Matplotlib Figure?
  2. What is the purpose of savefig()?
  3. Which file format is commonly used for raster images?
  4. What is the difference between PNG and SVG?
  5. How can you save a Figure at 300 DPI?
  6. How can you save a Figure with a transparent background?
  7. What is the purpose of bbox_inches="tight"?
  8. What does pad_inches control?
  9. 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.