Matplotlib Chinese User Guide 4.5 annotations

Source: Internet
Author: User
Callout

Original: Annotation

Translator: Dragon

Protocol: CC BY-NC-SA 4.0 basic Annotation

Using text () places the text anywhere in the Axis field. A common use case for text is to annotate some of the characteristics of the drawing, while the annotate () method provides an auxiliary function to make annotations easier. In the callout, there are two points to consider: the callout position represented by the parameter xy and the text position of the Xytext. Both of these parameters are (x, y) tuples.

Import NumPy as NP
import matplotlib.pyplot as plt

fig = plt.figure ()
ax = fig.add_subplot ()

t = Np.ara Nge (0.0, 5.0, 0.01)
s = Np.cos (2*np.pi*t) line
, = Ax.plot (t, S, lw=2)

ax.annotate (' Local Max ', xy= (2, 1), Xyte xt= (3, 1.5),
            arrowprops=dict (facecolor= ' black ', shrink=0.05), Ax.set_ylim (

-2,2)
plt.show ()

Source

In the example, XY (arrowhead tip) and Xytext position (text position) are in data coordinates. There are several other coordinate systems that you can select-you can use Xycoords and textcoords and one of the following strings (the default is data) to specify the coordinates of XY and xytext.

| Parameters | Coordinate system |
| ' Figure Points ' | Number of points in the lower-left corner of the graph |
| ' Figure pixels ' | Number of pixels from the lower-left corner of the graph |
| ' Figure fraction ' | 0,0 is the lower-left corner of the graph, 1,1 is the upper-right corner |
| ' Axes points ' | Number of points in the lower left corner of the axis field |
| ' Axes pixels ' | Number of pixels from the lower-left corner of the axis field |
| ' Axes fraction ' | 0,0 is the lower-left corner of the axis field, 1,1 is the upper-right corner |
| ' Data ' | Using the Axis-field data coordinate system |

For example, to place text in an axis decimal coordinate system, we can:

Ax.annotate (' Local Max ', xy= (3, 1),  xycoords= ' data ',
            xytext= (0.8, 0.95), textcoords= ' axes fraction ',
            Arrowprops=dict (facecolor= ' Black ", shrink=0.05),
            horizontalalignment= ' right ', verticalalignment= ' top ',
            )

For a physical coordinate system (dots or pixels), the origin is the lower-left corner of the graph or axis.

Alternatively, you can draw arrows from the text to the annotation point by providing a dictionary of Arrow properties in the Optional keyword parameter arrowprops.

arrowprops Key Description
Width Arrow width, in dots
Frac The proportion of the head of the arrow
Headwidth The width of the bottom of the arrow, in points
Shrink Move the hint and leave it at a distance from the annotation point and text
**kwargs Matplotlib.patches.Polygon of any key, such as Facecolor

In the following example, the XY point is the original coordinate (xycoords defaults to ' data '). For polar axes, it is in (theta, radius) space. The text in this example is placed in the graphics decimal coordinate system. Matplotlib.text.Text keyword args, such as horizontalalignment,verticalalignment and FontSize, are passed to the text instance from annotate.

Source

Notes (including fancy arrows) for more information on all the higher-than-large content, see Advanced Annotations and Pylab_examples sample code: annotation_demo.py.

Do not continue unless you have read the basic callout, text () and annotate (). Advanced Annotations use boxes and text to label

Let's start with a simple example.

Source

The text () function in the Pyplot module (or the text method of the Axes class) accepts the Bbox keyword parameter and, when provided, draws a box around the text.

The patch object associated with the text can be accessed in the following ways:

bb = T.get_bbox_patch ()

The return value is an instance of Fancybboxpatch, and the patch properties (such as facecolor,edgewidth, etc.) can be accessed and modified as usual. To change the shape of the box, use the Set_boxstyle method.

Bb.set_boxstyle ("Rarrow", pad=0.6)

The parameter is the name of the box style and its properties as a keyword parameter. Currently, the following box styles are implemented.

class name Property
Circle Circle pad=0.3
Darrow Darrow pad=0.3
Larrow Larrow pad=0.3
Rarrow Rarrow pad=0.3
Round Round Pad=0.3,rounding_size=none
Round4 Round4 Pad=0.3,rounding_size=none
Roundtooth Roundtooth Pad=0.3,tooth_size=none
Sawtooth Sawtooth Pad=0.3,tooth_size=none
Square Square pad=0.3

Source

Note that the property arguments can be separated by commas in the style name (this form can be used as the Boxstyle value of the Bbox parameter when initializing the text instance).

Bb.set_boxstyle ("rarrow,pad=0.6")
use arrows to label

The annotate () function in the Pyplot module (or the annotate method of the Axes class) is used to draw arrows at two points on the connection diagram.

Ax.annotate ("Annotation",
            xy= (x1, y1), xycoords= ' data ',
            xytext= (x2, y2), textcoords= ' offset points ',
            )

This will use the Xytext text callout provided in Textcoords to provide the point at the XY in coordinates (xycoords). In general, a callout point is specified in the data coordinate, and the callout text is specified in the offset point. See Annotate () for available coordinate systems.

Arrows that connect two dots (xy and xytext) can be drawn optionally by specifying the Arrowprops parameter. To draw only arrows, use an empty string as the first argument.

Ax.annotate ("",
            xy= (0.2, 0.2), xycoords= ' data ',
            xytext= (0.8, 0.8), textcoords= ' data ',
            arrowprops=dict ( Arrowstyle= "->",
                            connectionstyle= "ARC3"),
            )

Source

The drawing of the arrows takes several steps. Creates a connection path between two points. This is controlled by the Connectionstyle key value. If a patch object (Patcha and PATCHB) is provided, the path is clipped to avoid the patch. The path is further reduced by the amount of pixels provided (SHIRNKA&SHRINKB) path to the arrow patch, controlled by the Arrowstyle key value.

Source

The creation of a connection path between two points is controlled by the Connectionstyle key, and the following styles are available.

name Property
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 of the angle3 and ARC3 means that the resulting path is two spline segments (three control points). As discussed below, some arrow style options are available when the connection path is two times spline.

The behavior of each connection style is demonstrated (limited) in the following example. (Warning: The behavior of a bar style is not currently defined and may change in the future).

Source

The connection path (after cut and shrink) is then transformed into an arrow patch based on the given Arrow style.

name Property
- 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
< -|>
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

Source

Some arrows apply only to connection styles that generate two-time spline segments. They are fancy,simple,wedge. For these arrowhead styles, you must use the Angle3 or ARC3 connection style.

If a callout string is provided, the Patcha default is set to the Bbox patch for the text.

Source

As with the text command, you can use the Bbox parameter to draw a box around the text.

Source

By default, the start point is set to the center of the text range. You can adjust using the Relpos key value. These values are normalized according to the scope of the text. For example, (0,0) represents the lower-left corner, (1,1) represents the upper-right corner.

Source

Place the artist in the anchoring position of the axis field

There is a class of artists that can be placed in the anchoring position of the Axis field. A common example is the legend. This type of artist can be created using the Offsetbox class. There are several predefined classes in the mpl_toolkits.axes_grid.anchored_artists.

From mpl_toolkits.axes_grid.anchored_artists import anchoredtext
at = anchoredtext ("Figure 1a",
                  prop=dict ( size=8), Frameon=true,
                  loc=2,
                  )
at.patch.set_boxstyle ("round,pad=0.,rounding_size=0.2")
ax.add_ Artist (at)

Source

The LOC keyword has the same meaning as the legend command.

A simple application is when the pixel size of the artist (or artist's collection) is known at the time of creation. For example, if you want to draw a circle with a fixed size of 20 pixel x20 pixels (a radius of 10 pixels), you can use Anchoreddrawingarea. instances are created (in pixels) using the size of the drawing area. Users can add artists anywhere in the plot area. Note that the range of artists added to the drawing area is independent of the location of the drawing area itself, and is related only to the initial size.

From mpl_toolkits.axes_grid.anchored_artists import anchoreddrawingarea

ada = Anchoreddrawingarea (20, 20, 0, 0,
                          loc=1, Pad=0., Frameon=false)
P1 = Circle ((ten),
ada.drawing_area.add_artist (p1)
P2 = Circle ((5), fc= "R")
Ada.drawing_ Area.add_artist (p2)

Artists added to the drawing area should not have transform sets (they will be overridden), and the artists ' dimensions are interpreted as pixel coordinates, that is, the circles in the example above are 10 pixels and 5 pixels respectively.

Source

Sometimes you want your artist to scale by data coordinates (or other coordinates, not canvas pixels). You can use the Anchoredauxtransformbox class. This is similar to Anchoreddrawingarea, except that the artist's range is determined by the specified transformation when drawing.

From mpl_toolkits.axes_grid.anchored_artists import anchoredauxtransformbox

box = Anchoredauxtransformbox ( Ax.transdata, loc=2)
el = Ellipse ((0,0), width=0.1, height=0.4, angle=30) # in Data coordinates!
Box.drawing_area.add_artist (EL)

The ellipses in the preceding example have the width and height corresponding to 0.1 and 0.4 in the data coordinates, and will be scaled automatically when the view limit of the Axis field changes.

Source

You can set the Bbox_to_anchor parameter as shown in the legend. Using Hpacker and Vpacker, you can arrange the artist in the same way as the legend (in fact, this is how the legend was created).

Source

Note that, unlike the legend, Bbox_transform is set to Identitytransform by default. use complex coordinates to label

The annotations in Matplotlib support several types of coordinates described in the callout text. For advanced users who want more control, it supports several other options.

Transform instance, for example:

Ax.annotate ("Test", xy= (0.5, 0.5), xycoords=ax.transaxes)

Equivalent:

Ax.annotate ("Test", xy= (0.5, 0.5), xycoords= "axes fraction")

With it, you can mark a point in the other axis fields:

Ax1, ax2 = subplot (121), subplot (122)
ax2.annotate ("Test", xy= (0.5, 0.5), Xycoords=ax1.transdata,
             xytext= (0.5 , 0.5), Textcoords=ax2.transdata,
             arrowprops=dict (arrowstyle= "->"))

Artist instance. The XY value (or xytext) is interpreted as the decimal coordinate of the artist's Bbox (Get_window_extent return value).

An1 = Ax.annotate ("Test 1", xy= (0.5, 0.5), xycoords= "Data",
                  va= "center", ha= "center",
                  bbox=dict (boxstyle= "  Round ", fc=" W "))
an2 = Ax.annotate (" Test 2 ", xy= (1, 0.5), Xycoords=an1, # (1,0.5) of the An1 ' s bbox
                  xytext= (30,0), Textcoords= "offset points",
                  va= "center", ha= "left",
                  bbox=dict (boxstyle= "Round", fc= "W"),
                  arrowprops= Dict (arrowstyle= "->"))

Source

Please note that your responsibility is to determine the range of the coordinate artist (An1 in the example above) before drawing an2. In most cases, this means that an2 need to be later than An1.

A callable object that returns an instance of Bboxbase or transform. If you return a transform, it is the same as 1, and if it returns bbox, it is the same as 2. A callable object should accept a single parameter of the renderer instance. For example, the following two commands produce the same result:

An2 = Ax.annotate ("Test 2", xy= (1, 0.5), Xycoords=an1,
                  xytext= (30,0), textcoords= "offset points")
an2 = Ax.annotate ("Test 2", xy= (1, 0.5), xycoords=an1.get_window_extent,
                  xytext= (30,0), textcoords= "offset points")

Specifies a tuple of two-dollar coordinates. The first entry is for the x-coordinate and the second for the Y coordinate. For example

Annotate ("Test", xy= (0.5, 1), xycoords= ("Data", "axes fraction"))

The unit of 0.5 is the data coordinate, and the 1 unit is the normalized axis field coordinate. You can use an artist or transform as you would with a tuple. For example

Import Matplotlib.pyplot as Plt

plt.figure (figsize= (3,2))
ax=plt.axes ([0.1, 0.1, 0.8, 0.7])
an1 = Ax.annotate ("Test 1", xy= (0.5, 0.5), xycoords= "Data",
                  va= "center", ha= "center",
                  Bbox=dict (boxstyle= "Round", Fc= "W")

an2 = Ax.annotate ("Test 2", xy= (0.5, 1.), Xycoords=an1,
                  xytext= (0.5,1.1), textcoords= (An1, "axes") Fraction "),
                  va=" Bottom ", ha=" center ",
                  Bbox=dict (boxstyle=" Round ", fc=" W "),
                  arrowprops=dict ( Arrowstyle= "->")
plt.show ()

Source

Sometimes you want your comments to have some "offset points", not from the annotation point, but from some other point. Offsetfrom is the auxiliary class in this case.

Import Matplotlib.pyplot as Plt

plt.figure (figsize= (3,2))
ax=plt.axes ([0.1, 0.1, 0.8, 0.7])
an1 = Ax.annotate ("Test 1", xy= (0.5, 0.5), xycoords= "Data",
                  va= "center", ha= "center",
                  Bbox=dict (boxstyle= "Round", Fc= "W")) from

matplotlib.text import offsetfrom
offset_from = Offsetfrom (An1, (0.5, 0))
an2 = Ax.annotate (" Test 2 ", xy= (0.1, 0.1), xycoords=" Data ",
                  xytext= (0, -10), Textcoords=offset_from,
                  # Xytext is offset points from" xy= (0.5, 0), xycoords=an1 "
                  va=", ha= "center", Bbox=dict
                  (boxstyle= "Round", fc= "W"),
                  arrowprops= Dict (arrowstyle= "->"))
Plt.show ()

You can refer to this link: pylab_examples example code:annotation_demo3.py. using Connectorpatch

Connectorpatch is similar to a callout without text. Although it is recommended that you use callout functions in most cases, Connectorpatch is useful when you want to connect points on different axes.

From matplotlib.patches import connectionpatch
xy = (0.2, 0.2)
con = Connectionpatch (Xya=xy, Xyb=xy, coordsa= " Data ", coordsb=" data ",
                      axesa=ax1, axesb=ax2)
ax2.add_artist (Con)

The above code connects the XY points of the data coordinates in the AX1 with the XY points of the data coordinates in the AX2. This is a simple example.

Source

Although Connectorpatch instances can be added to any axis, you may need to add them to the latest axes in the drawing order to prevent overlapping with other axes. Top Topics scaling effect between axis fields

Mpl_toolkits.axes_grid.inset_locator defines some patch classes for interconnection of two axis fields. Understanding code requires some knowledge of how MPL transformations work. However, the way it is used is straightforward.

Source

Defining custom Box Styles

You can use custom box styles, and the Boxstyle value can be a callable object in the following form:

def __call__ (self, x0, y0, width, height, mutation_size,
             aspect_ratio=1.):
    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.