How to Save a Plot to a File Using Matplotlib
[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() :
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 to True , 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, using bbox_inches=’tight’ is ideal.
- If bbox_inches is set to ‘tight’ , then the pad_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.
Creating, viewing, and saving Matplotlib Figures#
When looking at Matplotlib visualization, you are almost always looking at Artists placed on a Figure . In the example above, the figure is the blue region and add_subplot has added an Axes artist to the Figure (see Parts of a Figure ). A more complicated visualization can add multiple Axes to the Figure, colorbars, legends, annotations, and the Axes themselves can have multiple Artists added to them (e.g. ax.plot or ax.imshow ).
Viewing Figures#
We will discuss how to create Figures in more detail below, but first it is helpful to understand how to view a Figure. This varies based on how you are using Matplotlib, and what Backend you are using.
Notebooks and IDEs#
If you are using a Notebook (e.g. Jupyter) or an IDE that renders Notebooks (PyCharm, VSCode, etc), then they have a backend that will render the Matplotlib Figure when a code cell is executed. One thing to be aware of is that the default Jupyter backend ( %matplotlib inline ) will by default trim or expand the figure size to have a tight box around Artists added to the Figure (see Saving Figures , below). If you use a backend other than the default «inline» backend, you will likely need to use an ipython «magic» like %matplotlib notebook for the Matplotlib notebook or %matplotlib widget for the ipympl backend.
Standalone scripts and interactive use#
If the user is on a client with a windowing system, there are a number of Backends that can be used to render the Figure to the screen, usually using a Python Qt, Tk, or Wx toolkit, or the native MacOS backend. These are typically chosen either in the user’s matplotlibrc , or by calling, for example, matplotlib.use(‘QtAgg’) at the beginning of a session or script.
When run from a script, or interactively (e.g. from an iPython shell) the Figure will not be shown until we call plt.show() . The Figure will appear in a new GUI window, and usually will have a toolbar with Zoom, Pan, and other tools for interacting with the Figure. By default, plt.show() blocks further interaction from the script or shell until the Figure window is closed, though that can be toggled off for some purposes. For more details, please see Interactive mode .
Note that if you are on a client that does not have access to a windowing system, the Figure will fallback to being drawn using the «Agg» backend, and cannot be viewed, though it can be saved .
Creating Figures#
By far the most common way to create a figure is using the pyplot interface. As noted in Matplotlib Application Interfaces (APIs) , the pyplot interface serves two purposes. One is to spin up the Backend and keep track of GUI windows. The other is a global state for Axes and Artists that allow a short-form API to plotting methods. In the example above, we use pyplot for the first purpose, and create the Figure object, fig . As a side effect fig is also added to pyplot’s global state, and can be accessed via gcf .
Users typically want an Axes or a grid of Axes when they create a Figure, so in addition to figure , there are convenience methods that return both a Figure and some Axes. A simple grid of Axes can be achieved with pyplot.subplots (which simply wraps Figure.subplots ):
fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout='constrained')
More complex grids can be achieved with pyplot.subplot_mosaic (which wraps Figure.subplot_mosaic ):
fig, axs = plt.subplot_mosaic([['A', 'right'], ['B', 'right']], figsize=(4, 3), layout='constrained') for ax_name in axs: axs[ax_name].text(0.5, 0.5, ax_name, ha='center', va='center')
Sometimes we want to have a nested layout in a Figure, with two or more sets of Axes that do not share the same subplot grid. We can use add_subfigure or subfigures to create virtual figures inside a parent Figure; see Figure subfigures for more details.
fig = plt.figure(layout='constrained', facecolor='lightskyblue') fig.suptitle('Figure') figL, figR = fig.subfigures(1, 2) figL.set_facecolor('thistle') axL = figL.subplots(2, 1, sharex=True) axL[1].set_xlabel('x [m]') figL.suptitle('Left subfigure') figR.set_facecolor('paleturquoise') axR = figR.subplots(1, 2, sharey=True) axR[0].set_title('Axes 1') figR.suptitle('Right subfigure')
It is possible to directly instantiate a Figure instance without using the pyplot interface. This is usually only necessary if you want to create your own GUI application or service that you do not want carrying the pyplot global state. See the embedding examples in Embedding Matplotlib in graphical user interfaces for examples of how to do this.
Figure options#
There are a few options available when creating figures. The Figure size on the screen is set by figsize and dpi. figsize is the (width, height) of the Figure in inches (or, if preferred, units of 72 typographic points). dpi are how many pixels per inch the figure will be rendered at. To make your Figures appear on the screen at the physical size you requested, you should set dpi to the same dpi as your graphics system. Note that many graphics systems now use a «dpi ratio» to specify how many screen pixels are used to represent a graphics pixel. Matplotlib applies the dpi ratio to the dpi passed to the figure to make it have higher resolution, so you should pass the lower number to the figure.
The facecolor, edgecolor, linewidth, and frameon options all change the appearance of the figure in expected ways, with frameon making the figure transparent if set to False.
Finally, the user can specify a layout engine for the figure with the layout parameter. Currently Matplotlib supplies «constrained» , «compressed» and «tight» layout engines. These rescale axes inside the Figure to prevent overlap of ticklabels, and try and align axes, and can save significant manual adjustment of artists on a Figure for many common cases.
Adding Artists#
The FigureBase class has a number of methods to add artists to a Figure or a SubFigure . By far the most common are to add Axes of various configurations ( add_axes , add_subplot , subplots , subplot_mosaic ) and subfigures ( subfigures ). Colorbars are added to Axes or group of Axes at the Figure level ( colorbar ). It is also possible to have a Figure-level legend ( legend ). Other Artists include figure-wide labels ( suptitle , supxlabel , supylabel ) and text ( text ). Finally, low-level Artists can be added directly using add_artist usually with care being taken to use the appropriate transform. Usually these include Figure.transFigure which ranges from 0 to 1 in each direction, and represents the fraction of the current Figure size, or Figure.dpi_scale_trans which will be in physical units of inches from the bottom left corner of the Figure (see Transformations Tutorial for more details).
Saving Figures#
Finally, Figures can be saved to disk using the savefig method. fig.savefig(‘MyFigure.png’, dpi=200) will save a PNG formatted figure to the file MyFigure.png in the current directory on disk with 200 dots-per-inch resolution. Note that the filename can include a relative or absolute path to any place on the file system.
Many types of output are supported, including raster formats like PNG, GIF, JPEG, TIFF and vector formats like PDF, EPS, and SVG.
By default, the size of the saved Figure is set by the Figure size (in inches) and, for the raster formats, the dpi. If dpi is not set, then the dpi of the Figure is used. Note that dpi still has meaning for vector formats like PDF if the Figure includes Artists that have been rasterized ; the dpi specified will be the resolution of the rasterized objects.
It is possible to change the size of the Figure using the bbox_inches argument to savefig. This can be specified manually, again in inches. However, by far the most common use is bbox_inches=’tight’ . This option «shrink-wraps», trimming or expanding as needed, the size of the figure so that it is tight around all the artists in a figure, with a small pad that can be specified by pad_inches, which defaults to 0.1 inches. The dashed box in the plot below shows the portion of the figure that would be saved if bbox_inches=’tight’ were used in savefig.