Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 57 ยท 3D, Animation and Advanced

Transforms and the Artist Layer

Learn data, axes, figure and display coordinates, transData and blended transforms, custom Artists, collections, zorder and path effects, and why artists drive speed.

Every visible thing in a Matplotlib figure is an Artist: lines, text, ticks, patches, images, even the Axes and the Figure. And every artist has a transform that converts its coordinates (the numbers you gave it) into pixels on the screen. Once you understand these two ideas, the rest of the library stops feeling like magic: annotations land where you expect, shapes stay circular, and slow plots become easy to explain.

This lesson looks under the hood: the four coordinate systems, how to combine them, how to write a small custom artist, how collections draw thousands of shapes cheaply, how draw order (zorder) works, and how path effects add outlines and shadows. It builds on the anatomy of a figure and shapes and patches.

Four coordinate systems

Data Your numbers. ax.transData.
Axes 0 to 1 inside the Axes. ax.transAxes.
Figure 0 to 1 across the figure. fig.transFigure.
Display Pixels from the bottom-left.

A transform is a function from one system to the next.

1 / 2

The four coordinate systems

Matplotlib can place the same thing in four coordinate systems:

Name Transform Range Use it when
Data ax.transData your axis limits marking a point of your data
Axes ax.transAxes (0, 0) bottom-left to (1, 1) top-right of the Axes a label in a fixed corner, whatever the data
Figure fig.transFigure (0, 0) to (1, 1) across the figure titles or logos spanning several Axes
Display None or IdentityTransform() pixels rarely, mostly for events and debugging

Many functions accept a transform= argument. ax.text(0.5, 0.95, "Title", transform=ax.transAxes) places text at the top middle of the Axes no matter how you zoom. You can convert by hand: ax.transData.transform((x, y)) returns pixels, and ax.transData.inverted().transform((px, py)) converts pixels back to data.

Python The same point in four coordinate systems

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All four labels sit where their coordinate system says. If you resize or zoom, the data-based ones move with the data, and the axes-based and figure-based ones stay put.

Blended transforms

Sometimes you want x in data units and y in Axes units: a band covering a range of x over the full height, or a label pinned to the top edge above a chosen x. matplotlib.transforms.blended_transform_factory(x_transform, y_transform) builds exactly that. (ax.get_xaxis_transform() and ax.get_yaxis_transform() are shortcuts for the two common blends.) This is how axvspan and axvline work.

You can also add transforms. ax.transData + ScaledTranslation(dx, dy, fig.dpi_scale_trans) shifts anything by a distance measured in inches (or points) from a data location, which is how offset labels stay a fixed distance away from a marker even as the figure is resized.

Python Blended transforms and a fixed-size circle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The red circle looks like an ellipse because the data units on x and y are not equally long on the screen. The green one is defined in Axes fractions, which are also unequal here. If you need a true circle regardless of limits, draw it in display or points units, or call ax.set_aspect("equal").

Writing a small custom Artist

All artists share one contract: they have a draw(renderer) method. Matplotlib walks the artist tree (Figure, then Axes, then children) and calls draw on each visible artist, sorted by zorder. To make your own, subclass matplotlib.artist.Artist, store what you need, and talk to the renderer. A GraphicsContext (renderer.new_gc()) carries colours and line widths; renderer.draw_path(gc, path, transform) draws a Path.

Python
from matplotlib.artist import Artist
from matplotlib.path import Path

class Crosshair(Artist):
    def __init__(self, x, y, size=0.5, color="crimson"):
        super().__init__()
        self.x, self.y, self.size, self.color = x, y, size, color

    def draw(self, renderer):
        if not self.get_visible():
            return
        gc = renderer.new_gc()
        gc.set_foreground(self.color)
        gc.set_linewidth(2)
        s = self.size
        path = Path([(self.x - s, self.y), (self.x + s, self.y),
                     (self.x, self.y - s), (self.x, self.y + s)],
                    [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO])
        renderer.draw_path(gc, path, self.axes.transData)
        gc.restore()
        self.stale = False
Python A Crosshair artist added to an Axes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In practice you rarely write artists from scratch. Subclassing an existing one (a Patch, Line2D or Text) and overriding one method is more common, and so is composing existing artists. But knowing the contract makes the library's behaviour predictable.

Collections: many shapes, one artist

Each artist costs a certain amount of Python work per draw. A plot with 5,000 separate ax.plot lines creates 5,000 Line2D artists, and the drawing time is dominated by that overhead. A collection stores many shapes in one artist and sends them to the renderer together.

  • LineCollection(segments): a list of line segments (each an array of points), with per-line colours and widths.
  • PolyCollection(verts): many filled polygons, with per-polygon colours.
  • PatchCollection(patches), EllipseCollection, PathCollection (what scatter returns) and QuadMesh (what pcolormesh returns) are siblings.

Collections are not added with plot: use ax.add_collection(coll), then ax.autoscale_view() because collections do not trigger autoscaling by themselves.

Python 400 lines as one LineCollection, plus a PolyCollection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first panel has one artist for 400 lines. Colouring a collection by an array (array=... with a cmap) is also how you map a number onto each member and get a colorbar.

zorder and draw order

Within an Axes, artists are drawn in increasing zorder; ties are drawn in the order they were added. Defaults are: patches and collections 1, lines 2, text 3, legend 5, and gridlines and ticks 1.5 (between patches and lines, from the default axisbelow="line"). Set zorder= on any artist to move it forward or backward. A very common use is putting a highlighted point above a line, or drawing a shaded band behind everything with a low value. Artists in different Axes are drawn Axes by Axes, so zorder does not interleave across Axes (use ax.set_zorder to reorder whole Axes, as twin axes do).

Path effects: outlines, shadows and strokes

matplotlib.patheffects re-draws an artist several times with modifications. withStroke(linewidth=3, foreground="white") gives text a halo that keeps it readable on a busy background, SimpleLineShadow and SimplePatchShadow add drop shadows, and Normal() draws the original. Assign them with artist.set_path_effects([...]) or the path_effects= keyword.

Python zorder and path effects together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why performance depends on artists

Rendering cost grows with the number of artists and with the number of points. A few guidelines follow directly from what you have just learned:

  • Draw many similar shapes with one collection, not a loop of plot or add_patch calls.
  • One ax.plot with a 2D array draws many lines as many artists. Use a LineCollection when there are hundreds.
  • ax.scatter is one artist for any number of points, but a plain plot(..., "o") with one Line2D is faster when all markers are identical.
  • Count what is on the Axes with len(ax.get_children()), and see what has changed with the stale flag.
  • Heavier artists (path effects, transparency, thousands of text labels) multiply drawing time. More on this in Plotting Large Data Fast.

ax.get_children() and fig.findobj() list artists. When a plot feels slow, counting the artists often points straight at the cause.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which transform places text at a fixed corner of an Axes regardless of the data limits?

    transAxes uses fractions of the Axes box, (0, 0) bottom-left to (1, 1) top-right, so the text stays put when data limits change.
  2. 2. What does blended_transform_factory(ax.transData, ax.transAxes) produce?

    The first argument is used for x and the second for y. This is how bands that span the full height at chosen x positions are built.
  3. 3. Why is one LineCollection with 400 lines faster than 400 calls to ax.plot?

    Each plot call creates a Line2D artist with its own overhead. A collection passes all segments to the renderer together.
  4. 4. In what order are artists drawn within one Axes?

    Lower zorder values are drawn first, so higher values appear on top. Artists with the same zorder follow insertion order.
  5. 5. What is the one method every custom Artist must provide to appear on screen?

    Matplotlib walks the artist tree and calls draw(renderer) on every visible artist.

Summary

  • Every visible object is an Artist with a transform that maps its coordinates to display pixels.
  • The four systems are data (ax.transData), axes fractions (ax.transAxes), figure fractions (fig.transFigure) and display pixels; transform and inverted() convert between them.
  • blended_transform_factory mixes systems (x in data, y in axes), and offset transforms keep distances fixed in points.
  • A custom artist implements draw(renderer) using a graphics context and renderer.draw_path.
  • Collections (LineCollection, PolyCollection, PatchCollection) draw many shapes as one artist; add them with add_collection and autoscale_view.
  • zorder sets draw order (low first); patheffects add halos and shadows.
  • Fewer artists means faster drawing.

Next, learn to export your work in Saving Figures.