API reference¶
curved_text and CurvedText take the same arguments and make the same
artist. The function takes the axes first, as matplotlib’s helper functions do.
The class takes it after x, y, text, as matplotlib.text.Text does. The Notes
and Limits of CurvedText say what can change after creation.
- curved_text.curved_text(ax: Axes, x: ArrayLike | Sequence[Any], y: ArrayLike | Sequence[Any], text: str, *, pos: float = 0.5, anchor: str = 'center', offset: float = 0.0, box: bool | str | dict = False, crowding: str = 'none', valign: str = 'center', upright: bool = False, min_radius: float | str | None = 'auto', smooth: float | str | None = None, **kwargs: Any) CurvedText[source]¶
Draw
textalong the curve(x, y)onaxand return the artist.A short form of
CurvedText, with the same arguments and the same result. The axes is the first argument here, as in matplotlib’s other axes-first helper functions.CurvedTexttakes it afterx, y, text, asmatplotlib.text.Textdoes. Passing the axes last to this function raisesAttributeError.- Parameters:
ax (matplotlib.axes.Axes) – The axes to draw into.
x (array-like) – The curve in data coordinates: 1-D, equal length, ordered along the curve.
y (array-like) – The curve in data coordinates: 1-D, equal length, ordered along the curve.
text (str) – The string to draw. It may contain mathtext runs (
$...$).pos (float, default 0.5) – Anchor position as a fraction of the drawn arc length of the curve.
anchor ({"start", "center", "end"}, default "center") – Which part of the label sits at
pos.offset (float, default 0.0) – Distance from the curve, perpendicular to it, in points (1/72 inch).
box (bool, str, or dict, default False) – A band behind the label that clears the lines it crosses:
Truefor white, a color string, or a dict withcolor,pad, andalpha.crowding ({"none", "curvature"}, default "none") –
"curvature"adds spacing between characters on tight bends.valign ({"center", "baseline", "ascender", "descender"}, default "center") – Which line of the text lies on the curve.
upright (bool, default False) – Turn the label over where it would read upside down.
CurvedTextdescribes the rule.min_radius ({"auto"}, None, or float, default "auto") – The least radius, in points, of the path the label rides.
"auto"rounds a bend tighter than the label’s ink;Noneturns the rounding off.CurvedTextdescribes the rule.smooth ({"auto"}, None, or float, default None) – The width, in points, over which the path the label rides is smoothed.
"auto"smooths where the path wiggles under the label;Noneleaves the path as it is.CurvedTextdescribes the rule.**kwargs –
Textproperties applied to every glyph and math run, such ascolor,fontsize,alpha, andpath_effects.CurvedTextlists the properties that have no effect.
- Returns:
The label artist, already added to
ax.- Return type:
- Raises:
ValueError, TypeError, matplotlib.units.ConversionError, AttributeError – As for
CurvedText, which lists the conditions.
Notes
The layout is computed again on every draw, so the label follows the curve through resizing, panning, and zooming. See the Notes and Limits of
CurvedTextfor vector output, 3D axes, what can change after creation, removing a label, and usetex.Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> from curved_text import curved_text >>> x = np.linspace(0, 2 * np.pi, 200) >>> y = np.sin(x) >>> fig, ax = plt.subplots() >>> line, = ax.plot(x, y) >>> label = curved_text(ax, x, y, "a sine wave", pos=0.5, offset=8)
- class curved_text.CurvedText(x: ArrayLike | Sequence[Any], y: ArrayLike | Sequence[Any], text: str, axes: Axes, *, pos: float = 0.5, anchor: str = 'center', offset: float = 0.0, box: bool | str | dict = False, crowding: str = 'none', valign: str = 'center', upright: bool = False, min_radius: float | str | None = 'auto', smooth: float | str | None = None, **kwargs: Any)[source]¶
Bases:
TextA string drawn along an (x, y) curve, one glyph at a time.
Each character of
textis drawn as a per-character glyph, and each$...$run as one math run. The label follows the curve through figure layout, resizing, and interactive panning and zooming, because its layout is computed again on every draw. Usecurved_text()to add a label in one call. This class takes the axes afterx, y, text, asmatplotlib.text.Textdoes, wherecurved_text()takes it first.- Parameters:
x (array-like) – The curve in data coordinates: 1-D, equal length, and ordered along the curve. See Notes for gaps and units.
y (array-like) – The curve in data coordinates: 1-D, equal length, and ordered along the curve. See Notes for gaps and units.
text (str) – The string to draw, on one line. It may contain mathtext runs (
$...$).axes (matplotlib.axes.Axes) – The axes to draw into. It follows
x, y, texthere and comes first incurved_text().pos (float, default 0.5) – Where the label is anchored, as a fraction of the drawn arc length of the curve:
0.0is the start of the drawn curve and1.0its end. A value outside 0 to 1 places the anchor on the straight extension beyond either end of the curve. A value far outside can fall outside the figure. Passclip_on=Falseto see an anchor outside the axes. On a curve with gaps, the fraction is measured on screen along the drawn stretches (connected pieces of the curve between gaps). Zooming can move the anchor onto another stretch, and the label follows the stretch that holds its anchor. The label reads in the order of the points as they appear on screen. If the points run from right to left, the text is upside down unlessuprightis set.poscounts from the first point.anchor ({"start", "center", "end"}, default "center") – Which part of the label sits at
pos.offset (float, default 0.0) – Distance from the curve, perpendicular to it, in points (1/72 inch). Positive is to the left of the direction of travel, which is above a curve that runs from left to right. On a label turned over by
upright, positive is toward the tops of the letters. The label is laid along the parallel (offset) curve at that distance. The clearance from the curve and the spacing of the characters stay even where the curve bends steeply or asymmetrically.posandanchorare measured against the original curve and carried perpendicularly onto the offset curve.box (bool, str, or dict, default False) – A casing drawn behind the label to clear the lines it crosses: a band that follows the curve at the label’s height, under the glyphs.
Truedraws a white band; a color string sets its color; a dict acceptscolor,pad(band height relative to the tallest glyph, default1.1), andalpha. The band has rounded ends, so it extends about half its height past the first and last glyph. For a lighter casing around each glyph (a halo), pass a whitewithStrokethroughpath_effects. A wide stroke merges adjacent glyphs, soboxgives solid coverage under plain text.crowding ({"none", "curvature"}, default "none") – How to space glyphs around bends.
"none"spaces them as ordinary text does, by width and kerning (the adjustment of the space between particular pairs of characters). On the concave side of a tight bend the rotated glyphs can overlap."curvature"opens an even gap, added space between every pair of characters, that grows with the local curvature and the glyph height, so the inside edges stop colliding. A deadband (a range below which no gap is added) leaves gentle bends and straight runs unchanged.valign ({"center", "baseline", "ascender", "descender"}, default "center") – Which line of the text lies on the curve.
"center"straddles the text on the curve."baseline"places the text baseline on the curve, so the body sits above it and descenders below."ascender"and"descender"place the ascender or descender line on it. Each choice is one font-metric shift applied identically to every glyph and math run, so plain text and math stay aligned. Combine it withoffsetto lift the chosen line off the curve.upright (bool, default False) – Keep the text from reading upside down. Each draw, the label is turned over when the straight line across the stretch of curve it covers points left on screen, or straight down, so it reads left to right or from bottom to top. The label keeps its place on the curve:
posandanchorstill refer to the curve as given, so the label covers the same stretch of it. An inverted axis or a change of the view is followed on the next draw. The decision is for the whole label, so a label that winds around, as along a spiral, reads upside down where it turns. A label whose chord is near the vertical can turn over when the view changes.min_radius ({"auto"}, None, or float, default "auto") –
The least radius of curvature, in points, of the path the label rides. On the inside of a bend tighter than the label’s ink, the ink would fold over itself, and an
offsettoward the inside of a bend larger than the bend’s radius would lay the label along a path that doubles back. The label rides a rounded copy of the curve instead: a ball of the least radius is rolled along each side of the curve, and where the curve bends more tightly than the ball, the ball’s arc replaces the curve. A bend gentler than the ball is left exactly as it is."auto"takes, for each side of the path, 1.5 times the height of the label’s ink on that side: the ink above the path is on the inside of a left bend, and the ink below it is on the inside of a right bend. A number sets the radius, in points, for both sides.Noneor0turns the rounding off. The rounding is worked out on every draw, and it combines withcrowdingandoffset.At a tight bend the label leaves the curve by at most the least radius less the curve’s own radius. Two kinds of curve are outside the guarantee, and the label can fold there, as with
Noneor, near a narrow hairpin, more: a hairpin whose arms are less than about 20 degrees apart (more for a larger label), where the ball fits only beyond the reach of the ball test (about six radii of arc length), and a jagged curve that changes direction at the scale of the label’s ink, such as noisy data plotted point by point. Pass a smoothed curve for such data, or ask forsmooth.smooth ({"auto"}, None, or float, default None) –
The width, in points of arc length, over which the path the label rides is smoothed; the line itself is not changed. A line of measured data wiggles at about the width of a glyph, which tilts neighboring glyphs by different amounts and steps them up and down. The path is smoothed by a Gaussian of this standard deviation, corrected so that a smooth bend keeps its shape, and the label rides the result. The smoothing is worked out on every draw, in display space, and it comes before the rounding of
min_radiusand the offset.Noneor0turns the smoothing off. A number smooths by that width wherever the label is, so it rounds any bend narrower than the width, and it is the choice for raw, unaveraged data."auto"takes three quarters of an em, the font size, and smooths only where the path wiggles under the label: where the chords across half an em, laid end to end along the label, turn one way and then the other at least twice. A curve that turns the same way all through the label, a tight bend included, is drawn as without smoothing; a serpentine that alternates twice or more under the label is smoothed. The test is a heuristic, tuned on real monthly prices, and it switches on and off asposor the view changes: give a number for a steadier result.The label rides the smoothed path, not the line, so a line that wiggles by more than the label’s
offsetcan touch the letters. Use an offset larger than the wiggles.**kwargs –
Extra keyword arguments are
Textproperties. The font ones,fontsize,fontfamily,fontproperties,fontstyle,fontweight,math_fontfamily,parse_math, andusetex, apply to every glyph and every math run when the label is made.color,alpha,path_effects,snap,sketch_params,url,gid, and the clipping properties belong to the label and pass to its glyphs at every draw, so their setters act after construction too. The color, alpha, and path effects do not pass to theboxcasing, which has its own color and alpha. Properties that describe one text box have no effect, because the curve places every glyph:ha,va,rotation_mode,wrap,bbox,linespacing,multialignment, andbackgroundcolor.antialiasedis accepted and has no effect.label=adds no legend entry, andlegend()warns once that it has no handle for the label.transformis replaced, because glyphs are drawn in display pixels. Agidof"lab"becomes"lab-0","lab-1", and so on, numbered in order along the label, one number for each character and one for each math run (a space takes a number and draws nothing), so a saved SVG has each id once. Select the parts by prefix, for example[id^=lab-].rotationraisesValueError, because the curve sets each glyph’s angle. Useboxfor a background. An unknown property raisesAttributeError.parse_math=Falsetreats dollar signs literally (the default comes from thetext.parse_mathrcParam, a matplotlib runtime setting).clip_on(defaultTrue) clips the label at the edge of the axes;clip_on=Falselets it extend beyond them.
- Raises:
ValueError – If any of these holds: -
xandyare not 1-D arrays of equal length with at least two points. -xandyhave no two consecutive finite points. -posis not finite. -anchor,valign, orcrowdingis not one of the listed values. - Aboxdict has a key other thancolor,pad, andalpha. -rotationis passed, because the curve sets each glyph’s angle. -min_radiusorsmoothis a string other than"auto", or is negative, infinite, or NaN.TypeError – If
textis not a string,posis not a number,uprightis not a bool (1and0are not accepted),min_radiusorsmoothis notNone,"auto", or a number (a bool is not accepted), oraxesis a 3D axes.matplotlib.units.ConversionError – If the axes cannot convert the data of
xory.AttributeError – If a keyword argument is not a property of
Text.
Notes
Each glyph is laid out on one shared text baseline and mapped onto the curve from its outline. A plain character is placed rigidly, with one rotation by the chord across its own width, so its shape is undistorted. A math run is bent along the curve, so radicals (square-root signs) and fractions stay connected. Because both kinds share the baseline, plain text and math sit level, and no glyph steps up or down against its neighbors. The rotation chord follows the local tangent but averages over the glyph’s own width, so rotation stays smooth across the vertices of a coarsely sampled curve.
Gaps and units. A NaN (not a number), infinite, or masked point (a point hidden by a NumPy masked array) leaves a gap, as in
plot. The curve needs at least two consecutive finite points. A value outside the domain of a log or logit axis leaves a gap too. On a log axis these are values of 0 or below; on a logit axis, values of 0 or below and of 1 or above. A stretch is a connected piece of the curve between gaps. Any type the axes’ unit converters accept works, as forplot: dates (datetime64,datetime, pandas dates), category strings, and unit-aware values. An axis without units takes them from the curve. Category strings not yet on an axis are added to it, as ticks.A label that overruns either end of the curve, or of the stretch it follows on a curve with gaps, is not clipped. The glyphs beyond the end are placed on a straight extension of the end tangent, over a gap if there is one, and the label never continues onto another stretch. To run a label along scattered points or a curve with gaps, pass a smooth curve that follows their overall shape, such as a fit. The label never draws the curve it follows.
Mathtext. Each
$...$run is laid out by matplotlib’s mathtext engine. Every glyph outline and every bar, such as a fraction bar, is mapped onto the curve by arc length. The run sits on the same baseline as the surrounding plain glyphs. Fractions, radicals, and large brackets stay joined, because the label rides a path whose radius is at least 1.5 times the height of its ink on the inside of a bend (min_radius). Where the path bends toward the expression, its inside edge is squeezed along the curve, to a third of its natural length at the tightest bend the path allows. A curve that bends more tightly is rounded: the label leaves it to ride the rounded path, so the expression does not fold over itself.LaTeX typesetting (usetex). When
text.usetexis set orusetex=Trueis passed, LaTeX (a typesetting system) typesets the label, so it matches the other usetex text of the figure.curved_textrequireslatex, as for any matplotlib usetex figure. matplotlib’s own usetex text, such as tick labels, also needsdvipng. The usetex setting is fixed when the label is created. Set the LaTeX preamble, font family, and font lists before the figure is first drawn. Math runs are passed to LaTeX as written, so they can run TeX commands, including ones that read local files. Do not pass untrusted text with usetex on. See LaTeX typesetting (usetex) for plain text, Greek letters, the preamble, caching, andvalign.Glyphs are rendered from their outlines, not as hinted
Textartists. On a rotated label this lets one baseline be pinned exactly, at the cost of pixel-grid hinting, which matters little on rotated text. Plain text and mathtext are rendered the same way. Under usetex, matplotlib loads the glyphs with light hinting, laid out at a resolution where it is negligible.Limits.
Vector output: in PDF, SVG, PostScript, and EPS output, each character is drawn as an outline path, not as text. The label cannot be selected, searched, or edited as text, and each character is a separate shape. In PNG output the label looks as it does on screen.
Axes: Cartesian and polar axes work. On polar axes the angle runs counterclockwise, so a curve from angle 0 to π runs right to left over the top and its label reads upside down unless
uprightis set. A 3D axes raisesTypeError.Animation:
animated=Trueandax.draw_artist(label)work, so a label can be blitted. The label draws its casing and its glyphs itself, so a blitting loop that draws the label draws all of it.One artist: the label is the only artist the axes holds, so
ax.textslists the label, not its characters. Its parts have no zorder of their own: the casing and then the glyphs draw at the label’s zorder.After creation:
set_visible,set_zorder,set_animated,set_alpha,set_color,set_path_effects,set_gid,set_url,set_rasterized,set_snap,set_sketch_params, and the clipping setters act on what is drawn. The text, the font, the curve, and the placement arguments are fixed when the label is made: remove the label and make a new one to change them.Lifecycle:
label.remove()removes the label.ax.clear()removes it with the other artists. A figure that holds a label can be pickled.legend(loc="best")avoids the label from matplotlib 3.9.pos:posis a fraction of the curve you pass in, including any part outside the axes limits: pass the visible piece of the curve. A value outside 0 to 1 places the anchor on the straight extension beyond an end; a value far outside can place it outside the figure. Useclip_on=Falseto see an anchor outside the axes.Axis limits: the label does not change the data limits. Plot the curve first, or set the limits yourself.
Cost: the time of a draw grows with the number of characters and the number of curve points, and is paid on every redraw. If interactive pan and zoom feels slow, pass fewer points: decimate or smooth the curve. Dozens of labels draw in well under a second.
Text: one line. A newline in the string is not a line break.
After creation.
curved_text()andCurvedTexttake the same arguments and make the same artist. Keep the returned object to hide it (set_visible), restack it (set_zorder), change its clipping, or remove it (remove()). To change the text, color, size, or curve, remove the label and make a new one.get_text()does not return the label’s string.- set_figure(fig) None[source]¶
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.
- Parameters:
fig (~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure)
- remove() None[source]¶
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g., with .FigureCanvasBase.draw_idle. Call ~.axes.Axes.relim to update the Axes limits if desired.
Note: there is no support for removing the artist’s legend entry.
- draw(renderer, *args, **kwargs) None[source]¶
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).
- Parameters:
renderer (~matplotlib.backend_bases.RendererBase subclass.)
Notes
This method is overridden in the Artist subclasses.
- get_window_extent(renderer=None, dpi=None) Bbox[source]¶
The extent of the label as drawn, in display pixels: its glyphs and its box casing.
Figure layout (
bbox_inches="tight", constrained layout, and from matplotlib 3.9legend(loc="best")) measures the label through it. The label is placed on the curve to be measured, even before its first draw. The container’s own Text takes no part. Each glyph counts by the box of its outline’s control points. The box can exceed the ink by a fraction of a pixel and never falls short of it. The casing counts by its band, half its line width beyond its centerline on every side.Without a renderer, the label is measured at the figure’s dpi (dots per inch).
dpiscales the extent to that resolution. A hidden label has an empty extent at the curve’s first shown point. So has a label that cannot be placed: an empty label, a label off any axes, a curve with no stretch left to draw, or a degenerate curve.Repeated measurements reuse the last placement while the renderer, the curve position, and the glyphs are unchanged.