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

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

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

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 here.

Additional Resources

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

How to Set Axis Ranges in Matplotlib
How to Increase Plot Size in Matplotlib
How to Create Multiple Matplotlib Plots in One Figure

Leave a Reply

Your email address will not be published. Required fields are marked *