On this page
text
matplotlib.text
Classes for including text in a figure.
class matplotlib.text.Annotation(s, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)[source]-
Bases:
matplotlib.text.Text,matplotlib.text._AnnotationBaseAnnotate the point
xywith texts.Additional kwargs are passed to
Text.Parameters: -
s : str -
The text of the annotation.
-
xy : iterable -
Length 2 sequence specifying the (x,y) point to annotate.
-
xytext : iterable, optional -
Length 2 sequence specifying the (x,y) to place the text at. If None, defaults to
xy. -
xycoords : str, Artist, Transform, callable or tuple, optional -
The coordinate system that
xyis given in.For a
strthe allowed values are:Property 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 If a
Artistobject is passed in the units are fraction if it's bounding box.If a
Transformobject is passed in use that to transformxyto screen coordinatesIf a callable it must take a
RendererBaseobject as input and return aTransformorBboxobjectIf a
tuplemust be length 2 tuple of str,Artist,Transformor callable objects. The first transform is used for the x coordinate and the second for y.See Advanced Annotation for more details.
Defaults to
'data' -
textcoords : str, Artist, Transform, callable or tuple, optional -
The coordinate system that
xytextis given, which may be different than the coordinate system used forxy.All
xycoordsvalues are valid as well as the following strings:Property Description 'offset points' offset (in points) from the xy value 'offset pixels' offset (in pixels) from the xy value defaults to the input of
xycoords -
arrowprops : dict, optional -
If not None, properties used to draw a
FancyArrowPatcharrow betweenxyandxytext.If
arrowpropsdoes 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.FancyArrowPatchIf the
arrowpropscontains 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
FancyArrowPatchare: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.PathPatchDefaults to None
-
annotation_clip : bool, optional -
Controls the visibility of the annotation when it goes outside the axes area.
If
True, the annotation will only be drawn when thexyis inside the axes. IfFalse, the annotation will always be drawn regardless of its position.The default is
None, which behave asTrueonly if xycoords is "data".
Returns: - Annotation
anncoords
arrow-
Deprecated since version 3.0: The <lambda> function was deprecated in Matplotlib 3.0 and will be removed in 3.2.
contains(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: -
bool : bool
-
draw(renderer)[source]-
Draw the
Annotationobject to the given renderer.
get_window_extent(renderer=None)[source]-
Return a
Bboxobject bounding the text and arrow annotation, in display units.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 callget_window_extent()prior to the firstdraw(). For getting web page regions, it is simpler to call the method after saving the figure. The dpi used defaults to self.figure.dpi; the renderer dpi is irrelevant.
update_positions(renderer)[source]-
Update the pixel positions of the annotated point and the text.
xyann
-
class matplotlib.text.OffsetFrom(artist, ref_coord, unit='points')[source]-
Bases:
objectCallable helper class for working with
AnnotationParameters: -
artist : Artist, BboxBase, or Transform -
The object to compute the offset from.
-
ref_coord : length 2 sequence -
If
artistis anArtistorBboxBase, this values is the location to of the offset origin in fractions of theartistbounding box.If
artistis 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()[source]-
The unit for input to the transform used by
__call__
set_unit(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.ArtistHandle storing and drawing of text in window or data coordinates.
Create a
Textinstance at x, y with string text.Valid kwargs are
Property Description agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alphafloat animatedbool backgroundcolorcolor bboxdict with properties for patches.FancyBboxPatchclip_boxmatplotlib.transforms.Bboxclip_onbool clip_path{ ( path.Path,transforms.Transform),patches.Patch, None }colorcolor containscallable figureFigurefontfamily{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontname{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontpropertiesfont_manager.FontPropertiesfontsize{size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} fontstretch{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} fontstyle{'normal', 'italic', 'oblique'} fontvariant{'normal', 'small-caps'} fontweight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} gidstr horizontalalignment{'center', 'right', 'left'} in_layoutbool labelobject linespacingfloat (multiple of font size) multialignment{'left', 'right', 'center'} path_effectsAbstractPathEffectpickerNone or bool or float or callable position(float, float) rasterizedbool or None rotation{angle in degrees, 'vertical', 'horizontal'} rotation_mode{None, 'default', 'anchor'} sketch_params(scale: float, length: float, randomness: float) snapbool or None textstring or object castable to string (but Nonebecomes'')transformTransformurlstr usetexbool or None verticalalignment{'center', 'top', 'bottom', 'baseline', 'center_baseline'} visiblebool wrapbool xfloat yfloat zorderfloat contains(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: -
bool : bool
-
get_bbox_patch()[source]-
Return the bbox Patch, or None if the
patches.FancyBboxPatchis not made.
get_color()[source]-
Return the color of the text
get_family(*args, **kwargs)-
alias for
get_fontfamily
get_font_properties(*args, **kwargs)-
alias for
get_fontproperties
get_fontfamily()[source]-
Return the list of font families used for font lookup
get_fontname()[source]-
Return the font name as string
See also
get_fontproperties()[source]-
Return the
font_manager.FontPropertiesobject
get_fontsize()[source]-
Return the font size as integer
get_fontstyle()[source]-
Return the font style as string
get_fontvariant()[source]-
Return the font variant as a string
get_fontweight()[source]-
Get the font weight as string or number
get_ha(*args, **kwargs)-
alias for
get_horizontalalignment
get_horizontalalignment()[source]-
Return the horizontal alignment as string. Will be one of 'left', 'center' or 'right'.
get_name(*args, **kwargs)-
alias for
get_fontname
get_position()[source]-
Return the position of the text as a tuple (x, y)
get_prop_tup(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()[source]-
Return the text angle as float in degrees.
get_rotation_mode()[source]-
Get the text rotation mode.
get_size(*args, **kwargs)-
alias for
get_fontsize
get_stretch()[source]-
Get the font stretch as a string or number
get_style(*args, **kwargs)-
alias for
get_fontstyle
get_text()[source]-
Get the text as string
get_unitless_position()[source]-
Return the unitless position of the text as a tuple (x, y)
get_usetex()[source]-
Return whether this
Textobject uses TeX for rendering.If the user has not manually set this value, it defaults to
rcParams["text.usetex"].
get_va(*args, **kwargs)-
alias for
get_verticalalignment
get_variant(*args, **kwargs)-
alias for
get_fontvariant
get_verticalalignment()[source]-
Return the vertical alignment as string. Will be one of 'top', 'center', 'bottom' or 'baseline'.
get_weight(*args, **kwargs)-
alias for
get_fontweight
get_window_extent(renderer=None, dpi=None)[source]-
Return a
Bboxobject 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 callget_window_extentprior to the firstdraw. For getting web page regions, it is simpler to call the method after saving the figure.dpi defaults to self.figure.dpi; the renderer dpi is irrelevant. For the web application, if figure.dpi is not the value used when saving the figure, then the value that was used must be specified as the dpi argument.
get_wrap()[source]-
Return the wrapping state for the text.
static is_math_text(s, usetex=None)[source]-
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".
set_backgroundcolor(color)[source]-
Set the background color of the text by updating the bbox.
Parameters: -
color : color
See also
set_bbox- To change the position of the bounding box
-
set_bbox(rectprops)[source]-
Draw a bounding box around self.
Parameters: -
rectprops : dict with properties for patches.FancyBboxPatch -
The default boxstyle is 'square'. The mutation scale of the
patches.FancyBboxPatchis set to the fontsize.
Examples
t.set_bbox(dict(facecolor='red', alpha=0.5)) -
set_clip_box(clipbox)[source]-
Set the artist's clip
Bbox.Parameters: -
clipbox : matplotlib.transforms.Bbox
-
set_clip_on(b)[source]-
Set whether artist uses clipping.
When False, artists will be visible outside of the axes, which can lead to unexpected results.
Parameters: -
b : bool
-
set_clip_path(path, transform=None)[source]-
Set the artist's clip path, which may be:
- a
Patch(or subclass) instance -
a Path instance, in which case-
an optional
Transforminstance may be provided, which will be applied to the path before using it for clipping.
- None, to remove the clipping path
For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to None.
ACCEPTS: { (path.Path, transforms.Transform),patches.Patch, None }
- a
set_color(color)[source]-
Set the foreground color of the text
Parameters: -
color : color
-
set_family(*args, **kwargs)-
alias for
set_fontfamily
set_font_properties(*args, **kwargs)-
alias for
set_fontproperties
set_fontfamily(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.
Parameters: -
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
-
set_fontname(fontname)[source]-
alias for
set_familyOne-way alias only: the getter differs.
Parameters: -
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
-
set_fontproperties(fp)[source]-
Set the font properties that control the text.
Parameters: -
fp : font_manager.FontProperties
-
set_fontsize(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'}
See also
-
set_fontstretch(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(fontstyle)[source]-
Set the font style.
Parameters: -
fontstyle : {'normal', 'italic', 'oblique'}
-
set_fontvariant(variant)[source]-
Set the font variant, either 'normal' or 'small-caps'.
Parameters: -
variant : {'normal', 'small-caps'}
-
set_fontweight(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(*args, **kwargs)-
alias for
set_horizontalalignment
set_horizontalalignment(align)[source]-
Set the horizontal alignment to one of
Parameters: -
align : {'center', 'right', 'left'}
-
set_linespacing(spacing)[source]-
Set the line spacing as a multiple of the font size. Default is 1.2.
Parameters: -
spacing : float (multiple of font size)
-
set_ma(*args, **kwargs)-
alias for
set_multialignment
set_multialignment(align)[source]-
Set the alignment for multiple lines layout. The layout of the bounding box of all the lines is determined bu the horizontalalignment and verticalalignment properties, but the multiline text within that box can be
Parameters: -
align : {'left', 'right', 'center'}
-
set_name(*args, **kwargs)-
alias for
set_fontname
set_position(xy)[source]-
Set the (x, y) position of the text.
Parameters: -
xy : (float, float)
-
set_rotation(s)[source]-
Set the rotation of the text.
Parameters: -
s : {angle in degrees, 'vertical', 'horizontal'}
-
set_rotation_mode(m)[source]-
Set text rotation mode.
Parameters: -
m : {None, 'default', 'anchor'} -
If
Noneor"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(*args, **kwargs)-
alias for
set_fontsize
set_stretch(*args, **kwargs)-
alias for
set_fontstretch
set_style(*args, **kwargs)-
alias for
set_fontstyle
set_text(s)[source]-
Set the text string s.
It may contain newlines (
\n) or math in LaTeX syntax.Parameters: -
s : string or object castable to string (but None becomes '')
-
set_usetex(usetex)[source]-
Parameters: -
usetex : bool or None -
Whether to render using TeX,
Nonemeans to usercParams["text.usetex"].
-
set_va(*args, **kwargs)-
alias for
set_verticalalignment
set_variant(*args, **kwargs)-
alias for
set_fontvariant
set_verticalalignment(align)[source]-
Set the vertical alignment
Parameters: -
align : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
-
set_weight(*args, **kwargs)-
alias for
set_fontweight
set_wrap(wrap)[source]-
Set the wrapping state for the text.
Parameters: -
wrap : bool
-
set_x(x)[source]-
Set the x position of the text.
Parameters: -
x : float
-
set_y(y)[source]-
Set the y position of the text.
Parameters: -
y : float
-
update(kwargs)[source]-
Update properties from a dictionary.
update_bbox_position_size(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(other)[source]-
Copy properties from other to self.
zorder = 3
class matplotlib.text.TextWithDash(x=0, y=0, text='', color=None, verticalalignment='center', horizontalalignment='center', multialignment=None, fontproperties=None, rotation=None, linespacing=None, dashlength=0.0, dashdirection=0, dashrotation=None, dashpad=3, dashpush=0)[source]-
Bases:
matplotlib.text.TextThis is basically a
Textwith a dash (drawn with aLine2D) before/after it. It is intended to be a drop-in replacement forText, 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()returnsget_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 byget_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.draw(renderer)[source]-
Draw the
TextWithDashobject to the given renderer.
get_dashdirection()[source]-
Get the direction dash. 1 is before the text and 0 is after.
get_dashlength()[source]-
Get the length of the dash.
get_dashpad()[source]-
Get the extra spacing between the dash and the text, in canvas units.
get_dashpush()[source]-
Get the extra spacing between the dash and the specified text position, in canvas units.
get_dashrotation()[source]-
Get the rotation of the dash in degrees.
get_figure()[source]-
return the figure instance the artist belongs to
get_position()[source]-
Return the position of the text as a tuple (x, y)
get_prop_tup(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()[source]-
Return the unitless position of the text as a tuple (x, y)
get_window_extent(renderer=None)[source]-
Return a
Bboxobject 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 callget_window_extent()prior to the firstdraw(). For getting web page regions, it is simpler to call the method after saving the figure.
set_dashdirection(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: -
dd : int (1 is before, 0 is after)
-
set_dashlength(dl)[source]-
Set the length of the dash, in canvas units.
Parameters: -
dl : float
-
set_dashpad(dp)[source]-
Set the "pad" of the TextWithDash, which is the extra spacing between the dash and the text, in canvas units.
Parameters: -
dp : float
-
set_dashpush(dp)[source]-
Set the "push" of the TextWithDash, which is the extra spacing between the beginning of the dash and the specified position.
Parameters: -
dp : float
-
set_dashrotation(dr)[source]-
Set the rotation of the dash, in degrees.
Parameters: -
dr : float
-
set_figure(fig)[source]-
Set the figure instance the artist belongs to.
Parameters: -
fig : matplotlib.figure.Figure
-
set_position(xy)[source]-
Set the (x, y) position of the
TextWithDash.Parameters: -
xy : (float, float)
-
set_transform(t)[source]-
Set the
matplotlib.transforms.Transforminstance used by this artist.Parameters: -
t : matplotlib.transforms.Transform
-
set_x(x)[source]-
Set the x position of the
TextWithDash.Parameters: -
x : float
-
set_y(y)[source]-
Set the y position of the
TextWithDash.Parameters: -
y : float
-
update_coords(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.0.0/api/text_api.html