Skip to content

Saving plots

Saving plots

Matplotlib plots can be saved with the plt.savefig() function. The plt.savefig() function needs to be called right above the plt.show() command. All the features of the plot must be specified before the plot is saved as an image file. If the figure is saved after the plt.show() command, the figure will not be saved until the plot window is closed. This can be problematic when building plots in a Jupyter notebook with %matplotlib inline enabled.

A standard save fig command is:

plt.savefig('plot.png', dpi=300, bbox_inches='tight')

Where 'plot.png' is the name of the saved image. Matplotlib will infer the image file format (.png, .jpg, etc) based on the extension specified as part of the file name.

The keyword argument dpi= specifies how many dots per inch the saved (saved image resolution). dpi=72 is fine for web images. dpi=300 is probably better for an image designed to go in a written report or .pdf.

The keyword argument bbox_inches='tight' is optional. If the axis labels in the plot are cut off in the saved image, set bbox_inches='tight'.

The following code saves one of the line plots from the previous section to the image file: plot.png

In [1]:
import matplotlib.pyplot as plt
# if using a Jupyter notebook, include:
%matplotlib inline

x = [0, 2, 4, 6] y = [1, 3, 4, 8] plt.plot(x,y) plt.xlabel('x values') plt.ylabel('y values') plt.title('plotted x and y values') plt.legend(['line 1'])

#save the figure plt.savefig('plot.png', dpi=300, bbox_inches='tight')

plt.show()