Introduction to Figures#

fig=plt.figure(figsize=(2,2),facecolor='lightskyblue',layout='constrained')fig.suptitle('Figure')ax=fig.add_subplot()ax.set_title('Axes',loc='left',fontstyle='oblique',fontsize='medium')

(Sourcecode,2x.png,png)

When looking at Matplotlib visualization, you are almost always looking atArtists placed on aFigure. In the example above, the figure is theblue region andadd_subplot has added anAxes artist to theFigure (seeParts of a Figure). A more complicated visualization can addmultiple Axes to the Figure, colorbars, legends, annotations, and the Axesthemselves can have multiple Artists added to them(e.g.ax.plot orax.imshow).

Viewing Figures#

We will discuss how to create Figures in more detail below, but first it ishelpful to understand how to view a Figure. This varies based on how you areusing Matplotlib, and whatBackend you are using.

Notebooks and IDEs#

Image of figure generated in Jupyter Notebook with inline backend.

Screenshot of aJupyter Notebook, with a figuregenerated via the defaultinline backend.#

If you are using a Notebook (e.g.Jupyter) or an IDEthat renders Notebooks (PyCharm, VSCode, etc), then they have a backend thatwill render the Matplotlib Figure when a code cell is executed. The defaultJupyter backend (%matplotlibinline) creates static plots thatby default trim or expand the figure size to have a tight box around Artistsadded to the Figure (seeSaving Figures, below). For interactive plotsin Jupyter you will need to use an ipython "magic" like%matplotlibwidgetfor theipympl backend injupyterlabornotebook>=7, or%matplotlibnotebook for the Matplotlibnotebook innotebook<7 ornbclassic.

Note

Theipympl backend is in a separatepackage, seeInstalling ipympl.

Image of figure generated in Jupyter Notebook with notebook backend, including a toolbar.

Screenshot of a Jupyter Notebook with an interactive figure generated viathe%matplotlibnotebook magic. Users should also try the similarwidget backend if usingJupyterLab.#

Standalone scripts and interactive use#

If the user is on a client with a windowing system, there are a number ofBackends that can be used to render the Figure tothe screen, usually using a Python Qt, Tk, or Wx toolkit, or the native MacOSbackend. These are typically chosen either in the user'smatplotlibrc, or by calling, for example,matplotlib.use('QtAgg') at the beginning of a session or script.

Image of figure generated from a script via the QtAgg backend.

Screenshot of a Figure generated via a python script and shown using theQtAgg backend.#

When run from a script, or interactively (e.g. from anIPython shell) the Figurewill not be shown until we callplt.show(). The Figure will appear ina new GUI window, and usually will have a toolbar with Zoom, Pan, and other toolsfor interacting with the Figure. By default,plt.show() blocksfurther 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 seeInteractive mode.

Note that if you are on a client that does not have access to a windowingsystem, the Figure will fallback to being drawn using the "Agg" backend, andcannot be viewed, though it can besaved.

Creating Figures#

By far the most common way to create a figure is using thepyplot interface. As noted inMatplotlib Application Interfaces (APIs), the pyplot interface serves two purposes. One is to spinup the Backend and keep track of GUI windows. The other is a global state forAxes and Artists that allow a short-form API to plotting methods. In theexample above, we use pyplot for the first purpose, and create the Figure object,fig. As a side effectfig is also added to pyplot's global state, andcan be accessed viagcf.

Users typically want an Axes or a grid of Axes when they create a Figure, so inaddition tofigure, there are convenience methods that return botha Figure and some Axes. A simple grid of Axes can be achieved withpyplot.subplots (whichsimply wrapsFigure.subplots):

fig,axs=plt.subplots(2,2,figsize=(4,3),layout='constrained')

(Sourcecode,2x.png,png)

More complex grids can be achieved withpyplot.subplot_mosaic (which wrapsFigure.subplot_mosaic):

fig,axs=plt.subplot_mosaic([['A','right'],['B','right']],figsize=(4,3),layout='constrained')forax_name,axinaxs.items():ax.text(0.5,0.5,ax_name,ha='center',va='center')

(Sourcecode,2x.png,png)

Sometimes we want to have a nested layout in a Figure, with two or more sets ofAxes that do not share the same subplot grid.We can useadd_subfigure orsubfigures to create virtualfigures inside a parent Figure; seeFigure 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')

(Sourcecode,2x.png,png)

It is possible to directly instantiate aFigure instance without using thepyplot interface. This is usually only necessary if you want to create yourown GUI application or service that you do not want carrying the pyplot globalstate. See the embedding examples inEmbedding Matplotlib in graphical user interfaces for examples ofhow to do this.

Figure options#

There are a few options available when creating figures. The Figure size onthe screen is set byfigsize anddpi.figsize is the(width,height)of the Figure in inches (or, if preferred, units of 72 typographic points).dpiare how many pixels per inch the figure will be rendered at. To make your Figuresappear on the screen at the physical size you requested, you should setdpito the samedpi as your graphics system. Note that many graphics systems now usea "dpi ratio" to specify how many screen pixels are used to represent a graphicspixel. Matplotlib applies the dpi ratio to thedpi passed to the figure to makeit have higher resolution, so you should pass the lower number to the figure.

Thefacecolor,edgecolor,linewidth, andframeon options all change the appearance of thefigure in expected ways, withframeon making the figure transparent if set toFalse.

Finally, the user can specify a layout engine for the figure with thelayoutparameter. Currently Matplotlib supplies"constrained","compressed" and"tight" layout engines. Theserescale axes inside the Figure to prevent overlap of ticklabels, and try and alignaxes, and can save significant manual adjustment of artists on a Figure for manycommon cases.

Adding Artists#

TheFigure class has a number of methods for adding artists to aFigure oraSubFigure. By far the most common are to add Axes of various configurations(add_axes,add_subplot,subplots,subplot_mosaic) and subfigures (subfigures). Colorbarsare 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 usingadd_artistusually with care being taken to use the appropriate transform. Usually theseincludeFigure.transFigure which ranges from 0 to 1 in each direction, andrepresents the fraction of the current Figure size, orFigure.dpi_scale_transwhich will be in physical units of inches from the bottom left corner of the Figure(seeTransformations Tutorial for more details).

Saving Figures#

Finally, Figures can be saved to disk using thesavefig method.fig.savefig('MyFigure.png',dpi=200) will save a PNG formatted figure tothe fileMyFigure.png in the current directory on disk with 200 dots-per-inchresolution. Note that the filename can include a relative or absolute path toany 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 rasterformats, thedpi. Ifdpi is not set, then thedpi of the Figure is used.Note thatdpi still has meaning for vector formats like PDF if the Figure includesArtists that have beenrasterized; thedpi specified will be the resolution of the rasterized objects.

It is possible to change the size of the Figure using thebbox_inches argumentto savefig. This can be specified manually, again in inches. However, by farthe most common use isbbox_inches='tight'. This option "shrink-wraps", trimmingor expanding as needed, the size of the figure so that it is tight around all the artistsin a figure, with a small pad that can be specified bypad_inches, which defaults to0.1 inches. The dashed box in the plot below shows the portion of the figure thatwould be saved ifbbox_inches='tight' were used in savefig.

(Sourcecode,2x.png,png)