curved-text
Draw text that follows an arbitrary curve in matplotlib.
A label along its own curve replaces a legend, so the reader does not look away from the data to decode a color key. In (a) below, a legend identifies the lines. In (b), the same lines carry labels along the curves.
The label is recomputed every time the figure is drawn, so it keeps following the curve through layout changes, resizing, and interactive panning or zooming.
Install
pip install curved-text
Requires Python 3.9 or later, matplotlib 3.5 or later, and numpy 1.20 or later. seaborn and pandas are optional.
To work from a clone, install it in editable mode:
pip install -e .
The Gallery scripts need the extra dependencies. From a clone, run
pip install -e ".[examples]".
Usage
import numpy as np
import matplotlib.pyplot as plt
from curved_text import curved_text
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
curved_text(ax, x, y, "text that follows the curve",
pos=0.5, anchor="center", offset=8.0,
color="#b06306", fontsize=13)
plt.show()
The label follows the curve, and each character turns to match the curve under it:
More figures: Gallery. Every parameter: application programming interface (API) reference. Known limits (3D axes, text in vector files, and what cannot change after creation) are listed under Limits.
Choosing a curve
- The curve
(x, y)must be ordered along its length: each point comes after the one before it. It needs at least two points. - The curve should be smooth relative to the text size: it should have no bend
smaller than one character, or the glyphs overlap. Label a fitted or smoothed
copy of the data and leave that copy unplotted. A polynomial fit
(
numpy.polyfit) works, and so does a Gaussian filter about one character wide. A short running mean usually does not. For measured data,smooth(see Labels on measured data) smooths the path the label rides and leaves the line as it is. - The label reads in the order of the points on screen. A curve that runs from
right to left reads upside down unless
upright=True: see Placement. - The curve is in data coordinates, and the
transformkeyword is ignored. To place a label with axes fractions, convert the points to data coordinates first:ax.transData.inverted().transform(ax.transAxes.transform(points)).
Placement
Five independent parameters control where the label sits:
possets where the label is anchored along the curve, as a fraction of the curve's length.0.0is the start of the curve and1.0is its end. The default is0.5.anchorsets which part of the label lands atpos:"start","center", or"end". The default is"center".offsetshifts the label perpendicular to the curve, in points (1/72 inch). A positive value sits above a left-to-right curve. The default is0.0.valignsets which line of the text lies on the curve:"center","baseline","ascender", or"descender". The default is"center". See Vertical alignment (valign) below.uprightturns the label over where it would read upside down. It is off by default. The paragraph after the next figure describes it.
The next figure sweeps pos from the first point to the last. The ring marks
the anchor point in each panel.
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. Pass upright=True to
turn the label over wherever it would read upside down, such as for contour
labels and curves on an inverted axis. The label keeps its place on the curve,
and a positive offset is then toward the tops of the letters. The decision is
for the whole label, so one that winds around, as along a spiral, still reads
upside down where it turns. pos counts from the first point. The Gallery
section Why a label reads upside down: direction of
travel
shows the cases.
If the label runs past either end of the curve, it is not cut off. The curve continues straight in the direction it had at that end, and the extra glyphs sit on that straight line.
Curves with gaps and log axes
A curve with NaN (not a number), infinite, or masked points (points hidden by a
NumPy masked array) has gaps, as plot draws it. So does a curve with points
the axes cannot show. These are values of 0 or less on a log axis, and values
of 0 or less or 1 or more on a logit axis, whatever the nonpositive setting.
A stretch is a connected piece of the curve between gaps. pos counts only the
drawn length. The label follows the stretch that holds its anchor. It continues
straight past the ends of that stretch, over a gap if there is one, and never
continues onto another stretch. Lengths are measured on screen, so zooming can
move the anchor onto another stretch.
To label a curve with gaps, or scattered points, pass curved_text a smooth
curve that follows their overall shape, such as a fit or a smoothed copy. Leave
that curve unplotted: the label never draws the curve it follows.
In the next figure, the label follows one stretch of three curves with gaps: NaN points in (a), masked points in (b), and zeros on a log axis in (c).
Text cut off at the axes edge
A label is clipped to the axes, as lines are. Glyphs that run past the edge of
the axes are cut there. matplotlib's own ax.text is not clipped by default.
Pass clip_on=False to draw the whole label wherever its curve goes. A tight
bounding box (bbox_inches="tight") and constrained layout then make room for
it.
Dates, categories, and units
The curve takes the same data plot does: dates (datetime64, datetime,
pandas dates), category strings, and values with units. The axes convert them
as they convert the plotted line, so the label stays on it.
days = np.arange("2024-01-01", "2025-01-01", dtype="datetime64[D]")
# Day length at 40° N, from the sun's declination on each day of the year.
n = np.arange(days.size)
declination = np.radians(23.44) * np.sin(2 * np.pi * (n - 80) / 365)
hours = 24 / np.pi * np.arccos(-np.tan(np.radians(40)) * np.tan(declination))
fig, ax = plt.subplots()
ax.plot(days, hours)
curved_text(ax, days, hours, "day length at 40° N", pos=0.3, offset=6.0)
A label created before anything is plotted sets up the axis for its data, as
plot does. Category strings not yet on an axis are added to it, as ticks.
Data an axis cannot convert, such as strings on a date axis, raises
matplotlib's ConversionError when the label is made.
The function and the class
The class form of the same call is CurvedText:
from curved_text import CurvedText
CurvedText(x, y, "along the curve", ax, pos=0.2, anchor="start", offset=4.0)
The CurvedText class takes the axes after x, y, text, matching
matplotlib.text.Text. The curved_text function takes it first, matching
matplotlib's axes-first helper functions. Passing the axes last to curved_text
raises AttributeError.
Extra keyword arguments are Text properties, such as color, alpha,
fontsize, fontfamily, and path_effects. The font ones apply to every glyph
when the label is made. The color, alpha, and path effects belong to the label
and pass to its glyphs at every draw, so they can change after construction; the
box casing keeps its own color and alpha. Properties that
describe one text box, such as ha, va, bbox, and wrap, have no effect,
and transform is replaced. rotation raises ValueError, because the curve
sets each glyph's angle. A gid of "lab" becomes "lab-0", "lab-1", and
so on, numbered in order along the label, one number for each character and
each math run, so a saved SVG has each id once; select the parts by prefix,
for example [id^=lab-]. The
API reference
lists every property.
Features
Mathtext
A $...$ run (a math run) in the label is laid out by matplotlib's
mathtext
engine and then bent along the curve the way plain text is. Every part of the
expression follows the curve, including the bars of fractions and the overlines
of radicals (square-root signs). Plain and math runs mix freely in one string:
curved_text(ax, x, y, r"$E = \sqrt{(pc)^2 + (mc^2)^2}$",
pos=0.5, anchor="center", offset=14.0,
color="#b06306", fontsize=16)
The whole expression bends with the curve:
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. 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. See Labels on the inside of a tight bend.
Pass parse_math=False to treat dollar signs literally.
Plain words and math runs in one label share a single baseline. The math symbols sit level with the surrounding plain text, and a superscript lifts only the exponent, not the body. The alignment is built in, with no tuning:
curved_text(ax, x, y, r"mass $m$ and speed $c$ give $E = mc^2$",
valign="baseline")
The Gallery section Plain words and math share one baseline shows the symbols level with the words, with only the exponent raised.
LaTeX typesetting (usetex)
LaTeX (a typesetting system built on TeX) can typeset the label, so it matches
the other usetex text in the figure. Set matplotlib's text.usetex rcParam (a
matplotlib runtime setting), or pass usetex=True to curved_text.
curved_text requires latex, as for any matplotlib usetex figure.
matplotlib's own usetex text, such as tick labels, also needs dvipng.
curved_text(ax, x, y, r"yield 50% at $\sqrt{\bar{\sigma}_G}$", usetex=True)
Math runs go to LaTeX as written, so they can run TeX commands, including ones that read local files. Do not pass untrusted text with usetex on.
The page LaTeX typesetting (usetex)
covers plain text, Greek letters, the preamble, caching, and valign.
Background box and halo (box, path_effects)
Set box to add a casing behind the label: a band that follows the curve under
the glyphs, at the label's height. It keeps the label readable where it crosses
other lines. A single fill covers plain text and mathtext alike:
curved_text(ax, x, y, r"signal $s(t) = A\,e^{-t/\tau}$", box=True)
box accepts True, a color string, or a dict with these keys:
| Key | Meaning | Default |
|---|---|---|
color |
Fill color of the band | white |
pad |
Band height, as a multiple of the tallest glyph's height | 1.1 |
alpha |
Opacity of the band | opaque |
In (b) below, the white casing hides the lines under the label. In (a), without
box, the lines pass through the text.
For a lighter effect that outlines each glyph (a halo), pass a white
withStroke through matplotlib's
path_effects.
Path effects reach every glyph and every math run, as they do on any Text.
Each glyph is stroked on its own, so a wide stroke makes neighboring glyphs blur
together. Use box for solid coverage under plain text:
import matplotlib.patheffects as pe
curved_text(ax, x, y, r"signal $s(t) = A\,e^{-t/\tau}$",
path_effects=[pe.withStroke(linewidth=4, foreground="white")])
A wide stroke per character leaves gaps, and one box fill does not. A thin
halo has its own use. Over thin lines and dense figures it hides the lines only
where they touch the glyphs. The Gallery sections
Box versus a path-effects stroke and
A halo or a box show both cases.
Tight bends (crowding)
Glyphs are placed one after another as ordinary text places them, by width and
kerning. On a sharp
bend they crowd together on the inside of the bend, where each rigid glyph
overlaps its neighbor. Set crowding="curvature" to add an even gap between
glyphs that grows with the local curvature, so the inside edges stop colliding:
curved_text(ax, x, y, "winds", pos=0.5, anchor="center", offset=-13.0,
crowding="curvature", color="#b06306", fontsize=20)
The gap is the same between every pair of glyphs, so the spacing stays even.
The correction has a deadband (a range below which no gap is added). A gentle
bend or a straight run stays below it and is unchanged, so only crowded text is
spaced out. The default crowding="none" leaves the spacing as ordinary text
sets it.
The Gallery section Even spacing on a tight bend shows a sharp bend, where the correction visibly separates the glyphs. It also shows a gentle bend of the same word, unchanged because it falls below the deadband.
Labels on the inside of a tight bend (min_radius)
On the inside of a bend tighter than the label is tall, the ink would fold over
itself: a fraction bar or a radical's overline would run backward, and ink past
the center of curvature would come out mirrored. An offset toward the inside
of a bend larger than the bend's radius has the same cause. It lays the label
along a path that doubles back, so letters overlap or change order. By default
the label rides a rounded copy of the curve instead. A ball of a 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 it:
curved_text(ax, x, y, r"flux $\sqrt{\frac{a^2+b^2}{c^2}}$ out",
min_radius="auto")
"auto" is the default. It takes 1.5 times the height of the label's ink on
each side of the path. Pass a number to set the least radius in points for both
sides, or None to turn the rounding off. A bend gentler than the ball is left
exactly as it is, so a label on a gentle curve is unchanged.
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
fold there, as with min_radius=None or, near a narrow hairpin, more. One is a
hairpin whose arms are less than about 20 degrees apart, more for a larger
label: the ball fits only far along the curve, farther than six of its radii,
so the bend is blended instead of rounded, wherever the label sits on the arm.
The other is 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 for smooth.
The Gallery section Labels on the inside of a tight bend shows a math label and an offset label on a tight valley, with and without the rounding.
Labels on measured data (smooth)
A line of measured data wiggles at about the width of a letter, even after the
data is averaged. Each letter is placed at its own point on the curve, so
neighboring letters tilt by different amounts and step up and down. smooth
smooths the path the label rides and leaves the line alone:
curved_text(ax, dates, prices, "Microsoft", offset=14, smooth="auto")
smooth is None by default. A number is the width in points of arc length: a
Gaussian of that standard deviation, corrected so that a smooth bend keeps its
shape, and it smooths wherever the label is, so it rounds any bend narrower
than the width. It is the choice for raw, unaveraged data. "auto" takes three
quarters of an em 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 left as it is. The test is a
heuristic that switches on and off as the label or the view moves, so give a
number for a steadier result. The smoothing comes before the rounding of
min_radius.
The label rides the smoothed path, not the line. Where the line wiggles by more
than the label's offset, it can touch the letters, so give the label an offset
larger than the wiggles.
The Gallery section Labels on measured data
shows a label on a line of real monthly prices, with and without smooth.
Vertical alignment (valign)
By default the text straddles the curve (valign="center"). valign selects
which line of the text lies on the curve. "baseline" puts the baseline on the
curve, so the body sits above it. "ascender" and "descender" put the top or
bottom line of the text on the curve, which places the label below or above the
curve:
curved_text(ax, x, y, "Amplitude", valign="baseline")
The shift is a single font metric applied to the whole label, so it never
disturbs the spacing or the alignment of plain text with mathtext. Combine it
with offset to lift the chosen line clear of the curve.
With valign, the same word moves from straddling the arc to hanging below it
or sitting above it. The Gallery section valign: which line of the text lies on the curve
shows the word on an arc for each value.
Works with seaborn, pandas, and other matplotlib-backed libraries
curved_text needs only a matplotlib.axes.Axes, so it works with any library
that draws on matplotlib. seaborn's axes-level functions return an Axes, and
its figure-level functions expose one through .axes. The pandas
DataFrame.plot method returns an Axes as well. Pass that axes in directly.
Here df is a long-form data frame with the columns date, level, and
series:
import seaborn as sns
palette = {"NASDAQ Composite": "#003f7f", "S&P 500": "#b06306"}
ax = sns.lineplot(data=df, x="date", y="level", hue="series",
palette=palette, legend=False)
for name, line in df.groupby("series"):
curved_text(ax, line["date"], line["level"], name, color=palette[name],
pos=0.6, anchor="center", offset=8.0)
The Gallery section Any matplotlib-backed axes (seaborn, pandas)
labels two stock market indexes with similar calls, in seaborn's whitegrid
theme, with each label in place of a legend entry. It also passes
curved_text a smoothed copy of each line, which keeps the glyphs of a label
on monthly data from tilting into each other.
Limits
curved_text and CurvedText take the same arguments and make the same
artist. Keep the returned object to change the label after it is made. These
setters act on what is drawn: 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
(set_clip_on, set_clip_box, set_clip_path). The text, the font, the
curve, and the placement arguments (pos, anchor, offset, valign,
box, crowding, upright, min_radius, and smooth) are fixed when the
label is made. To change one, remove the label (remove()) and make a new
one.
get_text() does not return the label's string.
- Vector output: In Portable Document Format (PDF), Scalable Vector Graphics (SVG), PostScript, and Encapsulated PostScript (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 glyph 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
upright=True. 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:
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, so an artist between the label's zorder and the next one covers the whole label. - 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. - Axis limits: The label does not change the data limits. Plot the curve first, or set the limits yourself.
- Text: One line. A newline in the string is not a line break.
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.- 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.
How it works
Each character (and each $...$ run) is a part of the label, drawn from its
glyph outline and placed so that one shared text baseline follows the curve. A plain
glyph is turned rigidly: the package draws a straight line across the width of
that one glyph and turns the glyph to match. Averaging over the width keeps
neighboring glyphs smooth even when the curve has only a few points.
Sharing one baseline keeps plain text and mathtext level. The
design notes describe how mathtext is bent along the
curve.
All of this is measured in display space: pixels on the final figure after every scaling step. Spacing and perpendicular offset therefore stay correct at any dots per inch (dpi) and figure size. The layout is redone on every draw, so the label follows resizing and interactive panning and zooming.
Related
matplotlib-label-lines labels
one or many lines inline at a chosen or automatically picked point, each label
rotated to the local slope. curved-text addresses a different problem: it
makes a single string (plain or mathtext) follow a curve character by character,
with arc-length placement and a perpendicular offset, redone on every draw. Use
label-lines to replace legend entries on several lines, and curved-text to make
text follow a curve. For R users,
geomtextpath provides similar
functions for text along a curve in ggplot2 (an R plotting package).
For matplotlib users coming from LaTeX: curved-text is matplotlib's counterpart
of the text along path decoration of TikZ (a LaTeX drawing package), from
decorations.text. The mapping is close. pos and anchor play the role of
text align and the indents, and offset plays the role of raise. Text that
overruns the path follows the straight tangent extension. It is not cut off at
the end of the path.
Documentation
Full documentation, including the API reference and the design notes, is at thiebes.github.io/curved-text. More worked examples are in the example gallery.
Contributing
Bug reports, feature requests, and pull requests are welcome. See CONTRIBUTING.md for the development install, how to run the tests, linting, and the rest of the workflow. By participating you agree to the Code of Conduct.
Development and AI use
Generative AI tools were used to develop and maintain this package. The author (the sole maintainer) directed the design and reviewed, tested, and approved every change before committing it.
- Design and direction. The architecture and the design decisions were the
maintainer's: the chord-across-width placement, the
_CurveFramedisplay-space geometry, tangent-extension overflow, and the choice to support mathtext by bending glyph outlines along the curve. The mathtext feature was iterated against real problems found in use, including the baseline-alignment fix and the move from a per-character stroke to a single box casing once the per-letter halo was found to leave gaps. AI assisted in drafting the design documents and the implementation against these decisions. - Code. The implementation in
src/curved_text/was drafted with substantial AI assistance against that design, then reviewed and revised by the maintainer. Correctness, cross-version compatibility (the test suite runs against a matplotlib floor and a pre-release), packaging, and the release process were the maintainer's responsibility. - Tests. The test suite in
tests/was drafted with AI assistance and reviewed by the maintainer, and is run in CI on every change. - Documentation. The README, API reference, and example gallery prose were drafted with AI assistance and edited by the maintainer.
- How AI was used. Primarily conversational and agentic drafting with Anthropic's Claude. The maintainer provided the problem framing, the design decisions, and the final review.
No AI-generated content was committed without human review.
License
MIT
Metadata
Release files for curved-text 0.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| curved_text-0.9.0.tar.gz | 117.3 kB | With provenance | Details for curved_text-0.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| curved_text-0.9.0-py3-none-any.whl | Python 3 | none | any | Details for curved_text-0.9.0-py3-none-any.whl |
Total release size: 172.4 kB
Release files / curved_text-0.9.0.tar.gz
| Download URL | curved_text-0.9.0.tar.gz |
|---|---|
| Size | 117.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7c5ab44193c15f8bbde29bc2155e29567807bb80890e1f88fb89d37093ead2aa
|
|
BLAKE2b-256 checksum How to use checksums |
01a61b32477c9f346b2c9890225a20a23e1b810ee3b26874cb0b12f593129923
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.
Transparency logRelease files / curved_text-0.9.0-py3-none-any.whl
| Download URL | curved_text-0.9.0-py3-none-any.whl |
|---|---|
| Size | 55.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e019b4102c4208be834395c01a613aae40949143f20bb739022834281859bc15
|
|
BLAKE2b-256 checksum How to use checksums |
3f5b2541df4e2c719c7f9e6342f0715340310d806f3304ad1d3f299d1b8b2312
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.
Transparency logSecurity for curved-text 0.9.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for curved_text-0.9.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.