How to Save Matplotlib Figure to a File (With Examples)

Matplotlib is a powerful library for plotting data in Python. To save a figure to a file, you will need to use the savefig() function. This function provides the ability to save your figure in a wide variety of formats, such as PNG, PDF, and EPS. To save your figure to a file, you must provide a file name and the file format you wish to save it in. Examples are provided to help you understand how to use this function more effectively.


You can use the following basic syntax to save a Matplotlib figure to a file:

import matplotlib.pyplot as plt

#save figure in various formats
plt.savefig('my_plot.png')
plt.savefig('my_plot.jpg') 
plt.savefig('my_plot.pdf')

The following examples show how to use this syntax in practice.

Example 1: Save Matplotlib Figure to PNG File

The following code shows how to save a Matplotlib figure to a PNG file:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4, 5, 6]
y = [8, 13, 14, 11, 16, 22]

#create scatterplot with axis labels
plt.plot(x, y)
plt.xlabel('X Variable')
plt.ylabel('Y Variable')

#save figure to PNG file
plt.savefig('my_plot.png')

If we navigate to the location where we saved the file, we can view it:

Example 2: Save Matplotlib Figure with Tight Layout

By default, Matplotlib adds generous padding around the outside of the figure.

To remove this padding, we can use the bbox_inches=’tight’ argument:

#save figure to PNG file with no padding
plt.savefig('my_plot.png', bbox_inches='tight')

Notice that there is less padding around the outside of the plot.

Example 3: Save Matplotlib Figure with Custom Size

You can also use the dpi argument to increase the size of the Matplotlib figure when saving it:

#save figure to PNG file with increased size
plt.savefig('my_plot.png', dpi = 100)

You can find the complete online documentation for the Matplotlib savefig() function .

The following tutorials explain how to perform other common functions in Matplotlib:

x