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 matplotlib figure is a tree of Artists: the Figure, its Axes, each Axes' two Axis objects, and marks such as Line2D and Text. They are created either through explicit Axes methods or through pyplot, which acts on a "current" Axes (Hunter and Droettboom, 2012). In the script's figures of 5,247 NHANES adults, pyplot can send a title to the wrong panel without an error. One scatter plot holds 144 Artists, all 5,247 points in a single one. The data point (50 years, 120 mm Hg) sits at pixel (335.3, 165.8), fixed by the axis limits, subplot parameters, figure size and dpi. Repeated SVG saves differ by default and become byte-identical with svg.hashsalt fixed and the date removed, and pyplot keeps every figure until it is closed.

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. On 23 November 2026 it was rerun with matplotlib 3.10.1 and, in a separate environment, 3.11.2: every number reproduced except the byte sizes of the PNG files and the SVG hashes, which depend on the version (3.11.2 wrote 60,023 and 118,735 bytes for the two PNG files below).

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 an EEG analysis application he had written in 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 (Worked problem 2 accounts for all 144). 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 ranges widened by 5% at each end), 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. Worked problem 1 computes all of these positions by hand.

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 33 of them once (27 of which differ from matplotlib 3.10.1's defaults) (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.

Worked problems

The problems take the script's figure apart by hand, using only documented defaults, and compare its fitted line with the one in The NumPy Package. The script's review block checks each number under matplotlib 3.10.1 and 3.11.2, which agree.

Problem 1 (from data to pixels by hand). Derive the display position (335.3, 165.8) of the data point (50 years, 120 mm Hg), and its new height 169.5 after ax.set_ylim(60, 250).

Solution. Three defaults fix the transform. First, the axis limits: autoscaling widens the data range by axes.xmargin and axes.ymargin, 0.05 of the range at each end. Ages run from 18 to 80, a range of 62, so the limits are $18 - 3.1 = 14.9$ and $80 + 3.1 = 83.1$. Mean systolic pressures run from 72.67 to 238.0, a range of 165.33, so the limits are 64.40 and 246.27. Second, the Axes' place in the Figure: the subplot parameters put its left edge at 0.125 of the figure's width, its right edge at 0.9, its bottom at 0.11 and its top at 0.88. Third, the Figure's size in pixels: 6.4 by 4.8 inches at 100 dots per inch is 640 by 480. A data value maps linearly within the limits, then into the Axes' fraction of the figure, then to pixels:

$$x_{\text{px}} = 640\left(0.125 + 0.775 \times \frac{50 - 14.9}{83.1 - 14.9}\right) = 640 \times 0.52386 = 335.3,$$

$$y_{\text{px}} = 480\left(0.11 + 0.77 \times \frac{120 - 64.40}{246.27 - 64.40}\right) = 480 \times 0.34540 = 165.8.$$

The Axes' top-right corner is $(0.9 \times 640, 0.88 \times 480) = (576.0, 422.4)$, as the body reports. With the limits 60 and 250, the vertical fraction becomes $(120 - 60)/190 = 0.31579$, and $y_{\text{px}} = 480(0.11 + 0.77 \times 0.31579) = 169.5$; the horizontal position does not change. The script computes both by this formula and checks them against ax.transData. The calculation shows what the transform depends on (the limits, the subplot parameters, the figure size and the dpi) and therefore what invalidates a position computed earlier: changing any of them.

Problem 2 (accounting for the 144 Artists). Account for the 56 Line2D and 46 Text objects in the scatter plot, and for the total of 144.

Solution. The figure has 9 ticks on each axis, 18 in all. Each Tick holds three lines (a tick mark on each side of the Axes, tick1line and tick2line, and a grid line) and two labels (label1 and label2, one per side), whether or not they are visible. That gives $18 \times 3 = 54$ lines and $18 \times 2 = 36$ texts. The other lines are the fitted line and its sample in the legend: $54 + 1 + 1 = 56$. The other texts are each Axis's label and offset text (4), the Axes' three titles, center, left and right (3), and the legend's two entry labels and its empty title (3): $36 + 4 + 3 + 3 = 46$. The remaining 42 objects are the 18 XTick and YTick containers, the 4 spines, the 2 PathCollection objects (the scatter and its legend marker), the legend's 10 layout boxes (3 TextArea, 3 HPacker, 2 DrawingArea and 2 VPacker), 2 Rectangle objects (the Figure's and the Axes' backgrounds) and 1 FancyBboxPatch (the legend's frame), and the Legend, XAxis, YAxis, Axes and Figure themselves: $18 + 4 + 2 + 10 + 3 + 5 = 42$, and $56 + 46 + 42 = 144$. The script checks the line and text totals against their sources. Most of the Artists are invisible bookkeeping, and the 5,247 points are one of them.

Problem 3 (two least-squares lines for the same adults). This article's fitted line is $100.09 + 0.527 \times \text{age}$; the NumPy article's is $100.17 + 0.525 \times \text{age}$. Which is right?

Solution. Both, for different samples. This article fits the 5,247 adults with an age and a systolic pressure. The NumPy article fits the 5,232 who also have a diastolic pressure, because its array X holds all three columns and drops a row missing any of them. The script finds that the 15 adults excluded from the second sample have mean age 64.3 and mean systolic pressure 143.4, both above the averages, and fits both lines to confirm the two sets of coefficients. What moves the line is where those 15 points sit: at a mean age of 64.3, above the sample's mean age of 49.87, the first line predicts 133.95 (from its unrounded coefficients), and their mean pressure of 143.4 lies well above it. Points above the line to the right of the mean age pull the slope up, so removing them lowers it from 0.527 to 0.525. The intercept follows from $\bar{y} - b\bar{x}$ for the remaining adults, which is why it rises to 100.17 (Simple Linear Regression derives that formula and the slope's as least-squares estimates). Neither line is an error. The difference is the effect of a dropna over different columns, the kind of silent choice the pandas article recommends recording with a count.

Open questions

  • How large do this site's SVG figures get, and when does rasterizing pay? Measuring every figure's file size against its number of marks, before and after set_rasterized(True) on its largest collection, would give a rule for when to rasterize.
  • Do SVGs from different matplotlib versions differ only in bytes or also in appearance? The hashes differ between 3.10.1 and 3.11.2. Rendering both versions of each figure to pixels and comparing them would show whether a version change alters what readers see.
  • How much memory does an unclosed figure hold? The script showed that pyplot keeps all 25 figures. Measuring process memory as figures of this scatter's size accumulate would show how soon a loop over groups exhausts a small machine, such as the site's 1.75 GB server.

Where it leads

This article established matplotlib's object model: Artists in a tree, two interfaces over it, transforms from data to pixels, backends, saving and configuration. It ends the Python unit. The next unit, Probability and Statistics, begins with Data Collection and Sampling, on where data like the NHANES files come from and what their design allows. The design questions of what to draw are taken up in Best Practices for Visualizing Data.

References

Reviewed: verified, 23 Nov 2026 · citations checked, 23 Nov 2026 · editorial review, 23 Nov 2026 · 5 revisions