Annotations are graphical elements, often pieces of text, that explain, add
context to, or otherwise highlight some portion of the visualized data.
annotate supports a number of coordinate systems for flexibly
positioning data and annotations relative to each other and a variety of
options of for styling the text. Axes.annotate also provides an optional arrow
from the text to the data and this arrow can be styled in various ways.
text can also be used for simple text annotation, but does not
provide as much flexibility in positioning and styling as annotate.
Basic annotation
In an annotation, there are two points to consider: the location of the data
being annotated xy and the location of the annotation text xytext. Both
of these arguments are (x,y) tuples:
In this example, both the xy (arrow tip) and xytext locations
(text location) are in data coordinates. There are a variety of other
coordinate systems one can choose -- you can specify the coordinate
system of xy and xytext with one of the following strings for
xycoords and textcoords (default is 'data')
argument
coordinate system
'figure points'
points from the lower left corner of the figure
'figure pixels'
pixels from the lower left corner of the figure
'figure fraction'
(0, 0) is lower left of figure and (1, 1) is upper right
'axes points'
points from lower left corner of the Axes
'axes pixels'
pixels from lower left corner of the Axes
'axes fraction'
(0, 0) is lower left of Axes and (1, 1) is upper right
'data'
use the axes data coordinate system
The following strings are also valid arguments for textcoords
argument
coordinate system
'offset points'
offset (in points) from the xy value
'offset pixels'
offset (in pixels) from the xy value
For physical coordinate systems (points or pixels) the origin is the
bottom-left of the figure or Axes. Points are
typographic points
meaning that they are a physical unit measuring 1/72 of an inch. Points and
pixels are discussed in further detail in Plotting in physical coordinates.
Annotating data
This example places the text coordinates in fractional axes coordinates:
Annotations can be positioned relative to an Artist instance by passing
that Artist in as xycoords. Then xy is interpreted as a fraction of the
Artist's bounding box.
Here the annotation is placed at position (.5,.5) relative to the arrow's
lower left corner and is vertically and horizontally at that position.
Vertically, the bottom aligns to that reference point so that the label
is above the line. For an example of chaining annotation Artists, see the
Artist section of
Coordinate systems for annotations.
Annotating with arrows
You can enable drawing of an arrow from the text to the annotated point
by giving a dictionary of arrow properties in the optional keyword
argument arrowprops.
arrowprops key
description
width
the width of the arrow in points
frac
the fraction of the arrow length occupied by the head
headwidth
the width of the base of the arrow head in points
shrink
move the tip and base some percent away from
the annotated point and text
In the example below, the xy point is in the data coordinate system
since xycoords defaults to 'data'. For a polar Axes, this is in
(theta, radius) space. The text in this example is placed in the
fractional figure coordinate system. matplotlib.text.Text
keyword arguments like horizontalalignment, verticalalignment and
fontsize are passed from annotate to the
Text instance.
Annotations can be positioned at a relative offset to the xy input to
annotation by setting the textcoords keyword argument to 'offsetpoints'
or 'offsetpixels'.
The return value is a FancyBboxPatch; patch properties
(facecolor, edgewidth, etc.) can be accessed and modified as usual.
FancyBboxPatch.set_boxstyle sets the box shape:
bb.set_boxstyle("rarrow",pad=0.6)
The attribute arguments can also be specified within the style
name with separating comma:
bb.set_boxstyle("rarrow, pad=0.6")
Defining custom box styles
Custom box styles can be implemented as a function that takes arguments specifying
both a rectangular box and the amount of "mutation", and returns the "mutated" path.
The specific signature is the one of custom_box_style below.
Here, we return a new path which adds an "arrow" shape on the left of the box.
The custom box style can then be used by passing
bbox=dict(boxstyle=custom_box_style,...) to Axes.text.
An arrow connecting xy to xytext can be optionally drawn by
specifying the arrowprops argument. To draw only an arrow, use
empty string as the first argument:
There are classes of artists that can be placed at an anchored
location in the Axes. A common example is the legend. This type
of artist can be created by using the OffsetBox class. A few
predefined classes are available in matplotlib.offsetbox and in
mpl_toolkits.axes_grid1.anchored_artists.
frommatplotlib.offsetboximport
Using an Artist as an annotation
AnnotationBbox uses artists in OffsetBox container artists as the annotations
and supports positioning these annotations using the same coordinate systems as the
other annotation methods. For more examples, see
Artists as annotations
Matplotlib Annotations support several types of coordinate systems. The
examples in Basic annotation used the data coordinate system;
Some others more advanced options are:
Transforms map coordinates into different coordinate systems, usually the
display coordinate system. See Transformations Tutorial for a detailed
explanation. Here Transform objects are used to identify the coordinate
system of the corresponding points. For example, the Axes.transAxes
transform positions the annotation relative to the Axes coordinates; therefore
using it is identical to setting the coordinate system to "axes fraction":
Another commonly used Transform instance is Axes.transData. This
transform is the coordinate system of the data plotted in the Axes. In this
example, it is used to draw an arrow between related data points in two
Axes. We have passed an empty text because in this case, the annotation
connects data points.
A callable object that takes the renderer instance as single argument, and
returns either a Transform or a BboxBase. For example, the return
value of Artist.get_window_extent is a bbox, so this method is identical
to (2) passing in the artist:
Blended coordinate specification
A blended pair of coordinate specifications -- the first for the
x-coordinate, and the second is for the y-coordinate. For example, x=0.5 is
in data coordinates, and y=1 is in normalized axes coordinates:
Sometimes, you want your annotation with some "offset points", not from the
annotated point but from some other point or artist. text.OffsetFrom is
a helper for such cases.
ConnectionPatch is like an annotation without text. While annotate
is sufficient in most situations, ConnectionPatch is useful when you want
to connect points in different Axes. For example, here we connect the point
xy in the data coordinates of ax1 to point xy in the data coordinates
of ax2:
Here, we added the ConnectionPatch to the figure
(with add_artist) rather than to either Axes. This ensures that
the ConnectionPatch artist is drawn on top of both Axes, and is also necessary
when using constrained_layout
for positioning the Axes.
Likewise, custom box styles can be implemented as classes that implement
__call__.
The classes can then be registered into the BoxStyle._style_list dict,
which allows specifying the box style as a string,
bbox=dict(boxstyle="registered_name,param=value,...",...).
Note that this registration relies on internal APIs and is therefore not
officially supported.
frommatplotlib.patchesimportBoxStyleclassMyStyle:"""A simple box."""def__init__(self,pad=0.3):""" The arguments must be floats and have default values. Parameters ---------- pad : float amount of padding """self.pad=padsuper().__init__()def__call__(self,x0,y0,width,height,mutation_size):""" Given the location and size of the box, return the path of the box around it. Rotation is automatically taken care of. Parameters ---------- x0, y0, width, height : float Box location and size. mutation_size : float Reference scale for the mutation, typically the text font size. """# paddingpad=mutation_size*self.pad# width and height with padding addedwidth=width+2*padheight=height+2*pad# boundary of the padded boxx0,y0=x0-pad,y0-padx1,y1=x0+width,y0+height# return the new pathreturnPath([(x0,y0),(x1,y0),(x1,y1),(x0,y1),(x0-pad,(y0+y1)/2),(x0,y0),(x0,y0)],closed=True)BoxStyle._style_list["angled"]=MyStyle# Register the custom style.fig,ax=plt.subplots(figsize=(3,3))ax.text(0.5,0.5,"Test",size=30,va="center",ha="center",rotation=30,bbox=dict(boxstyle="angled,pad=0.5",alpha=0.2))delBoxStyle._style_list["angled"]# Unregister it.
Similarly, you can define a custom ConnectionStyle and a custom ArrowStyle. View
the source code at patches to learn how each class is defined.
The creation of the connecting path between two points is controlled by
connectionstyle key and the following styles are available:
Name
Attrs
angle
angleA=90,angleB=0,rad=0.0
angle3
angleA=90,angleB=0
arc
angleA=0,angleB=0,armA=None,armB=None,rad=0.0
arc3
rad=0.0
bar
armA=0.0,armB=0.0,fraction=0.3,angle=None
Note that "3" in angle3 and arc3 is meant to indicate that the
resulting path is a quadratic spline segment (three control
points). As will be discussed below, some arrow style options can only
be used when the connecting path is a quadratic spline.
The behavior of each connection style is (limitedly) demonstrated in the
example below. (Warning: The behavior of the bar style is currently not
well-defined and may be changed in the future).
The connecting path (after clipping and shrinking) is then mutated to
an arrow patch, according to the given arrowstyle:
Name
Attrs
-
None
->
head_length=0.4,head_width=0.2
-[
widthB=1.0,lengthB=0.2,angleB=None
|-|
widthA=1.0,widthB=1.0
-|>
head_length=0.4,head_width=0.2
<-
head_length=0.4,head_width=0.2
<->
head_length=0.4,head_width=0.2
<|-
head_length=0.4,head_width=0.2
<|-|>
head_length=0.4,head_width=0.2
fancy
head_length=0.4,head_width=0.4,tail_width=0.4
simple
head_length=0.5,head_width=0.5,tail_width=0.2
wedge
tail_width=0.3,shrink_factor=0.5
Some arrowstyles only work with connection styles that generate a
quadratic-spline segment. They are fancy, simple, and wedge.
For these arrow styles, you must use the "angle3" or "arc3" connection
style.
If the annotation string is given, the patch is set to the bbox patch
of the text by default.
By default, the starting point is set to the center of the text
extent. This can be adjusted with relpos key value. The values
are normalized to the extent of the text. For example, (0, 0) means
lower-left corner and (1, 1) means top-right.
The loc keyword has same meaning as in the legend command.
A simple application is when the size of the artist (or collection of
artists) is known in pixel size during the time of creation. For
example, If you want to draw a circle with fixed size of 20 pixel x 20
pixel (radius = 10 pixel), you can utilize
AnchoredDrawingArea. The instance
is created with a size of the drawing area (in pixels), and arbitrary artists
can be added to the drawing area. Note that the extents of the artists that are
added to the drawing area are not related to the placement of the drawing
area itself. Only the initial size matters.
The artists that are added to the drawing area should not have a
transform set (it will be overridden) and the dimensions of those
artists are interpreted as a pixel coordinate, i.e., the radius of the
circles in above example are 10 pixels and 5 pixels, respectively.
Sometimes, you want your artists to scale with the data coordinate (or
coordinates other than canvas pixels). You can use
AnchoredAuxTransformBox class.
This is similar to
AnchoredDrawingArea except that
the extent of the artist is determined during the drawing time respecting the
specified transform.
The ellipse in the example below will have width and height
corresponding to 0.1 and 0.4 in data coordinates and will be
automatically scaled when the view limits of the Axes change.
Another method of anchoring an artist relative to a parent Axes or anchor
point is via the bbox_to_anchor argument of AnchoredOffsetbox. This
artist can then be automatically positioned relative to another artist using
HPacker and VPacker:
Note that you must ensure that the extent of the coordinate artist (an1 in
this example) is determined before an2 gets drawn. Usually, this means
that an2 needs to be drawn after an1. The base class for all bounding
boxes is BboxBase
Any of the supported coordinate systems can be used in a blended
specification. For example, the text "Anchored to 1 & 2" is positioned
relative to the two Text Artists:
fig,ax=plt.subplots(figsize=(3,3))t1=ax.text(0.05,.05,"Text 1",va='bottom',ha='left')t2=ax.text(0.90,.90,"Text 2",ha='right')t3=ax.annotate("Anchored to 1 & 2",xy=(0,0),xycoords=(t1,t2),va='bottom',color='tab:orange',)