How to save a plot to a file using Matplotlib
Posted by: AJ Welch
[Matplotlib](https://matplotlib.org/ is a powerful two-dimensional plotting library for the Python language. Matplotlib is capable of creating all manner of graphs, plots, charts, histograms, and much more.
In most cases, matplotlib will simply output the chart to your viewport when the .show()
method is invoked, but we’ll briefly explore how to save a matplotlib creation to an actual file on disk.
Using matplotlib
While the feature-list of matplotlib is nearly limitless, we’ll quickly go over how to use the library to generate a basic chart for your own testing purposes.
Like all Python libraries, you’ll need to begin by installing matplotlib. We won’t go through the installation process here, but there’s plenty of information in the official documentation.
Once installed, import the matplotlib
library. You’ll likely also want to import the pyplot
sub-library, which is what you’ll generally be using to generate your charts and plots when using matplotlib.
In [1]: import matplotlib
import matplotlib.pyplot as plt
Now to create and display a simple chart, we’ll first use the .plot()
method and pass in a few arrays of numbers for our values. For this example, we’ll plot the number of books read over the span of a few months.
In [2]: plt.plot([0, 1, 2, 3, 4], [0, 3, 5, 9, 11])
We can also add a few axis labels:
In [3]: plt.xlabel('Months')
plt.ylabel('Books Read')
Finally, we can display the chart by calling .show()
:
In [4]: plt.show()
The savefig Method
With a simple chart under our belts, now we can opt to output the chart to a file instead of displaying it (or both if desired), by using the .savefig()
method.
In [5]: plt.savefig('books_read.png')
The .savefig() method requires a filename be specified as the first argument. This filename can be a full path and as seen above, can also include a particular file extension if desired. If no extension is provided, the configuration value of savefig.format
is used instead.
Additional savefig Options
In addition to the basic functionality of saving the chart to a file, .savefig()
also has a number of useful optional arguments.
dpi
can be used to set the resolution of the file to a numeric value.transparent
can be set toTrue
, which causes the background of the chart to be transparent.bbox_inches
can be set to alter the size of the bounding box (whitespace) around the output image. In most cases, if no bounding box is desired, usingbbox_inches='tight'
is ideal.-
If
bbox_inches
is set to'tight'
, then thepad_inches
option specifies the amount of padding around the image.
There are a handful of additional options for specific occasions, but overall this should get you started with easily generating image file outputs from your matplotlib charts.