plot
image file
data visualization
save figure
matplotlib

Save plot to image file instead of displaying it

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

In Python data analysis and visualization, Matplotlib is commonly used to create static, animated, and interactive plots. However, there are instances where you want to save a plot directly to an image file rather than display it on the screen. This can be particularly useful for generating reports or for saving plots as part of a batch operation, where visualization on the screen is unnecessary.

Technical Explanation

The savefig() Method

The savefig() function in Matplotlib is used to save the current figure to a file. This function provides a plethora of options, including changing the file format, adjusting the resolution, and setting the bounding box. Here's a basic syntax for the savefig() function:

python
1import matplotlib.pyplot as plt
2
3# Example plot
4plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
5
6# Save the plot to a file
7plt.savefig('plot.png')

File Format

Matplotlib supports saving in multiple file formats. The format is usually inferred from the file extension you provide in the filename argument. Common file formats include PNG, PDF, SVG, and JPEG:

python
plt.savefig('plot.pdf')  # Saves as a PDF
plt.savefig('plot.svg')  # Saves as an SVG file
plt.savefig('plot.jpeg') # Saves as a JPEG image

Resolution and DPI

You can specify the dots per inch (dpi) for the output image, which affects the resolution of the saved file. By default, Matplotlib uses a dpi of 100, but you can change this value:

python
plt.savefig('plot_high_res.png', dpi=300)

Increasing the DPI will result in a higher quality image but may also increase the file size substantially.

Transparent Background

For some file types like PNG, you can save the plot with a transparent background by using the transparent=True parameter:

python
plt.savefig('plot_transparent.png', transparent=True)

Bounding Box

The bbox_inches parameter defines what portion of the plot should be saved. For instance, using bbox_inches='tight' will reduce the whitespace around the plot:

python
plt.savefig('plot_tight.png', bbox_inches='tight')

Examples

Plot with Axis Labels and Title

python
1import matplotlib.pyplot as plt
2
3plt.figure()
4plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
5plt.title("Line Plot")
6plt.xlabel("x-axis")
7plt.ylabel("y-axis")
8
9# Save to file
10plt.savefig('line_plot.png', dpi=150)

Subplot Example

Suppose you want to save a figure that contains multiple subplots:

python
1fig, axs = plt.subplots(2, 2)
2
3axs[0, 0].plot([1, 2], [1, 2])
4axs[0, 1].plot([1, 2], [2, 3])
5axs[1, 0].plot([1, 2], [3, 4])
6axs[1, 1].plot([1, 2], [4, 5])
7
8# Save the entire figure
9plt.savefig('subplots.png')

Advantages of Saving Plots

  1. Automation: Enables automatic saving as part of a scripting or reporting system.
  2. Archiving: Useful for creating a persistent record of data visualizations.
  3. Versatility: Offers multiple formats suitable for different applications, such as web (PNG, JPEG), print (PDF), and vector graphics editors (SVG).

Disadvantages

  1. Static: Does not support interactive plots, which are crucial for exploratory data analysis.
  2. Size Management: Larger file sizes with high DPI settings can cause storage concerns.
  3. Fit Issues: Saving directly can sometimes result in poor format fitting if not properly calibrated.

Summary Table

FeatureDescription
File FormatsPNG, PDF, SVG, JPEG, etc. Infer from extension
DPIResolution management Default is 100
Transparent BackgroundUse transparent=True for PNG images
Bounding Box ManagementUse bbox_inches='tight' to remove whitespace
Automation and ArchivingConvenient for scripts and reports
InteractivityOnly static plots; no interactive features

Saving plots as image files using Matplotlib is a fundamental skill for data scientists and developers who need to create interpretative visuals for non-interactive applications. Adjusting settings such as format, resolution, and layout allows you to customize the output to suit your specific needs.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.