artists
Artist tutorial
Using Artist objects to render on the canvas.
There are three layers to the matplotlib API.
- the
matplotlib.backend_bases.FigureCanvasis the area onto which
the figure is drawn - the
matplotlib.backend_bases.Rendereris
the object which knows how to draw on theFigureCanvas - and the
matplotlib.artist.Artistis the object that knows how to use
a renderer to paint onto the canvas.
The FigureCanvas andRenderer handle all the details of
talking to user interface toolkits like wxPython or drawing languages like PostScript®, and
the Artist handles all the high level constructs like representing
and laying out the figure, text, and lines. The typical user will
spend 95% of their time working with the Artists.
There are two types of Artists: primitives and containers. The primitives
represent the standard graphical objects we want to paint onto our canvas:Line2D, Rectangle,Text, AxesImage, etc., and
the containers are places to put them (Axis,Axes and Figure). The
standard use is to create a Figure instance, use
the Figure to create one or more Axes orSubplot instances, and use the Axes instance
helper methods to create the primitives. In the example below, we create aFigure instance using matplotlib.pyplot.figure(), which is a
convenience method for instantiating Figure instances and connecting them
with your user interface or drawing toolkit FigureCanvas. As we will
discuss below, this is not necessary – you can work directly with PostScript,
PDF Gtk+, or wxPython FigureCanvas instances, instantiate your Figures
directly and connect them yourselves – but since we are focusing here on theArtist API we’ll let pyplot handle some of those details
for us:
1 | import matplotlib.pyplot as plt |
The Axes is probably the most important
class in the matplotlib API, and the one you will be working with most
of the time. This is because the Axes is the plotting area into
which most of the objects go, and the Axes has many special helper
methods (plot(),text(),hist(),imshow()) to create the most common
graphics primitives (Line2D,Text,Rectangle,Image, respectively). These helper methods
will take your data (e.g., numpy arrays and strings) and create
primitive Artist instances as needed (e.g., Line2D), add them to
the relevant containers, and draw them when requested. Most of you
are probably familiar with the Subplot,
which is just a special case of an Axes that lives on a regular
rows by columns grid of Subplot instances. If you want to create
an Axes at an arbitrary location, simply use theadd_axes() method which takes a list
of [left, bottom, width, height] values in 0-1 relative figure
coordinates:
1 | fig2 = plt.figure() |
Continuing with our example:
1 | import numpy as np |
In this example, ax is the Axes instance created by thefig.add_subplot call above (remember Subplot is just a
subclass of Axes) and when you call ax.plot, it creates aLine2D instance and adds it to the Axes.lines list. In the interactive ipython session below, you can see that theAxes.lines list is length one and contains the same line that was
returned by the line, = ax.plot... call:
1 | In [101]: ax.lines[0] |
If you make subsequent calls to ax.plot (and the hold state is “on”
which is the default) then additional lines will be added to the list.
You can remove lines later simply by calling the list methods; either
of these will work:
1 | del ax.lines[0] |
The Axes also has helper methods to configure and decorate the x-axis
and y-axis tick, tick labels and axis labels:
1 | xtext = ax.set_xlabel('my xdata') # returns a Text instance |
When you call ax.set_xlabel,
it passes the information on the Text
instance of the XAxis. Each Axes
instance contains an XAxis and aYAxis instance, which handle the layout and
drawing of the ticks, tick labels and axis labels.
Try creating the figure below.
1 | import numpy as np |

Customizing your objects
Every element in the figure is represented by a matplotlibArtist, and each has an extensive list of
properties to configure its appearance. The figure itself contains aRectangle exactly the size of the figure,
which you can use to set the background color and transparency of the
figures. Likewise, each Axes bounding box
(the standard white box with black edges in the typical matplotlib
plot, has a Rectangle instance that determines the color,
transparency, and other properties of the Axes. These instances are
stored as member variables Figure.patch and Axes.patch (“Patch” is a name inherited from
MATLAB, and is a 2D “patch” of color on the figure, e.g., rectangles,
circles and polygons). Every matplotlib Artist has the following
properties
Property
Description
alpha
The transparency - a scalar from 0-1
animated
A boolean that is used to facilitate animated drawing
axes
The axes that the Artist lives in, possibly None
clip_box
The bounding box that clips the Artist
clip_on
Whether clipping is enabled
clip_path
The path the artist is clipped to
contains
A picking function to test whether the artist contains the pick point
figure
The figure instance the artist lives in, possibly None
label
A text label (e.g., for auto-labeling)
picker
A python object that controls object picking
transform
The transformation
visible
A boolean whether the artist should be drawn
zorder
A number which determines the drawing order
rasterized
Boolean; Turns vectors into raster graphics (for compression & eps transparency)
Each of the properties is accessed with an old-fashioned setter or
getter (yes we know this irritates Pythonistas and we plan to support
direct access via properties or traits but it hasn’t been done yet).
For example, to multiply the current alpha by a half:
1 | a = o.get_alpha() |
If you want to set a number of properties at once, you can also use
the set method with keyword arguments. For example:
1 | o.set(alpha=0.5, zorder=2) |
If you are working interactively at the python shell, a handy way to
inspect the Artist properties is to use thematplotlib.artist.getp() function (simplygetp() in pyplot), which lists the properties
and their values. This works for classes derived from Artist as
well, e.g., Figure and Rectangle. Here are the Figure rectangle
properties mentioned above:
1 | In [149]: matplotlib.artist.getp(fig.patch) |
The docstrings for all of the classes also contain the Artist
properties, so you can consult the interactive “help” or the
matplotlib.artist for a listing of properties for a given object.
Object containers
Now that we know how to inspect and set the properties of a given
object we want to configure, we need to know how to get at that object.
As mentioned in the introduction, there are two kinds of objects:
primitives and containers. The primitives are usually the things you
want to configure (the font of a Text
instance, the width of a Line2D) although
the containers also have some properties as well – for example theAxes Artist is a
container that contains many of the primitives in your plot, but it
also has properties like the xscale to control whether the xaxis
is ‘linear’ or ‘log’. In this section we’ll review where the various
container objects store the Artists that you want to get at.
Figure container
The top level container Artist is thematplotlib.figure.Figure, and it contains everything in the
figure. The background of the figure is aRectangle which is stored inFigure.patch. As
you add subplots (add_subplot()) and
axes (add_axes()) to the figure
these will be appended to the Figure.axes. These are also returned by the
methods that create them:
1 | In [156]: fig = plt.figure() |
Because the figure maintains the concept of the “current axes” (seeFigure.gca andFigure.sca) to support the
pylab/pyplot state machine, you should not insert or remove axes
directly from the axes list, but rather use theadd_subplot() andadd_axes() methods to insert, and thedelaxes() method to delete. You are
free however, to iterate over the list of axes or index into it to get
access to Axes instances you want to customize. Here is an
example which turns all the axes grids on:
1 | for ax in fig.axes: |
The figure also has its own text, lines, patches and images, which you
can use to add primitives directly. The default coordinate system for
the Figure will simply be in pixels (which is not usually what you
want) but you can control this by setting the transform property of
the Artist you are adding to the figure.
More useful is “figure coordinates” where (0, 0) is the bottom-left of
the figure and (1, 1) is the top-right of the figure which you can
obtain by setting the Artist transform to fig.transFigure:
1 | import matplotlib.lines as lines |

Here is a summary of the Artists the figure contains
Figure attribute
Description
axes
A list of Axes instances (includes Subplot)
patch
The Rectangle background
images
A list of FigureImages patches - useful for raw pixel display
legends
A list of Figure Legend instances (different from Axes.legends)
lines
A list of Figure Line2D instances (rarely used, see Axes.lines)
patches
A list of Figure patches (rarely used, see Axes.patches)
texts
A list Figure Text instances
Axes container
The matplotlib.axes.Axes is the center of the matplotlib
universe – it contains the vast majority of all the Artists used
in a figure with many helper methods to create and add theseArtists to itself, as well as helper methods to access and
customize the Artists it contains. Like theFigure, it contains aPatchpatch which is aRectangle for Cartesian coordinates and aCircle for polar coordinates; this patch
determines the shape, background and border of the plotting region:
1 | ax = fig.add_subplot(111) |
When you call a plotting method, e.g., the canonicalplot() and pass in arrays or lists of
values, the method will create a matplotlib.lines.Line2D()
instance, update the line with all the Line2D properties passed as
keyword arguments, add the line to the Axes.lines container, and returns it to you:
1 | In [213]: x, y = np.random.rand(2, 100) |
plot returns a list of lines because you can pass in multiple x, y
pairs to plot, and we are unpacking the first element of the length
one list into the line variable. The line has been added to theAxes.lines list:
1 | In [229]: print(ax.lines) |
Similarly, methods that create patches, likebar() creates a list of rectangles, will
add the patches to the Axes.patches list:
1 | In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50, facecolor='yellow') |
You should not add objects directly to the Axes.lines orAxes.patches lists unless you know exactly what you are doing,
because the Axes needs to do a few things when it creates and adds
an object. It sets the figure and axes property of the Artist, as
well as the default Axes transformation (unless a transformation
is set). It also inspects the data contained in the Artist to
update the data structures controlling auto-scaling, so that the view
limits can be adjusted to contain the plotted data. You can,
nonetheless, create objects yourself and add them directly to theAxes using helper methods likeadd_line() andadd_patch(). Here is an annotated
interactive session illustrating what is going on:
1 | In [262]: fig, ax = plt.subplots() |
There are many, many Axes helper methods for creating primitiveArtists and adding them to their respective containers. The table
below summarizes a small sampling of them, the kinds of Artist they
create, and where they store them
Helper method
Artist
Container
ax.annotate - text annotations
Annotate
ax.texts
ax.bar - bar charts
Rectangle
ax.patches
ax.errorbar - error bar plots
Line2D and Rectangle
ax.lines and ax.patches
ax.fill - shared area
Polygon
ax.patches
ax.hist - histograms
Rectangle
ax.patches
ax.imshow - image data
AxesImage
ax.images
ax.legend - axes legends
Legend
ax.legends
ax.plot - xy plots
Line2D
ax.lines
ax.scatter - scatter charts
PolygonCollection
ax.collections
ax.text - text
Text
ax.texts
In addition to all of these Artists, the Axes contains two
important Artist containers: the XAxis
and YAxis, which handle the drawing of the
ticks and labels. These are stored as instance variablesxaxis andyaxis. The XAxis and YAxis
containers will be detailed below, but note that the Axes contains
many helper methods which forward calls on to theAxis instances so you often do not need to
work with them directly unless you want to. For example, you can set
the font color of the XAxis ticklabels using the Axes helper
method:
1 | for label in ax.get_xticklabels(): |
Below is a summary of the Artists that the Axes contains
Axes attribute
Description
artists
A list of Artist instances
patch
Rectangle instance for Axes background
collections
A list of Collection instances
images
A list of AxesImage
legends
A list of Legend instances
lines
A list of Line2D instances
patches
A list of Patch instances
texts
A list of Text instances
xaxis
matplotlib.axis.XAxis instance
yaxis
matplotlib.axis.YAxis instance
Axis containers
The matplotlib.axis.Axis instances handle the drawing of the
tick lines, the grid lines, the tick labels and the axis label. You
can configure the left and right ticks separately for the y-axis, and
the upper and lower ticks separately for the x-axis. The Axis
also stores the data and view intervals used in auto-scaling, panning
and zooming, as well as the Locator andFormatter instances which control where
the ticks are placed and how they are represented as strings.
Each Axis object contains a label attribute
(this is what pyplot modifies in calls toxlabel() and ylabel()) as
well as a list of major and minor ticks. The ticks areXTick and YTick instances,
which contain the actual line and text primitives that render the ticks and
ticklabels. Because the ticks are dynamically created as needed (e.g., when
panning and zooming), you should access the lists of major and minor ticks
through their accessor methods get_major_ticks()
and get_minor_ticks(). Although the ticks contain
all the primitives and will be covered below, Axis instances have accessor
methods that return the tick lines, tick labels, tick locations etc.:
1 | fig, ax = plt.subplots() |

1 | axis.get_ticklabels() |
note there are twice as many ticklines as labels because by
1 | axis.get_ticklines() |
by default you get the major ticks back
1 | axis.get_ticklines() |
but you can also ask for the minor ticks
1 | axis.get_ticklines(minor=True) |

Tick containers
The matplotlib.axis.Tick is the final container object in our
descent from the Figure to theAxes to the Axis
to the Tick. The Tick contains the tick
and grid line instances, as well as the label instances for the upper
and lower ticks. Each of these is accessible directly as an attribute
of the Tick.
Tick attribute
Description
tick1line
Line2D instance
tick2line
Line2D instance
gridline
Line2D instance
label1
Text instance
label2
Text instance
Here is an example which sets the formatter for the right side ticks with
dollar signs and colors them green on the right side of the yaxis
1 | import matplotlib.ticker as ticker |





