matplotlib.text

Classes for including text in a figure.

class matplotlib.text.Annotation(**kwargs) [source]

Bases: matplotlib.text.Text, matplotlib.text._AnnotationBase

An Annotation is a Text that can refer to a specific position xy. Optionally an arrow pointing from the text to xy can be drawn.

Attributes:
xy

The annotated position.

xycoords

The coordinate system for xy.

arrow_patch

A FancyArrowPatch to point from xytext to xy.

Annotate the point xy with text text.

In the simplest form, the text is placed at xy.

Optionally, the text can be displayed in another position xytext. An arrow pointing from the text to the annotated point xy can then be added by defining arrowprops.

Parameters:
textstr

The text of the annotation. s is a deprecated synonym for this parameter.

xy(float, float)

The point (x, y) to annotate.

xytext(float, float), optional

The position (x, y) to place the text at. If None, defaults to xy.

xycoordsstr, Artist, Transform, callable or tuple, optional

The coordinate system that xy is given in. The following types of values are supported:

  • One of the following strings:

    Value Description
    'figure points' Points from the lower left of the figure
    'figure pixels' Pixels from the lower left of the figure
    'figure fraction' Fraction of figure from lower left
    'axes points' Points from lower left corner of axes
    'axes pixels' Pixels from lower left corner of axes
    'axes fraction' Fraction of axes from lower left
    'data' Use the coordinate system of the object being annotated (default)
    'polar' (theta, r) if not native 'data' coordinates
  • An Artist: xy is interpreted as a fraction of the artists Bbox. E.g. (0, 0) would be the lower left corner of the bounding box and (0.5, 1) would be the center top of the bounding box.
  • A Transform to transform xy to screen coordinates.
  • A function with one of the following signatures:

    def transform(renderer) -> Bbox
    def transform(renderer) -> Transform
    

    where renderer is a RendererBase subclass.

    The result of the function is interpreted like the Artist and Transform cases above.

  • A tuple (xcoords, ycoords) specifying separate coordinate systems for x and y. xcoords and ycoords must each be of one of the above described types.

See Advanced Annotations for more details.

Defaults to 'data'.

textcoordsstr, Artist, Transform, callable or tuple, optional

The coordinate system that xytext is given in.

All xycoords values are valid as well as the following strings:

Value Description
'offset points' Offset (in points) from the xy value
'offset pixels' Offset (in pixels) from the xy value

Defaults to the value of xycoords, i.e. use the same coordinate system for annotation point and text position.

arrowpropsdict, optional

The properties used to draw a FancyArrowPatch arrow between the positions xy and xytext.

If arrowprops does not contain the key 'arrowstyle' the allowed keys are:

Key Description
width The width of the arrow in points
headwidth The width of the base of the arrow head in points
headlength The length of the arrow head in points
shrink Fraction of total length to shrink from both ends
? Any key to matplotlib.patches.FancyArrowPatch

If arrowprops contains the key 'arrowstyle' the above keys are forbidden. The allowed values of 'arrowstyle' are:

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

Valid keys for FancyArrowPatch are:

Key Description
arrowstyle the arrow style
connectionstyle the connection style
relpos default is (0.5, 0.5)
patchA default is bounding box of the text
patchB default is None
shrinkA default is 2 points
shrinkB default is 2 points
mutation_scale default is text size (in points)
mutation_aspect default is 1.
? any key for matplotlib.patches.PathPatch

Defaults to None, i.e. no arrow is drawn.

annotation_clipbool or None, optional

Whether to draw the annotation when the annotation point xy is outside the axes area.

  • If True, the annotation will only be drawn when xy is within the axes.
  • If False, the annotation will always be drawn.
  • If None, the annotation will only be drawn when xy is within the axes and xycoords is 'data'.

Defaults to None.

**kwargs

Additional kwargs are passed to Text.

Returns:
annotationAnnotation
property anncoords

The coordinate system to use for Annotation.xyann.

contains(self, event) [source]

Test whether the mouse event occurred in the patch.

In the case of text, a hit is true anywhere in the axis-aligned bounding-box containing the text.

Returns:
boolbool
draw(self, renderer) [source]

Draw the Annotation object to the given renderer.

get_anncoords(self)

Return the coordinate system to use for Annotation.xyann.

See also xycoords in Annotation.

get_window_extent(self, renderer=None) [source]

Return the Bbox bounding the text and arrow, in display units.

Parameters:
rendererRenderer, optional

A renderer is needed to compute the bounding box. If the artist has already been drawn, the renderer is cached; thus, it is only necessary to pass this argument when calling get_window_extent before the first draw. In practice, it is usually easier to trigger a draw first (e.g. by saving the figure).

set_anncoords(self, coords)

Set the coordinate system to use for Annotation.xyann.

See also xycoords in Annotation.

set_figure(self, fig) [source]

Set the Figure instance the artist belongs to.

Parameters:
figFigure
update_positions(self, renderer) [source]

Update the pixel positions of the annotated point and the text.

property xyann

The the text position.

See also xytext in Annotation.

class matplotlib.text.OffsetFrom(artist, ref_coord, unit='points') [source]

Bases: object

Callable helper class for working with Annotation

Parameters:
artistArtist, BboxBase, or Transform

The object to compute the offset from.

ref_coordlength 2 sequence

If artist is an Artist or BboxBase, this values is the location to of the offset origin in fractions of the artist bounding box.

If artist is a transform, the offset origin is the transform applied to this value.

unit{'points, 'pixels'}

The screen units to use (pixels or points) for the offset input.

get_unit(self) [source]

The unit for input to the transform used by __call__

set_unit(self, unit) [source]

The unit for input to the transform used by __call__

Parameters:
unit{'points', 'pixels'}
class matplotlib.text.Text(x=0, y=0, text='', color=None, verticalalignment='baseline', horizontalalignment='left', multialignment=None, fontproperties=None, rotation=None, linespacing=None, rotation_mode=None, usetex=None, wrap=False, **kwargs) [source]

Bases: matplotlib.artist.Artist

Handle storing and drawing of text in window or data coordinates.

Create a Text instance at x, y with string text.

Valid keyword arguments are:

Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c color
contains callable
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font_properties font_manager.FontProperties
fontsize or size {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
multialignment or ma {'left', 'right', 'center'}
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool or None
rotation {angle in degrees, 'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float
contains(self, mouseevent) [source]

Test whether the mouse event occurred in the patch.

In the case of text, a hit is true anywhere in the axis-aligned bounding-box containing the text.

Returns:
boolbool
draw(self, renderer) [source]

Draws the Text object to the given renderer.

get_bbox_patch(self) [source]

Return the bbox Patch, or None if the patches.FancyBboxPatch is not made.

get_c(self)

Alias for get_color.

get_color(self) [source]

Return the color of the text

get_family(self)

Alias for get_fontfamily.

get_font_properties(self)

Alias for get_fontproperties.

get_fontfamily(self) [source]

Return the list of font families used for font lookup

get_fontname(self) [source]

Return the font name as string

get_fontproperties(self) [source]

Return the font_manager.FontProperties object

get_fontsize(self) [source]

Return the font size as integer

get_fontstyle(self) [source]

Return the font style as string

get_fontvariant(self) [source]

Return the font variant as a string

get_fontweight(self) [source]

Get the font weight as string or number

get_ha(self)

Alias for get_horizontalalignment.

get_horizontalalignment(self) [source]

Return the horizontal alignment as string. Will be one of 'left', 'center' or 'right'.

get_name(self)

Alias for get_fontname.

get_position(self) [source]

Return the position of the text as a tuple (x, y)

get_prop_tup(self, renderer=None) [source]

Return a hashable tuple of properties.

Not intended to be human readable, but useful for backends who want to cache derived information about text (e.g., layouts) and need to know if the text has changed.

get_rotation(self) [source]

Return the text angle as float in degrees.

get_rotation_mode(self) [source]

Get the text rotation mode.

get_size(self)

Alias for get_fontsize.

get_stretch(self) [source]

Get the font stretch as a string or number

get_style(self)

Alias for get_fontstyle.

get_text(self) [source]

Get the text as string

get_unitless_position(self) [source]

Return the unitless position of the text as a tuple (x, y)

get_usetex(self) [source]

Return whether this Text object uses TeX for rendering.

get_va(self)

Alias for get_verticalalignment.

get_variant(self)

Alias for get_fontvariant.

get_verticalalignment(self) [source]

Return the vertical alignment as string. Will be one of 'top', 'center', 'bottom' or 'baseline'.

get_weight(self)

Alias for get_fontweight.

get_window_extent(self, renderer=None, dpi=None) [source]

Return the Bbox bounding the text, in display units.

In addition to being used internally, this is useful for specifying clickable regions in a png file on a web page.

Parameters:
rendererRenderer, optional

A renderer is needed to compute the bounding box. If the artist has already been drawn, the renderer is cached; thus, it is only necessary to pass this argument when calling get_window_extent before the first draw. In practice, it is usually easier to trigger a draw first (e.g. by saving the figure).

dpifloat, optional

The dpi value for computing the bbox, defaults to self.figure.dpi (not the renderer dpi); should be set e.g. if to match regions with a figure saved with a custom dpi value.

get_wrap(self) [source]

Return the wrapping state for the text.

static is_math_text(s, usetex=None) [source]

[Deprecated] Returns a cleaned string and a boolean flag. The flag indicates if the given string s contains any mathtext, determined by counting unescaped dollar signs. If no mathtext is present, the cleaned string has its dollar signs unescaped. If usetex is on, the flag always has the value "TeX".

Notes

Deprecated since version 3.1.

set_backgroundcolor(self, color) [source]

Set the background color of the text by updating the bbox.

Parameters:
colorcolor

See also

set_bbox
To change the position of the bounding box
set_bbox(self, rectprops) [source]

Draw a bounding box around self.

Parameters:
rectpropsdict with properties for patches.FancyBboxPatch

The default boxstyle is 'square'. The mutation scale of the patches.FancyBboxPatch is set to the fontsize.

Examples

t.set_bbox(dict(facecolor='red', alpha=0.5))
set_c(self, color)

Alias for set_color.

set_clip_box(self, clipbox) [source]

Set the artist's clip Bbox.

Parameters:
clipboxBbox
set_clip_on(self, b) [source]

Set whether the artist uses clipping.

When False artists will be visible out side of the axes which can lead to unexpected results.

Parameters:
bbool
set_clip_path(self, path, transform=None) [source]

Set the artist's clip path.

Parameters:
pathPatch or Path or TransformedPath or None

The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.

transformTransform, optional

Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform.

Notes

For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None.

For technical reasons (support of setp), a tuple (path, transform) is also accepted as a single positional parameter.

set_color(self, color) [source]

Set the foreground color of the text

Parameters:
colorcolor
set_family(self, fontname)

Alias for set_fontfamily.

set_font_properties(self, fp)

Alias for set_fontproperties.

set_fontfamily(self, fontname) [source]

Set the font family. May be either a single string, or a list of strings in decreasing priority. Each string may be either a real font name or a generic font class name. If the latter, the specific font names will be looked up in the corresponding rcParams.

If a Text instance is constructed with fontfamily=None, then the font is set to rcParams["font.family"] (default: ['sans-serif']), and the same is done when set_fontfamily() is called on an existing Text instance.

Parameters:
fontname{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
set_fontname(self, fontname) [source]

Alias for set_family.

One-way alias only: the getter differs.

Parameters:
fontname{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
set_fontproperties(self, fp) [source]

Set the font properties that control the text.

Parameters:
fpfont_manager.FontProperties
set_fontsize(self, fontsize) [source]

Set the font size. May be either a size string, relative to the default font size, or an absolute font size in points.

Parameters:
fontsize{size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
set_fontstretch(self, stretch) [source]

Set the font stretch (horizontal condensation or expansion).

Parameters:
stretch{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
set_fontstyle(self, fontstyle) [source]

Set the font style.

Parameters:
fontstyle{'normal', 'italic', 'oblique'}
set_fontvariant(self, variant) [source]

Set the font variant, either 'normal' or 'small-caps'.

Parameters:
variant{'normal', 'small-caps'}
set_fontweight(self, weight) [source]

Set the font weight.

Parameters:
weight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
set_ha(self, align)

Alias for set_horizontalalignment.

set_horizontalalignment(self, align) [source]

Set the horizontal alignment to one of

Parameters:
align{'center', 'right', 'left'}
set_linespacing(self, spacing) [source]

Set the line spacing as a multiple of the font size. Default is 1.2.

Parameters:
spacingfloat (multiple of font size)
set_ma(self, align)

Alias for set_multialignment.

set_multialignment(self, align) [source]

Set the alignment for multiple lines layout. The layout of the bounding box of all the lines is determined by the horizontalalignment and verticalalignment properties, but the multiline text within that box can be

Parameters:
align{'left', 'right', 'center'}
set_name(self, fontname)

Alias for set_fontname.

set_position(self, xy) [source]

Set the (x, y) position of the text.

Parameters:
xy(float, float)
set_rotation(self, s) [source]

Set the rotation of the text.

Parameters:
s{angle in degrees, 'vertical', 'horizontal'}
set_rotation_mode(self, m) [source]

Set text rotation mode.

Parameters:
m{None, 'default', 'anchor'}

If None or "default", the text will be first rotated, then aligned according to their horizontal and vertical alignments. If "anchor", then alignment occurs before rotation.

set_size(self, fontsize)

Alias for set_fontsize.

set_stretch(self, stretch)

Alias for set_fontstretch.

set_style(self, fontstyle)

Alias for set_fontstyle.

set_text(self, s) [source]

Set the text string s.

It may contain newlines (\n) or math in LaTeX syntax.

Parameters:
sobject

Any object gets converted to its str, except None which becomes ''.

set_usetex(self, usetex) [source]
Parameters:
usetexbool or None

Whether to render using TeX, None means to use rcParams["text.usetex"] (default: False).

set_va(self, align)

Alias for set_verticalalignment.

set_variant(self, variant)

Alias for set_fontvariant.

set_verticalalignment(self, align) [source]

Set the vertical alignment

Parameters:
align{'center', 'top', 'bottom', 'baseline', 'center_baseline'}
set_weight(self, weight)

Alias for set_fontweight.

set_wrap(self, wrap) [source]

Set the wrapping state for the text.

Parameters:
wrapbool
set_x(self, x) [source]

Set the x position of the text.

Parameters:
xfloat
set_y(self, y) [source]

Set the y position of the text.

Parameters:
yfloat
update(self, kwargs) [source]

Update properties from a dictionary.

update_bbox_position_size(self, renderer) [source]

Update the location and the size of the bbox.

This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox.

update_from(self, other) [source]

Copy properties from other to self.

zorder = 3
class matplotlib.text.TextWithDash(**kwargs) [source]

Bases: matplotlib.text.Text

[Deprecated] This is basically a Text with a dash (drawn with a Line2D) before/after it. It is intended to be a drop-in replacement for Text, and should behave identically to it when dashlength = 0.0.

The dash always comes between the point specified by set_position() and the text. When a dash exists, the text alignment arguments (horizontalalignment, verticalalignment) are ignored.

dashlength is the length of the dash in canvas units. (default = 0.0).

dashdirection is one of 0 or 1, where 0 draws the dash after the text and 1 before. (default = 0).

dashrotation specifies the rotation of the dash, and should generally stay None. In this case get_dashrotation() returns get_rotation(). (i.e., the dash takes its rotation from the text's rotation). Because the text center is projected onto the dash, major deviations in the rotation cause what may be considered visually unappealing results. (default = None)

dashpad is a padding length to add (or subtract) space between the text and the dash, in canvas units. (default = 3)

dashpush "pushes" the dash and text away from the point specified by set_position() by the amount in canvas units. (default = 0)

Note

The alignment of the two objects is based on the bounding box of the Text, as obtained by get_window_extent(). This, in turn, appears to depend on the font metrics as given by the rendering backend. Hence the quality of the "centering" of the label text with respect to the dash varies depending on the backend used.

Note

I'm not sure that I got the get_window_extent() right, or whether that's sufficient for providing the object bounding box.

Notes

Deprecated since version 3.1.

Create a Text instance at x, y with string text.

Valid keyword arguments are:

Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c color
contains callable
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font_properties font_manager.FontProperties
fontsize or size {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
multialignment or ma {'left', 'right', 'center'}
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool or None
rotation {angle in degrees, 'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float
draw(self, renderer) [source]

Draw the TextWithDash object to the given renderer.

get_dashdirection(self) [source]

Get the direction dash. 1 is before the text and 0 is after.

get_dashlength(self) [source]

Get the length of the dash.

get_dashpad(self) [source]

Get the extra spacing between the dash and the text, in canvas units.

get_dashpush(self) [source]

Get the extra spacing between the dash and the specified text position, in canvas units.

get_dashrotation(self) [source]

Get the rotation of the dash in degrees.

get_figure(self) [source]

Return the figure instance the artist belongs to.

get_position(self) [source]

Return the position of the text as a tuple (x, y)

get_prop_tup(self, renderer=None) [source]

Return a hashable tuple of properties.

Not intended to be human readable, but useful for backends who want to cache derived information about text (e.g., layouts) and need to know if the text has changed.

get_unitless_position(self) [source]

Return the unitless position of the text as a tuple (x, y)

get_window_extent(self, renderer=None) [source]

Return a Bbox object bounding the text, in display units.

In addition to being used internally, this is useful for specifying clickable regions in a png file on a web page.

renderer defaults to the _renderer attribute of the text object. This is not assigned until the first execution of draw(), so you must use this kwarg if you want to call get_window_extent() prior to the first draw(). For getting web page regions, it is simpler to call the method after saving the figure.

set_dashdirection(self, dd) [source]

Set the direction of the dash following the text. 1 is before the text and 0 is after. The default is 0, which is what you'd want for the typical case of ticks below and on the left of the figure.

Parameters:
ddint (1 is before, 0 is after)
set_dashlength(self, dl) [source]

Set the length of the dash, in canvas units.

Parameters:
dlfloat
set_dashpad(self, dp) [source]

Set the "pad" of the TextWithDash, which is the extra spacing between the dash and the text, in canvas units.

Parameters:
dpfloat
set_dashpush(self, dp) [source]

Set the "push" of the TextWithDash, which is the extra spacing between the beginning of the dash and the specified position.

Parameters:
dpfloat
set_dashrotation(self, dr) [source]

Set the rotation of the dash, in degrees.

Parameters:
drfloat
set_figure(self, fig) [source]

Set the figure instance the artist belongs to.

Parameters:
figFigure
set_position(self, xy) [source]

Set the (x, y) position of the TextWithDash.

Parameters:
xy(float, float)
set_transform(self, t) [source]

Set the matplotlib.transforms.Transform instance used by this artist.

Parameters:
tTransform
set_x(self, x) [source]

Set the x position of the TextWithDash.

Parameters:
xfloat
set_y(self, y) [source]

Set the y position of the TextWithDash.

Parameters:
yfloat
update_coords(self, renderer) [source]

Computes the actual x, y coordinates for text based on the input x, y and the dashlength. Since the rotation is with respect to the actual canvas's coordinates we need to map back and forth.

matplotlib.text.get_rotation(rotation) [source]

Return the text angle as float between 0 and 360 degrees.

rotation may be 'horizontal', 'vertical', or a numeric value in degrees.

© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.2.2/api/text_api.html