Almost all objects you interact with on a Matplotlib plot are called "Artist"
(and are subclasses of the Artist class). Figure
and Axes are Artists, and generally contain
Axis Artists and Artists that contain data or annotation information.
Creating Artists
Usually we do not instantiate Artists directly, but rather use a plotting
method on Axes. Some examples of plotting methods and the Artist
object they create is given below:
As an example, we can save the Line2D Artist returned from axes.Axes.plot:
In [209]: importmatplotlib.pyplotaspltIn [210]: importmatplotlib.artistasmartistIn [211]: importnumpyasnpIn [212]: fig,ax=plt.subplots()In [213]: x,y=np.random.rand(2,100)In [214]: lines=ax.plot(x,y,'-',label='example')In [215]: print(lines)[<matplotlib.lines.Line2D at 0xd378b0c>]
Note that plot returns a _list_ of lines because you can pass in multiple x,
y pairs to plot. The line has been added to the Axes, and we can retrieve the
Artist via get_lines():
In [216]: print(ax.get_lines())<a list of 1 Line2D objects>In [217]: print(ax.get_lines()[0])Line2D(example)
Changing Artist properties
Getting the lines object gives us access to all the properties of the
Line2D object. So if we want to change the linewidth after the fact, we can do so using Artist.set.
In addition to styling properties like color and linewidth, the Line2D
object has a data property. You can set the data after the line has been
created using Line2D.set_data. This is often used for Animations, where the
same line is shown evolving over time (see Animations using Matplotlib)
Not all Artists have helper methods, or you may want to use a low-level method
for some reason. For example the patches.Circle Artist does not have a
helper, but we can still create and add to an Axes using the
axes.Axes.add_artist method:
The Circle takes the center and radius of the Circle as arguments to its
constructor; optional arguments are passed as keyword arguments.
Note that when we add an Artist manually like this, it doesn't necessarily
adjust the axis limits like most of the helper methods do, so the Artists can
be clipped, as is the case above for the clipped_circle patch.
Sometimes we want to remove an Artist from a figure without re-specifying the
whole figure from scratch. Most Artists have a usable remove method that
will remove the Artist from its Axes list. For instance lines[0].remove()
would remove the Line2D artist created in the example above.