Saving & Exporting#
Up to this point, all of our examples have ended with the line plt.show()
. But there are many situations in which you might want or need to save a plot as a static image file. We can do this using plt.savefig()
.
matplotlib
supports the following image file types:
.png
: portable network graphics; raster-graphics file format that supports lossless data compression.pdf
: portable document format; proprietary Adobe file format; fixed-layout flat document.ps
: postscript; page description language developed by Adobe.eps
: encapsulated postscript; postscript document formatted as a graphics file format.svg
: scalable vector graphics; vector based image based on XML
A few examples of these workflows
%matplotlib inline
import matplotlib.pyplot as plt # import statement
# basic workflow
squares = [1,4,9,16,25] # dataset for y axis
inputs = [1,2,3,4,5] # dataset for x axis
fig, ax = plt.subplots() # figure for new plot
ax.plot(inputs, squares) # generate plot
ax.set_title("Square Numbers") # set plot title
ax.set_xlabel("Value") # set x axis label
ax.set_ylabel("Square of Value") # set y axis label
plt.savefig("output.png") # save to image file
plt.show() # show output
# setting DPI for higher resolution
plt.savefig('output.png', dpi=300)
<Figure size 640x480 with 0 Axes>
# set transparent background
plt.savefig('output.svg', transparent=True)
<Figure size 640x480 with 0 Axes>
Additional Resources#
For more on customization options when saving a figure as an image: