python logo

Matplotlib save figure to image file

Python hosting: Host, run, and code Python in the cloud!

If you want to save matplotlib figures as individual files, you can do this with the savefig function. If you want to save figures in a single file, use the saveas function instead.

Matplotlib is a python plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

Related course
The course below is all about data visualization:
Data Visualization with Matplotlib and Python

Save figure

For those who didn’t know, matplotlib savefig creates a file of the current figure as a PNG (with transparency), and saves it to your filesystem.

So Matplotlib can save plots directly to a file using savefig(). In this article we won’t cover the installation of matplotlib, if you want to install it see the installation faq.

Savefig is useful when you need to save a figure for viewing outside of matplotlib, such as in another program, or when you want to use a vector graphics program (Inkscape, Illustrator, etc.) to modify it.

It’s also useful if you want to save a copy of a figure in the same directory as your matplotlib script.

The method can be used like this:


fig.savefig('plot.png')

It can make an image from the figure. It decides on the image format based on the extension. For example to save a jpg image named figure1. jpg. The figure image must have an extension of jpg, png, or pdf.

The savefig method

The savefig() method is part of the matplotlib.pyplot module. This saves the contents of your figure to an image file.

It must have the output file as the first argument. You can add the full path, relative path or no path. If you don’t define a path, it will save the image in the current working directory.

The most basic program you can do is just 5 lines of code:

import matplotlib.pyplot as plt
plt.plot([0, 1, 2, 3, 4], [0, 2, 4, 8, 16])
plt.xlabel('Months')
plt.ylabel('Movies watched')
plt.savefig('example.png')

This works for larger plots too:


# load matplotlib modules
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# data to plot
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)

# create plot
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()

# save plot to file
fig.savefig('plot.png')

To change the format, simply change the extension like so:


fig.savefig('plot.pdf')

You can open your file with any external image program, because it’s just a regular image. If you use Linux, you can use the command below:


display plot.png

or open it in an image or pdf viewer if you saved it as pdf

matplotlib-plot-save A plot saved to a pdf

Additional savefig options

A number of new savefig options have been added to matplotlib. Backwards compatibility is maintained.
The options are:

savefig(filename, dpi=None, format='png', bbox_inches='tight', pad_inches=0.2, bbox=None, pad=None, dashes=None, loc='upper left', rot=0, vmax='I', vmin='I', hmax='I', hmin='I')

The output file name extension and format is controlled by the extension and format parameters; the above are defaults.

Useful parameters are:

  • filename the output file to save, if no path is included it will save it in the same directory as your program

  • transparent if you a transparent background set it to True

  • bbox_inches change the size of the white space around the image, in most cases tight is ideal

Save as PDF file

To save your matplotlib chart as a pdf, just change the file extension to .pdf


plt.savefig('line_plot.pdf')

The file will be saved in your working directory.

Save as SVG file

SVG is another vector-based graphics format, which lets you zoom in without losing quality. Not every program can open the svg image files.

To save as an SVG file, just change the extension to SVG


plt.savefig('line_plot.svg')

Save as JPEG file

If you save as jpeg file, you can include the quality parameter. This lets you save some disk space, but at the cost of image quality.


plt.savefig('line_plot.jpg', dpi=300, quality=80, optimize=True, progressive=True)

In general I recommend going with vector graphics formats like svg or pdf, because the quality is higher. If you don’t care about quality and just want to email the image or show it on a website, you could use png or jpeg.

Download Examples
 

BackNext





Leave a Reply: