The matplotlib Package

matplotlib's object model, which explains its two interfaces and most of its surprises. Its origin in epilepsy research and MATLAB; the backend, Artist and scripting layers; one scatter plot of 5,247 NHANES adults taken apart into its 144 Artists; pyplot's current Axes, which sends a title to the wrong panel; coordinate systems and transforms from data to pixels; backends and Agg; saving, with dpi, formats and byte-identical SVG output; figures left open; and mathtext without LaTeX.

A two-panel figure is meant to show systolic blood pressure against age on the left and a histogram of systolic pressure on the right, for the 5,247 NHANES 2017 to 2018 adults with a reading. Written with matplotlib's pyplot functions in a natural order,

plt.figure(figsize=(8, 3))
plt.subplot(1, 2, 1)
plt.scatter(age, sbp, s=2)
plt.subplot(1, 2, 2)
plt.hist(sbp, bins=40)
plt.title("Systolic pressure against age")     # meant for the left panel

it puts the title over the histogram. plt.title labels the "current" panel, which since the second plt.subplot call is the right one; the script that produced this article confirms that the left panel's title is empty. Nothing fails. The code reads like a description of a figure, but it is a sequence of commands to a state machine, and the state decides where each command lands.

matplotlib is the plotting library underneath most Python graphics: pandas' .plot methods and seaborn draw with it, and every figure on this site is made with it. Tools for Visualizing Data compares it with seaborn, plotly, ggplot2 and other tools, and explains the difference between its imperative style and declarative grammars of graphics. This article is about matplotlib itself: the objects a figure is made of, the two interfaces for creating them, how coordinates become pixels, how output reaches a screen or a file, and the practices that follow. The design principles for what to draw are in Best Practices for Visualizing Data.

All results come from tools/experiments/data-science/matplotlib-package.py in the site's repository, run with matplotlib 3.10.1 and the Agg backend.

Origins

matplotlib began in a neuroscience laboratory. John Hunter, its original author, was analyzing electrocorticography recordings of epilepsy patients (Hunter and Droettboom, 2012), at first with MATLAB, and in his own account "began to strain against the limitations of MATLAB as a programming language" as the application grew to involve databases, web servers and complex data structures (Hunter, 2008). He moved to Python but found no plotting package that met his requirements, which included publication-quality output with good text, PostScript output for TeX documents, and embedding in a graphical application, so he wrote one, emulating "MATLAB's plotting capabilities because that is something MATLAB does very well" (Hunter, 2008). Hunter (2007) introduced it to the scientific computing community; Hunter and Droettboom (2012) later described its architecture, and that description is the basis for most of what follows.

The two origins, an embeddable graphics library for an application and a replacement for MATLAB's interactive plotting commands, survive as matplotlib's two interfaces.

Three layers

Hunter and Droettboom (2012) describe matplotlib as three layers, "backend, artist, and scripting", in which "each layer that sits above another layer knows how to talk to the layer below it, but the lower layer is not aware of the layers above it".

The three layers of matplotlib. A pyplot call finds the current Figure and Axes and calls the corresponding Axes method; that method creates Artists; when the figure is drawn, each Artist paints itself through the Renderer of whichever backend is in use, raster or vector.
The three layers of matplotlib. A pyplot call finds the current Figure and Axes and calls the corresponding Axes method; that method creates Artists; when the figure is drawn, each Artist paints itself through the Renderer of whichever backend is in use, raster or vector.

The backend layer does the drawing. A FigureCanvas is the surface ("the paper"), a Renderer does the painting ("the paintbrush"), and an Event framework turns keyboard and mouse input from a windowing toolkit into matplotlib events. Different backends draw to different places: windows of the Qt, Tk, GTK or wx toolkits, notebook output cells, or files.

The Artist layer is the figure itself, as a tree of objects. "Everything you see in a matplotlib Figure is an Artist instance; the title, the lines, the tick labels, the images, and so on" (Hunter and Droettboom, 2012). Primitive Artists are the visible marks, such as Line2D, Rectangle, Text and the PathCollection that a scatter plot creates; container Artists, chiefly Figure, Axes, Axis and Tick, hold other Artists. Each Artist knows how to draw itself, given a Renderer, without knowing which backend the Renderer belongs to, which is what lets one figure be shown in a window or saved as PNG, SVG or PDF.

The scripting layer is matplotlib.pyplot, a set of functions that create and track Figures and Axes for the user. It is "a fairly thin wrapper around the core Artist API" (Hunter and Droettboom, 2012): plt.plot(...) gets the current Axes, creating a Figure and Axes if there are none, and calls that Axes' plot method with the same arguments.

The anatomy of a figure

One scatter plot of the 5,247 NHANES adults with a reading, with its main Artists labeled. The Figure holds one Axes, and the Axes holds the data Artists (a PathCollection from scatter and a Line2D from plot), the title, the legend, the spines and two Axis objects, each with its ticks, tick labels and label.
One scatter plot of the 5,247 NHANES adults with a reading, with its main Artists labeled. The Figure holds one Axes, and the Axes holds the data Artists (a PathCollection from scatter and a Line2D from plot), the title, the legend, the spines and two Axis objects, each with its ticks, tick labels and label.

A figure has three levels that matter in practice:

  • The Figure is the whole image: its size in inches (6.4 by 4.8 by default), its resolution in dots per inch (100 by default), its background, and everything drawn on it.
  • An Axes is one plotting region with its own data coordinates: one panel. Most plotting functions are methods of an Axes: ax.plot, ax.scatter, ax.hist, ax.set_xlabel. A Figure can hold any number of Axes, and color bars and insets are Axes too.
  • An Axis (ax.xaxis, ax.yaxis) is the number line along one side of an Axes, with its scale, limits, ticks and tick labels. The similar names are a common source of confusion: an Axes has two Axis objects.

The script builds the figure in the illustration, a scatter plot of systolic pressure against age with a least-squares line ($100.09 + 0.527 \times \text{age}$ for these 5,247 adults), axis labels, a title and a legend, and then walks the Artist tree with fig.findobj(). It finds 144 Artists: 56 Line2D objects, 46 Text objects, 9 XTick and 9 YTick objects, 4 spines, 2 PathCollection objects (the scatter and its marker in the legend), the Legend with its layout boxes, one XAxis, one YAxis, one Axes and one Figure. Only one of the 56 lines is the regression line; the rest are tick marks, grid lines and the legend's sample line. The whole scatter of 5,247 points is a single Artist, a PathCollection with 5,247 offsets, which is why scatter plots of large data are drawn quickly but saved as large vector files.

Every element can be reached and changed through this tree, ax.xaxis.get_major_ticks() or ax.title.set_fontsize(14), and every setting made through a pyplot function is a method call on one of these objects.

Two interfaces

The matplotlib documentation names the two interfaces the explicit "Axes" interface, "that uses methods on a Figure or Axes object to create other Artists, and build a visualization step by step", and the implicit "pyplot" interface, "that keeps track of the last Figure and Axes created, and adds Artists to the object it thinks the user wants" (Matplotlib Development Team, 2025a). The opening example in the explicit style is:

fig, (left, right) = plt.subplots(1, 2, figsize=(8, 3))
left.scatter(age, sbp, s=2)
left.set_title("Systolic pressure against age")
right.hist(sbp, bins=40)

Each call names the Axes it acts on, so the title cannot land on the wrong panel, and the order of the lines no longer matters. The pyplot functions remain useful for quick looks in a notebook, and pyplot is still the usual way to create a Figure (plt.subplots) and to show it, but for anything with more than one panel, or code that will be reused, the documentation's advice is "to be explicit from the outset" (Matplotlib Development Team, 2025a). The two mix freely: the script checks that after fig, ax = plt.subplots(), a call to plt.plot draws into ax, since ax is the current Axes, and plt.gcf() and plt.gca() return the current Figure and Axes for code that needs to move from one style to the other.

The method names differ slightly between the interfaces, by a set_ prefix: plt.title, plt.xlabel and plt.xlim correspond to ax.set_title, ax.set_xlabel and ax.set_xlim. Libraries that draw with matplotlib usually accept an ax argument (pandas' .plot(ax=...), seaborn's axes-level functions) and return the Axes they drew in, which is how their output is combined with other panels or adjusted afterwards.

Coordinates and transforms

Every point in a figure passes through several coordinate systems before it becomes a pixel. The documentation lists the main ones (Matplotlib Development Team, 2025b):

Coordinates Meaning Transform to display
data the values on the axes ax.transData
axes (0, 0) bottom left of the Axes, (1, 1) top right ax.transAxes
figure (0, 0) bottom left of the Figure, (1, 1) top right fig.transFigure
display pixels of the output, (0, 0) bottom left none

In the script's figure, 6.4 by 4.8 inches at 100 dots per inch, with automatic axis limits of 14.9 to 83.1 years and 64.4 to 246.3 mm Hg, the data point (50 years, 120 mm Hg) is at display position (335.3, 165.8) pixels; the top-right corner of the Axes, (1, 1) in axes coordinates, is at (576.0, 422.4); and the top right of the Figure is at (640, 480). The inverse transform takes (335.3, 165.8) back to (50, 120). After ax.set_ylim(60, 250), the same data point is at (335.3, 169.5): the transform depends on the axis limits, which is why matplotlib recomputes positions whenever limits change.

Transforms are what make annotations work. ax.annotate("note", xy=(50, 120), xytext=(0.7, 0.9), textcoords="axes fraction") places the arrow's tip in data coordinates and the text in axes coordinates, so the text stays in the corner whatever the data; ax.text(0.02, 0.95, "n = 5,247", transform=ax.transAxes) puts a label at a fixed place in the panel. The labels in the anatomy figure above were placed this way, in figure coordinates, with arrows to points in data and axes coordinates.

Backends

matplotlib chooses a backend when it first needs one. The documentation divides them into interactive backends, which open windows or draw into notebooks, and non-interactive "hardcopy" backends that write files (PNG, SVG, PDF, PS), and lists the ways to choose: the backend setting in a matplotlibrc file, the MPLBACKEND environment variable, or the function matplotlib.use(), with the last of these taking precedence (Matplotlib Development Team, 2025c). Without any of them, matplotlib tries the interactive backends in turn and falls back to Agg, "a non-interactive backend that can only write to files".

Agg, for the Anti-Grain Geometry library, is matplotlib's raster renderer. Hunter and Droettboom (2012) describe it as one of the design decisions that "worked quite well": the interactive backends draw with Agg and display its pixel buffer, so "the hardcopy is identical to the screen display". In Jupyter, the default inline backend draws each figure with Agg and embeds the result as an image in the output cell when the cell finishes; %matplotlib widget (the ipympl package) gives interactive figures inside the notebook instead. In a script, plt.show() opens windows on an interactive backend and displays nothing on Agg, so scripts that produce files should call savefig and need not call show at all. This site's figure scripts call matplotlib.use("Agg") before importing pyplot, so that they run the same way on any machine, with or without a display.

Saving figures

fig.savefig("name.svg") chooses the format from the file extension. For raster formats the dpi argument sets the resolution: the script's 6.4 by 4.8 inch figure is 640 by 480 pixels at 100 dpi (58,648 bytes as PNG) and 1,280 by 960 pixels at 200 dpi (117,315 bytes). Vector formats (SVG, PDF) store shapes and text rather than pixels, so they stay sharp at any size, but their size grows with the number of marks; Tools for Visualizing Data measures a scatter plot of these adults at 763 KB as SVG and 107 KB with only the points rasterized, which set_rasterized(True) on the scatter does. bbox_inches="tight" trims the saved image to the drawn content, and transparent=True leaves the background clear for display on colored pages, as on this site.

Repeatable output. A figure saved twice should produce the same file, so that a change in the file means a change in the figure, but by default an SVG does not. Saving the same small figure twice gave two files with different SHA-256 hashes, because matplotlib writes the current date into the file's metadata and, unless svg.hashsalt is set, salts the identifiers of the file's internal elements randomly. With plt.rcParams["svg.hashsalt"] set to a fixed string and metadata={"Date": None} passed to savefig, the two saves were byte-for-byte identical. This site's shared figure module, tools/figures/wikifig.py, sets both, which is why rerunning a figure script reproduces its files exactly and why a changed SVG in the repository always reflects a changed figure.

Figures left open

pyplot keeps a reference to every Figure it creates until the Figure is closed, so that it can show them later. A loop that creates a figure per group, saves it and moves on keeps every figure in memory. The script created 25 figures with plt.figure(); all 25 remained open, and matplotlib warned that more than 20 figures had been opened through the pyplot interface, the threshold set by rcParams["figure.max_open_warning"]. plt.close(fig) after saving, or plt.close("all"), releases them; the script ends with none open. Figures created directly as matplotlib.figure.Figure objects, without pyplot, are not tracked and are freed like any other Python object, and Hunter and Droettboom (2012) recommend this explicit style for web application servers and other programs that are not interactive sessions.

Configuration and mathematics

Every default, from figure size and font to colors, line widths and grid, is an entry in matplotlib.rcParams, which can be set in code, in a matplotlibrc file, or as a named style with plt.style.use. This site's figure module sets about thirty of them once (transparent backgrounds, the site palette as the color cycle, text colors, no top and right spines), so that each figure script contains only what is particular to its figure.

Text between dollar signs is rendered as mathematics, ax.set_title(r"$\bar{x} = \frac{1}{n}\sum_i x_i$"), by mathtext, matplotlib's own parser and layout engine for a subset of TeX. It does not need LaTeX installed: the script renders that title with text.usetex left at its default, False. Setting text.usetex to True hands all text to an installed LaTeX instead, which supports everything LaTeX does at the cost of speed and an external dependency. The r prefix makes the string raw, so that Python does not interpret backslash sequences such as \f or \b in the TeX commands as escape characters.

References