Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.0). For the latest version seehttps://matplotlib.org/stable/api/text_api.html
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

text

matplotlib.text

Classes for including text in a figure.

classmatplotlib.text.Annotation(s,xy,xytext=None,xycoords='data',textcoords=None,arrowprops=None,annotation_clip=None,**kwargs)

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

Annotate the pointxy with texts.

Additional kwargs are passed toText.

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 textat. If None, defaults toxy.

xycoords : str, Artist, Transform, callable or tuple, optional

The coordinate system thatxy is given in.

For astr the allowed values are:

PropertyDescription
‘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 beingannotated (default)
‘polar’(theta,r) if not native ‘data’ coordinates

If aArtist object is passed in the units arefraction if it’s bounding box.

If aTransform object is passedin use that to transformxy to screen coordinates

If a callable it must take aRendererBase object as inputand return aTransform orBbox object

If atuple must be length 2 tuple of str,Artist,Transform or callable objects. The first transform isused for thex coordinate and the second fory.

SeeAdvanced Annotation for more details.

Defaults to'data'

textcoords : str,Artist,Transform, callable or tuple, optional

The coordinate system thatxytext is given, whichmay be different than the coordinate system used forxy.

Allxycoords values are valid as well as the followingstrings:

PropertyDescription
‘offset points’offset (in points) from thexy value
‘offset pixels’offset (in pixels) from thexy value

defaults to the input ofxycoords

arrowprops : dict, optional

If not None, properties used to draw aFancyArrowPatch arrow betweenxy andxytext.

Ifarrowprops does not contain the key'arrowstyle' theallowed keys are:

KeyDescription
widththe width of the arrow in points
headwidththe width of the base of the arrow head in points
headlengththe length of the arrow head in points
shrinkfraction of total length to ‘shrink’ from both ends
?any key tomatplotlib.patches.FancyArrowPatch

If thearrowprops contains the key'arrowstyle' theabove keys are forbidden. The allowed values of'arrowstyle' are:

NameAttrs
'-'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 forFancyArrowPatch are:

KeyDescription
arrowstylethe arrow style
connectionstylethe connection style
relposdefault is (0.5, 0.5)
patchAdefault is bounding box of the text
patchBdefault is None
shrinkAdefault is 2 points
shrinkBdefault is 2 points
mutation_scaledefault is text size (in points)
mutation_aspectdefault is 1.
?any key formatplotlib.patches.PathPatch

Defaults to None

annotation_clip : bool, optional

Controls the visibility of the annotation when it goesoutside the axes area.

IfTrue, the annotation will only be drawn when thexy is inside the axes. IfFalse, the annotation willalways be drawn regardless of its position.

The default isNone, which behave asTrue only ifxycoords is “data”.

Returns:

Annotation

anncoords
contains(event)
draw(artist,renderer,*args,**kwargs)

Draw theAnnotation object to the givenrenderer.

get_window_extent(renderer=None)

Return aBbox object boundingthe text and arrow annotation, in display units.

renderer defaults to the _renderer attribute of the textobject. This is not assigned until the first execution ofdraw(), so you must use this kwarg if you wantto callget_window_extent() prior to the firstdraw(). For getting web page regions, it issimpler to call the method after saving the figure. Thedpi used defaults to self.figure.dpi; the renderer dpi isirrelevant.

set_figure(fig)
update_positions(renderer)

“Update the pixel positions of the annotated point and thetext.

xyann
classmatplotlib.text.OffsetFrom(artist,ref_coord,unit='points')

Bases:object

Callable helper class for working withAnnotation

Parameters:

artist :Artist,BboxBase, orTransform

The object to compute the offset from.

ref_coord : length 2 sequence

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’}

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

get_unit()

The unit for input to the transform used by__call__

set_unit(unit)

The unit for input to the transform used by__call__

Parameters:unit : {‘points’, ‘pixels’}
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,**kwargs)

Bases:matplotlib.artist.Artist

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

Create aText instance atx,ywith stringtext.

Valid kwargs are

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
axesanAxes instance
backgroundcolorany matplotlib color
bboxFancyBboxPatch prop dict
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colorany matplotlib color
containsa callable function
family or fontfamily or fontname or name[FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ]
figureamatplotlib.figure.Figure instance
fontproperties or font_propertiesamatplotlib.font_manager.FontProperties instance
gidan id string
horizontalalignment or ha[ ‘center’ | ‘right’ | ‘left’ ]
labelstring or anything printable with ‘%s’ conversion.
linespacingfloat (multiple of font size)
multialignment[‘left’ | ‘right’ | ‘center’ ]
path_effectsunknown
picker[None|float|boolean|callable]
position(x,y)
rasterized[True | False | None]
rotation[ angle in degrees | ‘vertical’ | ‘horizontal’ ]
rotation_modeunknown
size or fontsize[size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ]
sketch_paramsunknown
snapunknown
stretch or fontstretch[a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ]
style or fontstyle[ ‘normal’ | ‘italic’ | ‘oblique’]
textstring or anything printable with ‘%s’ conversion.
transformTransform instance
urla url string
usetexunknown
variant or fontvariant[ ‘normal’ | ‘small-caps’ ]
verticalalignment or ma or va[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
visible[True | False]
weight or fontweight[a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ]
wrapunknown
xfloat
yfloat
zorderany number
contains(mouseevent)

Test whether the mouse event occurred in the patch.

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

Returns True or False.

draw(artist,renderer,*args,**kwargs)

Draws theText object to the givenrenderer.

get_bbox_patch()

Return the bbox Patch object. Returns None if theFancyBboxPatch is not made.

get_color()

Return the color of the text

get_family()

Return the list of font families used for font lookup

get_font_properties()

alias for get_fontproperties

get_fontfamily()

alias for get_family

get_fontname()

alias for get_name

get_fontproperties()

Return theFontProperties object

get_fontsize()

alias for get_size

get_fontstretch()

alias for get_stretch

get_fontstyle()

alias for get_style

get_fontvariant()

alias for get_variant

get_fontweight()

alias for get_weight

get_ha()

alias for get_horizontalalignment

get_horizontalalignment()

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

get_name()

Return the font name as string

get_position()

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

get_prop_tup(renderer=None)

Return a hashable tuple of properties.

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

get_rotation()

return the text angle as float in degrees

get_rotation_mode()

get text rotation mode

get_size()

Return the font size as integer

get_stretch()

Get the font stretch as a string or number

get_style()

Return the font style as string

get_text()

Get the text as string

get_unitless_position()

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

get_usetex()

Return whether thisText object will render using TeX.

If the user has not manually set this value, it will default tothe value ofrcParams['text.usetex']

get_va()

alias forgetverticalalignment()

get_variant()

Return the font variant as a string

get_verticalalignment()

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

get_weight()

Get the font weight as string or number

get_window_extent(renderer=None,dpi=None)

Return aBbox object boundingthe text, in display units.

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

renderer defaults to the _renderer attribute of the textobject. This is not assigned until the first execution ofdraw(), so you must use this kwarg if you wantto callget_window_extent() prior to the firstdraw(). For getting web page regions, it issimpler to call the method after saving the figure.

dpi defaults to self.figure.dpi; the renderer dpi isirrelevant. For the web application, if figure.dpi is notthe value used when saving the figure, then the value thatwas used must be specified as thedpi argument.

get_wrap()

Returns the wrapping state for the text.

staticis_math_text(s,usetex=None)

Returns a cleaned string and a boolean flag.The flag indicates if the given strings contains any mathtext,determined by counting unescaped dollar signs. If no mathtextis present, the cleaned string has its dollar signs unescaped.If usetex is on, the flag always has the value “TeX”.

set_backgroundcolor(color)

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

See also

set_bbox()
To change the position of the bounding box.

ACCEPTS: any matplotlib color

set_bbox(rectprops)

Draw a bounding box around self. rectprops are any settableproperties for a FancyBboxPatch, e.g., facecolor=’red’, alpha=0.5.

t.set_bbox(dict(facecolor=’red’, alpha=0.5))

The default boxstyle is ‘square’. The mutationscale of the FancyBboxPatch is set to the fontsize.

ACCEPTS: FancyBboxPatch prop dict

set_clip_box(clipbox)

Set the artist’s clipBbox.

ACCEPTS: amatplotlib.transforms.Bbox instance

set_clip_on(b)

Set whether artist uses clipping.

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

ACCEPTS: [True | False]

set_clip_path(path,transform=None)

Set the artist’s clip path, which may be:

  • aPatch (or subclass) instance
  • aPath instance, in which case
    an optionalTransforminstance may be provided, which will be applied to thepath before using it for clipping.
  • None, to remove the clipping path

For efficiency, if the path happens to be an axis-alignedrectangle, this method will set the clipping box to thecorresponding rectangle and set the clipping path toNone.

ACCEPTS: [ (Path,Transform) |Patch | None ]

set_color(color)

Set the foreground color of the text

ACCEPTS: any matplotlib color

set_family(fontname)

Set the font family. May be either a single string, or a listof strings in decreasing priority. Each string may be eithera real font name or a generic font class name. If the latter,the specific font names will be looked up in thematplotlibrc file.

ACCEPTS: [FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ |
‘monospace’ ]
set_font_properties(fp)

alias for set_fontproperties

set_fontname(fontname)

alias for set_family

set_fontproperties(fp)

Set the font properties that control the text.fp must be amatplotlib.font_manager.FontProperties object.

ACCEPTS: amatplotlib.font_manager.FontProperties instance

set_fontsize(fontsize)

alias for set_size

set_fontstretch(stretch)

alias for set_stretch

set_fontstyle(fontstyle)

alias for set_style

set_fontvariant(variant)

alias for set_variant

set_fontweight(weight)

alias for set_weight

set_ha(align)

alias for set_horizontalalignment

set_horizontalalignment(align)

Set the horizontal alignment to one of

ACCEPTS: [ ‘center’ | ‘right’ | ‘left’ ]

set_linespacing(spacing)

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

ACCEPTS: float (multiple of font size)

set_ma(align)

alias for set_verticalalignment

set_multialignment(align)

Set the alignment for multiple lines layout. The layout of thebounding box of all the lines is determined bu the horizontalalignmentand verticalalignment properties, but the multiline text within thatbox can be

ACCEPTS: [‘left’ | ‘right’ | ‘center’ ]

set_name(fontname)

alias for set_family

set_position(xy)

Set the (x,y) position of the text

ACCEPTS: (x,y)

set_rotation(s)

Set the rotation of the text

ACCEPTS: [ angle in degrees | ‘vertical’ | ‘horizontal’ ]

set_rotation_mode(m)

set text rotation mode. If “anchor”, the un-rotated textwill first aligned according to theirha andva, and then will be rotated with the alignementreference point as a origin. If None (default), the text will berotated first then will be aligned.

set_size(fontsize)

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

ACCEPTS: [size in points | ‘xx-small’ | ‘x-small’ | ‘small’ |
‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ]
set_stretch(stretch)

Set the font stretch (horizontal condensation or expansion).

ACCEPTS: [a numeric value in range 0-1000 | ‘ultra-condensed’ |
‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ |‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ |‘ultra-expanded’ ]
set_style(fontstyle)

Set the font style.

ACCEPTS: [ ‘normal’ | ‘italic’ | ‘oblique’]

set_text(s)

Set the text strings

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

ACCEPTS: string or anything printable with ‘%s’ conversion.

set_usetex(usetex)

Set thisText object to render using TeX (or not).

IfNone is given, the option will be reset to use the value ofrcParams['text.usetex']

set_va(align)

alias for set_verticalalignment

set_variant(variant)

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

ACCEPTS: [ ‘normal’ | ‘small-caps’ ]

set_verticalalignment(align)

Set the vertical alignment

ACCEPTS: [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]

set_weight(weight)

Set the font weight.

ACCEPTS: [a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ |
‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ |‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ |‘extra bold’ | ‘black’ ]
set_wrap(wrap)

Sets the wrapping state for the text.

set_x(x)

Set thex position of the text

ACCEPTS: float

set_y(y)

Set they position of the text

ACCEPTS: float

update(kwargs)

Update properties from a dictionary.

update_bbox_position_size(renderer)

Update the location and the size of the bbox. This methodshould be used when the position and size of the bbox needs tobe updated before actually drawing the bbox.

update_from(other)

Copy properties from other to self

zorder = 3
classmatplotlib.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)

Bases:matplotlib.text.Text

This is basically aText with a dash(drawn with aLine2D) before/afterit. It is intended to be a drop-in replacement forText, and should behave identically toit whendashlength = 0.0.

The dash always comes between the point specified byset_position() and the text. When adash 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 thetext and 1 before. (default = 0).

dashrotation specifies the rotation of the dash, and shouldgenerally stayNone. In this caseget_dashrotation() returnsget_rotation(). (i.e., the dash takesits rotation from the text’s rotation). Because the text center isprojected onto the dash, major deviations in the rotation causewhat may be considered visually unappealing results.(default =None)

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

dashpush “pushes” the dash and text away from the pointspecified byset_position() by theamount in canvas units. (default = 0)

Note

The alignment of the two objects is based on the bounding boxof theText, as obtained byget_window_extent(). This, inturn, appears to depend on the font metrics as given by therendering backend. Hence the quality of the “centering” of thelabel text with respect to the dash varies depending on thebackend used.

Note

I’m not sure that I got theget_window_extent() right,or whether that’s sufficient for providing the object boundingbox.

draw(renderer)

Draw theTextWithDash object to the givenrenderer.

get_dashdirection()

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

get_dashlength()

Get the length of the dash.

get_dashpad()

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

get_dashpush()

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

get_dashrotation()

Get the rotation of the dash in degrees.

get_figure()

return the figure instance the artist belongs to

get_position()

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

get_prop_tup(renderer=None)

Return a hashable tuple of properties.

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

get_unitless_position()

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

get_window_extent(renderer=None)

Return aBbox object boundingthe text, in display units.

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

renderer defaults to the _renderer attribute of the textobject. This is not assigned until the first execution ofdraw(), so you must use this kwarg if you wantto callget_window_extent() prior to the firstdraw(). For getting web page regions, it issimpler to call the method after saving the figure.

set_dashdirection(dd)

Set the direction of the dash following the text.1 is before the text and 0 is after. The defaultis 0, which is what you’d want for the typicalcase of ticks below and on the left of the figure.

ACCEPTS: int (1 is before, 0 is after)

set_dashlength(dl)

Set the length of the dash.

ACCEPTS: float (canvas units)

set_dashpad(dp)

Set the “pad” of the TextWithDash, which is the extra spacingbetween the dash and the text, in canvas units.

ACCEPTS: float (canvas units)

set_dashpush(dp)

Set the “push” of the TextWithDash, whichis the extra spacing between the beginningof the dash and the specified position.

ACCEPTS: float (canvas units)

set_dashrotation(dr)

Set the rotation of the dash, in degrees

ACCEPTS: float (degrees)

set_figure(fig)

Set the figure instance the artist belong to.

ACCEPTS: amatplotlib.figure.Figure instance

set_position(xy)

Set the (x,y) position of theTextWithDash.

ACCEPTS: (x, y)

set_transform(t)

Set thematplotlib.transforms.Transform instance usedby this artist.

ACCEPTS: amatplotlib.transforms.Transform instance

set_x(x)

Set thex position of theTextWithDash.

ACCEPTS: float

set_y(y)

Set they position of theTextWithDash.

ACCEPTS: float

update_coords(renderer)

Computes the actualx,y coordinates for text based on theinputx,y and thedashlength. Since the rotation iswith respect to the actual canvas’s coordinates we need to mapback and forth.

matplotlib.text.get_rotation(rotation)

Return the text angle as float. The returnedangle is between 0 and 360 deg.

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

© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on Feb 20, 2017. Created usingSphinx 1.5.2.

[8]ページ先頭

©2009-2025 Movatter.jp