| [ Web Proxy ] |
| Viewing: https://matplotlib.org/stable/api/_as_gen/../text_api.html | [Back] [Original] |
matplotlib.text#Classes for including text in a figure.
Bases: Artist
Handle storing and drawing of text in window or data coordinates.
Create a Text instance at x, y with string text.
The text is aligned relative to the anchor point (x, y) according
to horizontalalignment (default: 'left') and verticalalignment
(default: 'baseline'). See also
Text alignment.
While Text accepts the 'label' keyword argument, by default it is not added to the handles of a legend.
Valid keyword arguments are:
Property
Description
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
float or None
bool
bool
dict with properties for
FancyBboxPatchor Noneunknown
unknown
unknown
fontfamilyorfamilyorfontname{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
list of str, or tuple of str, or None
float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
{'normal', 'italic', 'oblique'}
{'normal', 'small-caps'}
fontweightorweight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
str
{'left', 'center', 'right'}
bool
object
str or None
'normal' or float, default: 'normal'
str
bool
multialignmentorma{'left', 'right', 'center'}
bool
list of
AbstractPathEffectNone or bool or float or callable
(float, float)
bool
float or {'vertical', 'horizontal'}
{None, 'default', 'anchor', 'xtick', 'ytick'}
(scale: float, length: float, randomness: float)
bool or None
object
bool
str
bool, default:
rcParams["text.usetex"](default:False){'baseline', 'bottom', 'center', 'center_baseline', 'top'}
bool
bool
float
float
float
Return whether the mouse event occurred inside the axis-aligned bounding-box of the text.
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (Artist.get_visible
returns False).
RendererBase subclass.Notes
This method is overridden in the Artist subclasses.
Return the bbox Patch, or None if the patches.FancyBboxPatch
is not made.
For more details see Text.set_bbox.
Alias for get_fontfamily.
Alias for get_fontproperties.
Alias for get_fontproperties.
Return the font_manager.FontProperties.
Alias for get_horizontalalignment.
Return the horizontal alignment as a string. Will be one of 'left', 'center' or 'right'.
Return the font family name for math text rendered by Matplotlib.
The default value is rcParams["mathtext.fontset"] (default: 'dejavusans').
See also
Alias for get_fontname.
Alias for get_fontsize.
Alias for get_fontstyle.
Get the artist's bounding box in display space, taking clipping into account.
RendererBase, optionalRenderer used to draw the figure (i.e. fig.canvas.get_renderer()).
Bbox or NoneThe enclosing bounding box (in figure pixel coordinates), or None if clipping results in no intersection.
See also
Artist.get_window_extentGet the artist bounding box, ignoring clipping.
Return whether rotations of the transform affect the text direction.
Alias for get_verticalalignment.
Alias for get_fontvariant.
Return the vertical alignment as a string. Will be one of 'top', 'center', 'bottom', 'baseline' or 'center_baseline'.
Alias for get_fontweight.
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.
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 calling
draw_without_rendering or plt.show().
The dpi value for computing the bbox, defaults to
self.get_figure(root=True).dpi (not the renderer dpi); should be set
e.g. if to match regions with a figure saved with a custom dpi value.
Set multiple properties at once.
a.set(a=A, b=B, c=C)
is equivalent to
a.set_a(A)
a.set_b(B)
a.set_c(C)
In addition to the full property names, aliases are also supported, e.g.
set(lw=2) is equivalent to set(linewidth=2), but it is an error
to pass both simultaneously.
The order of the individual setter calls matches the order of parameters
in set(). However, most properties do not depend on each other so
that order is rarely relevant.
Supported properties are
Property
Description
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
float or None
bool
bool
dict with properties for
FancyBboxPatchor Noneunknown
unknown
unknown
{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
list of str, or tuple of str, or None
float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
{'normal', 'italic', 'oblique'}
{'normal', 'small-caps'}
{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
str
{'left', 'center', 'right'}
bool
object
str or None
'normal' or float, default: 'normal'
str
bool
{'left', 'right', 'center'}
bool
list of
AbstractPathEffectNone or bool or float or callable
(float, float)
bool
float or {'vertical', 'horizontal'}
{None, 'default', 'anchor', 'xtick', 'ytick'}
(scale: float, length: float, randomness: float)
bool or None
object
bool
str
bool, default:
rcParams["text.usetex"](default:False){'baseline', 'bottom', 'center', 'center_baseline', 'top'}
bool
bool
float
float
float
Set whether to use antialiased rendering.
Notes
Antialiasing will be determined by rcParams["text.antialiased"] (default: True)
and the parameter antialiased will have no effect if the text contains
math expressions.
Set the background color of the text.
This is realized through the bbox (see set_bbox),
creating the bbox patch if needed.
See also
set_bboxTo change the position of the bounding box
Draw a box behind/around the text.
This can be used to set a background and/or a frame around the text.
It's realized through a FancyBboxPatch behind the text (see also
Text.get_bbox_patch). The bbox patch is None by default and only
created when needed.
FancyBboxPatch or NoneThe default boxstyle is 'square'. The mutation
scale of the patches.FancyBboxPatch is set to the fontsize.
Pass None to remove the bbox patch completely.
Examples
t.set_bbox(dict(facecolor='red', alpha=0.5))
Set the artist's clip Bbox.
BboxBase or NoneWill typically be created from a TransformedBbox. For instance,
TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default
clipping for an artist added to an Axes.
Set whether the artist uses clipping.
When False, artists will be visible outside the Axes which can lead to unexpected results.
Set the artist's clip path.
Patch or Path or TransformedPath or NoneThe clip path. If given a Path, transform must be provided as
well. If None, a previously set clip path is removed.
Transform, optionalOnly 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 set), a tuple
(path, transform) is also accepted as a single positional
parameter.
Alias for set_fontfamily.
Alias for set_fontproperties.
Alias for set_fontproperties.
Set the font family. Can 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.
Set the feature tags to enable on the font.
A list of feature tags to be used with the associated font. These strings are eventually passed to HarfBuzz, and so all string formats supported by hb_feature_from_string() are supported. Note though that subranges are not explicitly supported and behaviour may change in the future.
For example, if your desired font includes Stylistic Sets which enable various typographic alternates including one that you do not wish to use (e.g., Contextual Ligatures), then you can pass the following to enable one and not the other:
fp.set_features([
'ss01', # Use Stylistic Set 1.
'-clig', # But disable Contextural Ligatures.
])
Available font feature tags may be found at https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
Alias for set_fontfamily.
One-way alias only: the getter differs.
Set the font properties that control the text.
font_manager.FontProperties or str or pathlib.PathIf a str, it is interpreted as a fontconfig pattern parsed by
FontProperties. If a pathlib.Path, it is interpreted as the
absolute path to a font file.
Set the font size.
If a float, the fontsize in points. The string values denote sizes relative to the default font size.
See also
Set the font stretch (horizontal condensation or expansion).
Set the font style.
Set the font weight.
Alias for set_horizontalalignment.
Set the horizontal alignment relative to the anchor point.
See also Text alignment.
Set the language of the text.
The language of the text in a format accepted by libraqm, namely a BCP47 language code.
If None, then defaults to rcParams["text.language"] (default: None).
Set the line spacing.
If 'normal', then the line spacing is automatically determined by font metrics for each line individually.
If a float, then line spacing will be fixed to this multiple of the font size for every line.
Alias for set_multialignment.
Set the font family for math text rendered by Matplotlib.
This does only affect Matplotlib's own math renderer. It has no effect
when rendering with TeX (usetex=True).
The name of the font family.
Available font families are defined in the default matplotlibrc file.
See also
Set the text alignment for multiline texts.
The layout of the bounding box of all the lines is determined by the horizontalalignment and verticalalignment properties. This property controls the alignment of the text lines within that box.
Alias for set_fontname.
Override switch to disable any mathtext parsing for this Text.
If False, this Text will never use mathtext. If True, mathtext
will be used if there is an even number of unescaped dollar signs.
Set the rotation of the text.
The rotation angle in degrees in mathematically positive direction (counterclockwise). 'horizontal' equals 0, 'vertical' equals 90.
Set text rotation mode.
If "default", the text will be first rotated, then aligned according
to their horizontal and vertical alignments. If "anchor", then
alignment occurs before rotation. "xtick" and "ytick" adjust the
horizontal/vertical alignment so that the text is visually pointing
towards its anchor point. This is primarily used for rotated tick
labels and positions them nicely towards their ticks. Passing
None will set the rotation mode to "default".
Alias for set_fontsize.
Alias for set_fontstretch.
Alias for set_fontstyle.
Set the text string s.
It may contain newlines (\n) or math in LaTeX syntax.
Any object gets converted to its str representation, except for
None which is converted to an empty string.
Whether rotations of the transform affect the text direction.
Whether to render using TeX, None means to use
rcParams["text.usetex"] (default: False).
Alias for set_verticalalignment.
Alias for set_fontvariant.
Set the vertical alignment relative to the anchor point.
See also Text alignment.
Alias for set_fontweight.
Set whether the text can be wrapped.
Wrapping makes sure the text is confined to the (sub)figure box. It does not take into account any other artists.
Notes
Wrapping does not work together with
savefig(..., bbox_inches='tight') (which is also used internally
by %matplotlib inline in IPython/Jupyter). The 'tight' setting
rescales the canvas to accommodate all content and happens before
wrapping.
[Discouraged] Update this artist's properties from the dictionary props.
Discouraged
This method exists for historic reasons. Please use Artist.set instead.
artist.update(props) is nowadays almost identical to
artist.set(**props) with the only difference that set will
additionally check that a property is not specified multiple times
through aliases.
Dictionary of properties (keys) and their new values.
A list of return values from the configured setters.
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.
Bases: 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.
The annotated position.
The coordinate system for xy.
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.
The text of the annotation.
The point (x, y) to annotate. The coordinate system is determined by xycoords.
The position (x, y) to place the text at. The coordinate system is determined by textcoords.
Artist or Transform or callable, default: 'data'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 |
'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 object being annotated (default) |
'polar' |
(theta, r) if not native 'data' coordinates |
Note that 'subfigure pixels' and 'figure pixels' are the same for the parent figure, so users who want code that is usable in a subfigure can use 'subfigure pixels'.
An Artist: xy is interpreted as a fraction of the artist's
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 annotation for more details.
Artist or Transform or callable, default: value of xycoordsThe 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 |
'offset fontsize' |
Offset, relative to fontsize, from the xy value |
The properties used to draw a FancyArrowPatch arrow between the
positions xy and xytext. Defaults to None, i.e. no arrow is
drawn.
For historical reasons there are two different ways to specify arrows, "simple" and "fancy":
Simple arrow:
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 |
The arrow is attached to the edge of the text box, the exact position (corners or centers) depending on where it's pointing to.
Fancy arrow:
This is used if 'arrowstyle' is provided in the arrowprops.
Valid keys are the following FancyArrowPatch 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 |
? |
Any |
The exact starting point position of the arrow is defined by relpos. It's a tuple of relative coordinates of the text box, where (0, 0) is the lower left corner and (1, 1) is the upper right corner. Values <0 and >1 are supported and specify points outside the text box. By default (0.5, 0.5), so the starting point is centered in the text box.
Whether to clip (i.e. not draw) the annotation when the annotation point xy is outside the Axes area.
If True, the annotation will be clipped when xy is outside the Axes.
If False, the annotation will always be drawn.
If None, the annotation will be clipped when xy is outside the Axes and xycoords is 'data'.
Additional kwargs are passed to Text.
See also
The coordinate system to use for Annotation.xyann.
Return whether the mouse event occurred inside the axis-aligned bounding-box of the text.
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (Artist.get_visible
returns False).
RendererBase subclass.Notes
This method is overridden in the Artist subclasses.
Return the coordinate system to use for Annotation.xyann.
See also xycoords in Annotation.
Get the artist's bounding box in display space, taking clipping into account.
RendererBase, optionalRenderer used to draw the figure (i.e. fig.canvas.get_renderer()).
Bbox or NoneThe enclosing bounding box (in figure pixel coordinates), or None if clipping results in no intersection.
See also
Artist.get_window_extentGet the artist bounding box, ignoring clipping.
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.
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 calling
draw_without_rendering or plt.show().
The dpi value for computing the bbox, defaults to
self.get_figure(root=True).dpi (not the renderer dpi); should be set
e.g. if to match regions with a figure saved with a custom dpi value.
Set multiple properties at once.
a.set(a=A, b=B, c=C)
is equivalent to
a.set_a(A)
a.set_b(B)
a.set_c(C)
In addition to the full property names, aliases are also supported, e.g.
set(lw=2) is equivalent to set(linewidth=2), but it is an error
to pass both simultaneously.
The order of the individual setter calls matches the order of parameters
in set(). However, most properties do not depend on each other so
that order is rarely relevant.
Supported properties are
Property
Description
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
float or None
bool
unknown
annotation_clipbool or None
bool
dict with properties for
FancyBboxPatchor None
BboxBaseor Nonebool
Patch or (Path, Transform) or None
unknown
fontfamilyorfamilyorfontname{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
list of str, or tuple of str, or None
float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
{'normal', 'italic', 'oblique'}
{'normal', 'small-caps'}
fontweightorweight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
str
{'left', 'center', 'right'}
bool
object
str or None
'normal' or float, default: 'normal'
str
bool
multialignmentorma{'left', 'right', 'center'}
bool
list of
AbstractPathEffectNone or bool or float or callable
(float, float)
bool
float or {'vertical', 'horizontal'}
{None, 'default', 'anchor', 'xtick', 'ytick'}
(scale: float, length: float, randomness: float)
bool or None
object
bool
str
bool, default:
rcParams["text.usetex"](default:False){'baseline', 'bottom', 'center', 'center_baseline', 'top'}
bool
bool
float
float
float
Set the coordinate system to use for Annotation.xyann.
See also xycoords in Annotation.
Set the Figure or SubFigure instance the artist belongs to.
Warning
This function should typically not be called by users.
This is a low-level API and only modifies the internal state of the Artist. Only modifying this is not enough and will typically lead to an inconsistent state, because the state of the figure has to be changed as well.
Users should typically instead call one of the high-level APIs, i.e.
Figure.add_artist or one of the Axes methods
Adding artists.
Update the pixel positions of the annotation text and the arrow patch.
The text position.
See also xytext in Annotation.
Bases: object
Callable helper class for working with Annotation.
Artist or BboxBase or TransformThe object to compute the offset from.
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.
The screen units to use (pixels or points) for the offset input.
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 the PathPatch (or other artists)
to draw this path onto the canvas.
Position of the text. For no offset, use xy=(0, 0).
The text to convert to a path.
Font size in points. Defaults to the size specified via the font properties prop.
FontProperties, optionalFont property. If not provided, will use a default
FontProperties with parameters from the
rcParams.
(Currently ignored)
Whether to use tex rendering.
Examples
The following creates a path from the string "ABC" with Helvetica font face; and another path from the latex fraction 1/2:
from matplotlib.text import TextPath
from matplotlib.font_manager import FontProperties
fp = 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 see Using a text as a Path.
Return the codes
Return the cached path after updating it if necessary.
Bases: object
A class that converts strings to paths.
Parse mathtext string s and convert it to a (vertices, codes) pair.
Convert the string s to vertices and codes using usetex mode.
Convert string s to vertices and codes using the provided ttf font.
Convert text s to path (a tuple of vertices and codes for matplotlib.path.Path).
FontPropertiesThe font properties for the text.
The text to be converted.
If True, use mathtext parser. If "TeX", use tex for rendering.
The language of the text in a format accepted by libraqm, namely a BCP47 language code.
A list of arrays containing the (x, y) coordinates of the vertices.
A list of path codes.
Examples
Create a list of vertices and codes from a text, and create a Path
from those:
from matplotlib.path import Path
from matplotlib.text import TextToPath
from matplotlib.font_manager import FontProperties
fp = FontProperties(family="Comic Neue", style="italic")
verts, codes = TextToPath().get_text_path(fp, "ABC")
path = Path(verts, codes, closed=False)
Also see TextPath for a more direct way to create a path from a text.
| Web Proxy Viewer | New URL | Original Page |