matplotlib.text#

Classes for including text in a figure.

classmatplotlib.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,transform_rotates_text=False,parse_math=None,antialiased=None,**kwargs)[source]#

Bases:Artist

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

Create aText instance atx,y with stringtext.

The text is aligned relative to the anchor point (x,y) accordingtohorizontalalignment (default: 'left') andverticalalignment(default: 'baseline'). See alsoText alignment.

While Text accepts the 'label' keyword argument, by default it is notadded to the handles of a legend.

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 and two offsets from the bottom left corner of the image

alpha

float or None

animated

bool

antialiased

bool

backgroundcolor

color

bbox

dict with properties forpatches.FancyBboxPatch

clip_box

unknown

clip_on

unknown

clip_path

unknown

color orc

color

figure

Figure orSubFigure

fontfamily orfamily orfontname

{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

fontproperties orfont orfont_properties

font_manager.FontProperties orstr orpathlib.Path

fontsize orsize

float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

fontstretch orstretch

{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}

fontstyle orstyle

{'normal', 'italic', 'oblique'}

fontvariant orvariant

{'normal', 'small-caps'}

fontweight orweight

{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 orha

{'left', 'center', 'right'}

in_layout

bool

label

object

linespacing

float (multiple of font size)

math_fontfamily

str

mouseover

bool

multialignment orma

{'left', 'right', 'center'}

parse_math

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

position

(float, float)

rasterized

bool

rotation

float or {'vertical', 'horizontal'}

rotation_mode

{None, 'default', 'anchor'}

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

text

object

transform

Transform

transform_rotates_text

bool

url

str

usetex

bool, default:rcParams["text.usetex"] (default:False)

verticalalignment orva

{'baseline', 'bottom', 'center', 'center_baseline', 'top'}

visible

bool

wrap

bool

x

float

y

float

zorder

float

contains(mouseevent)[source]#

Return whether the mouse event occurred inside the axis-alignedbounding-box of the text.

draw(renderer)[source]#

Draw the Artist (and its children) using the given renderer.

This has no effect if the artist is not visible (Artist.get_visiblereturns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

get_antialiased()[source]#

Return whether antialiased rendering is used.

get_bbox_patch()[source]#

Return the bbox Patch, or None if thepatches.FancyBboxPatchis not made.

get_c()[source]#

Alias forget_color.

get_color()[source]#

Return the color of the text.

get_family()[source]#

Alias forget_fontfamily.

get_font()[source]#

Alias forget_fontproperties.

get_font_properties()[source]#

Alias forget_fontproperties.

get_fontfamily()[source]#

Return the list of font families used for font lookup.

get_fontname()[source]#

Return the font name as a string.

get_fontproperties()[source]#

Return thefont_manager.FontProperties.

get_fontsize()[source]#

Return the font size as an integer.

get_fontstyle()[source]#

Return the font style as a string.

get_fontvariant()[source]#

Return the font variant as a string.

get_fontweight()[source]#

Return the font weight as a string or a number.

get_ha()[source]#

Alias forget_horizontalalignment.

get_horizontalalignment()[source]#

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

get_math_fontfamily()[source]#

Return the font family name for math text rendered by Matplotlib.

The default value isrcParams["mathtext.fontset"] (default:'dejavusans').

get_name()[source]#

Alias forget_fontname.

get_parse_math()[source]#

Return whether mathtext parsing is considered for thisText.

get_position()[source]#

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

get_rotation()[source]#

Return the text angle in degrees between 0 and 360.

get_rotation_mode()[source]#

Return the text rotation mode.

get_size()[source]#

Alias forget_fontsize.

get_stretch()[source]#

Return the font stretch as a string or a number.

get_style()[source]#

Alias forget_fontstyle.

get_text()[source]#

Return the text string.

get_transform_rotates_text()[source]#

Return whether rotations of the transform affect the text direction.

get_unitless_position()[source]#

Return the (x, y) unitless position of the text.

get_usetex()[source]#

Return whether thisText object uses TeX for rendering.

get_va()[source]#

Alias forget_verticalalignment.

get_variant()[source]#

Alias forget_fontvariant.

get_verticalalignment()[source]#

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

get_weight()[source]#

Alias forget_fontweight.

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

Return theBbox bounding the text, in display units.

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

Parameters:
rendererRenderer, optional

A renderer is needed to compute the bounding box. If the artisthas already been drawn, the renderer is cached; thus, it is onlynecessary to pass this argument when callingget_window_extentbefore the first draw. In practice, it is usually easier totrigger a draw first, e.g. by callingdraw_without_rendering orplt.show().

dpifloat, optional

The dpi value for computing the bbox, defaults toself.get_figure(root=True).dpi (not the renderer dpi); should be sete.g. if to match regions with a figure saved with a custom dpi value.

get_wrap()[source]#

Return whether the text can be wrapped.

set(*,agg_filter=<UNSET>,alpha=<UNSET>,animated=<UNSET>,antialiased=<UNSET>,backgroundcolor=<UNSET>,bbox=<UNSET>,clip_box=<UNSET>,clip_on=<UNSET>,clip_path=<UNSET>,color=<UNSET>,fontfamily=<UNSET>,fontproperties=<UNSET>,fontsize=<UNSET>,fontstretch=<UNSET>,fontstyle=<UNSET>,fontvariant=<UNSET>,fontweight=<UNSET>,gid=<UNSET>,horizontalalignment=<UNSET>,in_layout=<UNSET>,label=<UNSET>,linespacing=<UNSET>,math_fontfamily=<UNSET>,mouseover=<UNSET>,multialignment=<UNSET>,parse_math=<UNSET>,path_effects=<UNSET>,picker=<UNSET>,position=<UNSET>,rasterized=<UNSET>,rotation=<UNSET>,rotation_mode=<UNSET>,sketch_params=<UNSET>,snap=<UNSET>,text=<UNSET>,transform=<UNSET>,transform_rotates_text=<UNSET>,url=<UNSET>,usetex=<UNSET>,verticalalignment=<UNSET>,visible=<UNSET>,wrap=<UNSET>,x=<UNSET>,y=<UNSET>,zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties 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 and two offsets from the bottom left corner of the image

alpha

float or None

animated

bool

antialiased

bool

backgroundcolor

color

bbox

dict with properties forpatches.FancyBboxPatch

clip_box

unknown

clip_on

unknown

clip_path

unknown

color

color

figure

Figure orSubFigure

fontfamily orfontname

{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

fontproperties

font_manager.FontProperties orstr orpathlib.Path

fontsize

float or {'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'}

gid

str

horizontalalignment

{'left', 'center', 'right'}

in_layout

bool

label

object

linespacing

float (multiple of font size)

math_fontfamily

str

mouseover

bool

multialignment

{'left', 'right', 'center'}

parse_math

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

position

(float, float)

rasterized

bool

rotation

float or {'vertical', 'horizontal'}

rotation_mode

{None, 'default', 'anchor'}

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

text

object

transform

Transform

transform_rotates_text

bool

url

str

usetex

bool, default:rcParams["text.usetex"] (default:False)

verticalalignment

{'baseline', 'bottom', 'center', 'center_baseline', 'top'}

visible

bool

wrap

bool

x

float

y

float

zorder

float

set_antialiased(antialiased)[source]#

Set whether to use antialiased rendering.

Parameters:
antialiasedbool

Notes

Antialiasing will be determined byrcParams["text.antialiased"] (default:True)and the parameterantialiased will have no effect if the text containsmath expressions.

set_backgroundcolor(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(rectprops)[source]#

Draw a bounding box around self.

Parameters:
rectpropsdict with properties forpatches.FancyBboxPatch

The default boxstyle is 'square'. The mutationscale of thepatches.FancyBboxPatch is set to the fontsize.

Examples

t.set_bbox(dict(facecolor='red',alpha=0.5))
set_c(color)[source]#

Alias forset_color.

set_clip_box(clipbox)[source]#

Set the artist's clipBbox.

Parameters:
clipboxBboxBase or None

Will typically be created from aTransformedBbox. For instance,TransformedBbox(Bbox([[0,0],[1,1]]),ax.transAxes) is the defaultclipping for an artist added to an Axes.

set_clip_on(b)[source]#

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes whichcan lead to unexpected results.

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

Set the artist's clip path.

Parameters:
pathPatch orPath orTransformedPath or None

The clip path. If given aPath,transform must be provided aswell. IfNone, a previously set clip path is removed.

transformTransform, optional

Only used ifpath is aPath, in which case the givenPathis converted to aTransformedPath usingtransform.

Notes

For efficiency, ifpath is aRectangle this method will set theclipping box to the corresponding rectangle and set the clipping pathtoNone.

For technical reasons (support ofset), a tuple(path,transform) is also accepted as a single positionalparameter.

set_color(color)[source]#

Set the foreground color of the text

Parameters:
colorcolor
set_family(fontname)[source]#

Alias forset_fontfamily.

set_font(fp)[source]#

Alias forset_fontproperties.

set_font_properties(fp)[source]#

Alias forset_fontproperties.

set_fontfamily(fontname)[source]#

Set the font family. Can be either a single string, or a list ofstrings in decreasing priority. Each string may be either a real fontname or a generic font class name. If the latter, the specific fontnames will be looked up in the corresponding rcParams.

If aText instance is constructed withfontfamily=None, then thefont is set torcParams["font.family"] (default:['sans-serif']), and thesame is done whenset_fontfamily() is called on an existingText instance.

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

Alias forset_fontfamily.

One-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:
fpfont_manager.FontProperties orstr orpathlib.Path

If astr, it is interpreted as a fontconfig pattern parsed byFontProperties. If apathlib.Path, it is interpreted as theabsolute path to a font file.

set_fontsize(fontsize)[source]#

Set the font size.

Parameters:
fontsizefloat or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

If a float, the fontsize in points. The string values denote sizesrelative to the default font size.

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.

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(align)[source]#

Alias forset_horizontalalignment.

set_horizontalalignment(align)[source]#

Set the horizontal alignment relative to the anchor point.

See alsoText alignment.

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

Set the line spacing as a multiple of the font size.

The default line spacing is 1.2.

Parameters:
spacingfloat (multiple of font size)
set_ma(align)[source]#

Alias forset_multialignment.

set_math_fontfamily(fontfamily)[source]#

Set the font family for math text rendered by Matplotlib.

This does only affect Matplotlib's own math renderer. It has no effectwhen rendering with TeX (usetex=True).

Parameters:
fontfamilystr

The name of the font family.

Available font families are defined in thedefault matplotlibrc file.

set_multialignment(align)[source]#

Set the text alignment for multiline texts.

The layout of the bounding box of all the lines is determined by thehorizontalalignment and verticalalignment properties. This propertycontrols the alignment of the text lines within that box.

Parameters:
align{'left', 'right', 'center'}
set_name(fontname)[source]#

Alias forset_fontname.

set_parse_math(parse_math)[source]#

Override switch to disable any mathtext parsing for thisText.

Parameters:
parse_mathbool

If False, thisText will never use mathtext. If True, mathtextwill be used if there is an even number of unescaped dollar signs.

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:
sfloat or {'vertical', 'horizontal'}

The rotation angle in degrees in mathematically positive direction(counterclockwise). 'horizontal' equals 0, 'vertical' equals 90.

set_rotation_mode(m)[source]#

Set text rotation mode.

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

If"default", the text will be first rotated, then aligned accordingto their horizontal and vertical alignments. If"anchor", thenalignment occurs before rotation. PassingNone will set the rotationmode to"default".

set_size(fontsize)[source]#

Alias forset_fontsize.

set_stretch(stretch)[source]#

Alias forset_fontstretch.

set_style(fontstyle)[source]#

Alias forset_fontstyle.

set_text(s)[source]#

Set the text strings.

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

Parameters:
sobject

Any object gets converted to itsstr representation, except forNone which is converted to an empty string.

set_transform_rotates_text(t)[source]#

Whether rotations of the transform affect the text direction.

Parameters:
tbool
set_usetex(usetex)[source]#
Parameters:
usetexbool or None

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

set_va(align)[source]#

Alias forset_verticalalignment.

set_variant(variant)[source]#

Alias forset_fontvariant.

set_verticalalignment(align)[source]#

Set the vertical alignment relative to the anchor point.

See alsoText alignment.

Parameters:
align{'baseline', 'bottom', 'center', 'center_baseline', 'top'}
set_weight(weight)[source]#

Alias forset_fontweight.

set_wrap(wrap)[source]#

Set whether the text can be wrapped.

Wrapping makes sure the text is confined to the (sub)figure box. Itdoes not take into account any other artists.

Parameters:
wrapbool

Notes

Wrapping does not work together withsavefig(...,bbox_inches='tight') (which is also used internallyby%matplotlibinline in IPython/Jupyter). The 'tight' settingrescales the canvas to accommodate all content and happens beforewrapping.

set_x(x)[source]#

Set thex position of the text.

Parameters:
xfloat
set_y(y)[source]#

Set they position of the text.

Parameters:
yfloat
update(kwargs)[source]#

Update this artist's properties from the dictprops.

Parameters:
propsdict
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 needsto be updated before actually drawing the bbox.

update_from(other)[source]#

Copy properties fromother toself.

zorder=3#
classmatplotlib.text.Annotation(text,xy,xytext=None,xycoords='data',textcoords=None,arrowprops=None,annotation_clip=None,**kwargs)[source]#

Bases:Text,_AnnotationBase

AnAnnotation is aText that can refer to a specific positionxy.Optionally an arrow pointing from the text toxy can be drawn.

Attributes:
xy

The annotated position.

xycoords

The coordinate system forxy.

arrow_patch

AFancyArrowPatch to point fromxytext toxy.

Annotate the pointxy with texttext.

In the simplest form, the text is placed atxy.

Optionally, the text can be displayed in another positionxytext.An arrow pointing from the text to the annotated pointxy can thenbe added by definingarrowprops.

Parameters:
textstr

The text of the annotation.

xy(float, float)

The point(x, y) to annotate. The coordinate system is determinedbyxycoords.

xytext(float, float), default:xy

The position(x, y) to place the text at. The coordinate systemis determined bytextcoords.

xycoordssingle or two-tuple of str orArtist orTransform or callable, default: 'data'

The coordinate system thatxy is given in. The following typesof 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

    'subfigure points'

    Points from the lower left of the subfigure

    'subfigure pixels'

    Pixels from the lower left of the subfigure

    'subfigure fraction'

    Fraction of subfigure from lower left

    'axes points'

    Points from lower left corner of the Axes

    'axes pixels'

    Pixels from lower left corner of the Axes

    'axes fraction'

    Fraction of Axes from lower left

    'data'

    Use the coordinate system of the objectbeing annotated (default)

    'polar'

    (theta, r) if not native 'data'coordinates

    Note that 'subfigure pixels' and 'figure pixels' are the samefor the parent figure, so users who want code that is usable ina subfigure can use 'subfigure pixels'.

  • AnArtist:xy is interpreted as a fraction of the artist'sBbox. E.g.(0, 0) would be the lowerleft corner of the bounding box and(0.5, 1) would be thecenter top of the bounding box.

  • ATransform to transformxy to screen coordinates.

  • A function with one of the following signatures:

    deftransform(renderer)->Bboxdeftransform(renderer)->Transform

    whererenderer is aRendererBase subclass.

    The result of the function is interpreted like theArtist andTransform cases above.

  • A tuple(xcoords, ycoords) specifying separate coordinatesystems forx andy.xcoords andycoords must each beof one of the above described types.

SeeAdvanced annotation for more details.

textcoordssingle or two-tuple of str orArtist orTransform or callable, default: value ofxycoords

The coordinate system thatxytext is given in.

Allxycoords values are valid as well as the following strings:

Value

Description

'offset points'

Offset, in points, from thexy value

'offset pixels'

Offset, in pixels, from thexy value

'offset fontsize'

Offset, relative to fontsize, from thexy value

arrowpropsdict, optional

The properties used to draw aFancyArrowPatch arrow between thepositionsxy andxytext. Defaults to None, i.e. no arrow isdrawn.

For historical reasons there are two different ways to specifyarrows, "simple" and "fancy":

Simple arrow:

Ifarrowprops does not contain the key 'arrowstyle' theallowed 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

?

AnyFancyArrowPatch property

The arrow is attached to the edge of the text box, the exactposition (corners or centers) depending on where it's pointing to.

Fancy arrow:

This is used if 'arrowstyle' is provided in thearrowprops.

Valid keys are the followingFancyArrowPatch parameters:

Key

Description

arrowstyle

The arrow style

connectionstyle

The connection style

relpos

See below; default is (0.5, 0.5)

patchA

Default is bounding box of the text

patchB

Default is None

shrinkA

In points. Default is 2 points

shrinkB

In points. Default is 2 points

mutation_scale

Default is text size (in points)

mutation_aspect

Default is 1

?

AnyFancyArrowPatch property

The exact starting point position of the arrow is defined byrelpos. It's a tuple of relative coordinates of the text box,where (0, 0) is the lower left corner and (1, 1) is the upperright corner. Values <0 and >1 are supported and specify pointsoutside the text box. By default (0.5, 0.5), so the starting pointis centered in the text box.

annotation_clipbool or None, default: None

Whether to clip (i.e. not draw) the annotation when the annotationpointxy is outside the Axes area.

  • IfTrue, the annotation will be clipped whenxy is outsidethe Axes.

  • IfFalse, the annotation will always be drawn.

  • IfNone, the annotation will be clipped whenxy is outsidethe Axes andxycoords is 'data'.

**kwargs

Additional kwargs are passed toText.

Returns:
Annotation

See also

Annotations
propertyanncoords#

The coordinate system to use forAnnotation.xyann.

contains(mouseevent)[source]#

Return whether the mouse event occurred inside the axis-alignedbounding-box of the text.

draw(renderer)[source]#

Draw the Artist (and its children) using the given renderer.

This has no effect if the artist is not visible (Artist.get_visiblereturns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

get_anncoords()[source]#

Return the coordinate system to use forAnnotation.xyann.

See alsoxycoords inAnnotation.

get_tightbbox(renderer=None)[source]#

LikeArtist.get_window_extent, but includes any clipping.

Parameters:
rendererRendererBase subclass, optional

renderer that will be used to draw the figures (i.e.fig.canvas.get_renderer())

Returns:
Bbox or None

The enclosing bounding box (in figure pixel coordinates).Returns None if clipping results in no intersection.

get_window_extent(renderer=None)[source]#

Return theBbox bounding the text, in display units.

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

Parameters:
rendererRenderer, optional

A renderer is needed to compute the bounding box. If the artisthas already been drawn, the renderer is cached; thus, it is onlynecessary to pass this argument when callingget_window_extentbefore the first draw. In practice, it is usually easier totrigger a draw first, e.g. by callingdraw_without_rendering orplt.show().

dpifloat, optional

The dpi value for computing the bbox, defaults toself.get_figure(root=True).dpi (not the renderer dpi); should be sete.g. if to match regions with a figure saved with a custom dpi value.

set(*,agg_filter=<UNSET>,alpha=<UNSET>,animated=<UNSET>,anncoords=<UNSET>,annotation_clip=<UNSET>,antialiased=<UNSET>,backgroundcolor=<UNSET>,bbox=<UNSET>,clip_box=<UNSET>,clip_on=<UNSET>,clip_path=<UNSET>,color=<UNSET>,fontfamily=<UNSET>,fontproperties=<UNSET>,fontsize=<UNSET>,fontstretch=<UNSET>,fontstyle=<UNSET>,fontvariant=<UNSET>,fontweight=<UNSET>,gid=<UNSET>,horizontalalignment=<UNSET>,in_layout=<UNSET>,label=<UNSET>,linespacing=<UNSET>,math_fontfamily=<UNSET>,mouseover=<UNSET>,multialignment=<UNSET>,parse_math=<UNSET>,path_effects=<UNSET>,picker=<UNSET>,position=<UNSET>,rasterized=<UNSET>,rotation=<UNSET>,rotation_mode=<UNSET>,sketch_params=<UNSET>,snap=<UNSET>,text=<UNSET>,transform=<UNSET>,transform_rotates_text=<UNSET>,url=<UNSET>,usetex=<UNSET>,verticalalignment=<UNSET>,visible=<UNSET>,wrap=<UNSET>,x=<UNSET>,y=<UNSET>,zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties 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 and two offsets from the bottom left corner of the image

alpha

float or None

animated

bool

anncoords

unknown

annotation_clip

bool or None

antialiased

bool

backgroundcolor

color

bbox

dict with properties forpatches.FancyBboxPatch

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

color orc

color

figure

unknown

fontfamily orfamily orfontname

{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

fontproperties orfont orfont_properties

font_manager.FontProperties orstr orpathlib.Path

fontsize orsize

float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

fontstretch orstretch

{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}

fontstyle orstyle

{'normal', 'italic', 'oblique'}

fontvariant orvariant

{'normal', 'small-caps'}

fontweight orweight

{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 orha

{'left', 'center', 'right'}

in_layout

bool

label

object

linespacing

float (multiple of font size)

math_fontfamily

str

mouseover

bool

multialignment orma

{'left', 'right', 'center'}

parse_math

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

position

(float, float)

rasterized

bool

rotation

float or {'vertical', 'horizontal'}

rotation_mode

{None, 'default', 'anchor'}

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

text

object

transform

Transform

transform_rotates_text

bool

url

str

usetex

bool, default:rcParams["text.usetex"] (default:False)

verticalalignment orva

{'baseline', 'bottom', 'center', 'center_baseline', 'top'}

visible

bool

wrap

bool

x

float

y

float

zorder

float

set_anncoords(coords)[source]#

Set the coordinate system to use forAnnotation.xyann.

See alsoxycoords inAnnotation.

set_figure(fig)[source]#

Set theFigure orSubFigure instance the artist belongs to.

Parameters:
figFigure orSubFigure
update_positions(renderer)[source]#

Update the pixel positions of the annotation text and the arrow patch.

propertyxyann#

The text position.

See alsoxytext inAnnotation.

propertyxycoords#
classmatplotlib.text.OffsetFrom(artist,ref_coord,unit='points')[source]#

Bases:object

Callable helper class for working withAnnotation.

Parameters:
artistArtist orBboxBase orTransform

The object to compute the offset from.

ref_coord(float, float)

Ifartist is anArtist orBboxBase, this values isthe location to of the offset origin in fractions of theartist bounding box.

Ifartist is a transform, the offset origin is thetransform applied to this value.

unit{'points, 'pixels'}, default: 'points'

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

get_unit()[source]#

Return the unit for input to the transform used by__call__.

set_unit(unit)[source]#

Set the unit for input to the transform used by__call__.

Parameters:
unit{'points', 'pixels'}
classmatplotlib.text.TextPath(xy,s,size=None,prop=None,_interpolation_steps=1,usetex=False)[source]#

Bases:Path

Create a path from the text.

Create a path from the text. Note that it simply is a path,not an artist. You need to use thePathPatch (or other artists)to draw this path onto the canvas.

Parameters:
xytuple or array of two float values

Position of the text. For no offset, usexy=(0,0).

sstr

The text to convert to a path.

sizefloat, optional

Font size in points. Defaults to the size specified via the fontpropertiesprop.

propFontProperties, optional

Font property. If not provided, will use a defaultFontProperties with parameters from thercParams.

_interpolation_stepsint, optional

(Currently ignored)

usetexbool, default: False

Whether to use tex rendering.

Examples

The following creates a path from the string "ABC" with Helveticafont face; and another path from the latex fraction 1/2:

frommatplotlib.textimportTextPathfrommatplotlib.font_managerimportFontPropertiesfp=FontProperties(family="Helvetica",style="italic")path1=TextPath((12,12),"ABC",size=12,prop=fp)path2=TextPath((0,0),r"$\frac{1}{2}$",size=12,usetex=True)

Also seeUsing a text as a Path.

propertycodes#

Return the codes

get_size()[source]#

Get the text size.

set_size(size)[source]#

Set the text size.

propertyvertices#

Return the cached path after updating it if necessary.

classmatplotlib.text.TextToPath[source]#

Bases:object

A class that converts strings to paths.

DPI=72#
FONT_SCALE=100.0#
get_glyphs_mathtext(prop,s,glyph_map=None,return_new_glyphs_only=False)[source]#

Parse mathtext strings and convert it to a (vertices, codes) pair.

get_glyphs_tex(prop,s,glyph_map=None,return_new_glyphs_only=False)[source]#

Convert the strings to vertices and codes using usetex mode.

get_glyphs_with_font(font,s,glyph_map=None,return_new_glyphs_only=False)[source]#

Convert strings to vertices and codes using the provided ttf font.

get_text_path(prop,s,ismath=False)[source]#

Convert texts to path (a tuple of vertices and codes formatplotlib.path.Path).

Parameters:
propFontProperties

The font properties for the text.

sstr

The text to be converted.

ismath{False, True, "TeX"}

If True, use mathtext parser. If "TeX", use tex for rendering.

Returns:
vertslist

A list of arrays containing the (x, y) coordinates of the vertices.

codeslist

A list of path codes.

Examples

Create a list of vertices and codes from a text, and create aPathfrom those:

frommatplotlib.pathimportPathfrommatplotlib.textimportTextToPathfrommatplotlib.font_managerimportFontPropertiesfp=FontProperties(family="Comic Neue",style="italic")verts,codes=TextToPath().get_text_path(fp,"ABC")path=Path(verts,codes,closed=False)

Also seeTextPath for a more direct way to create a path from a text.

get_text_width_height_descent(s,prop,ismath)[source]#
On this page