Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib text() / annotate() Function

Matplotlib text() / annotate() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

text() Add text at specified coordinates in the chart,annotate() add annotations with arrows that can precisely point to data points.

Function definition

text()

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Axes.text(x, y, s, fontdict=None, **kwargs)

annotate()

matplotlib.pyplot.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
Axes.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)

Parameter Description

text() parameters

Parameters Description
x, y Text position coordinates
s The text string to display
fontsize Font size
color Text Colors
ha / horizontalalignment Horizontal alignment: 'center', 'right', 'left'
va / verticalalignment Vertical alignment: 'center', 'top', 'bottom', 'baseline'
rotation Rotation angle (in degrees)
fontweight Font weight: 'normal', 'bold', 'light'
bbox Text background box properties, e.g. dict(facecolor='yellow', alpha=0.5)

Parameters specific to annotate()

Parameters Description
text Annotation text content
xy Coordinates of the target point being pointed to (x, y) (the arrow tip)
xytext Coordinates where the text is placed. Default None (text placed at the xy position)
xycoords / textcoords Coordinate system for xy / xytext: 'data', 'axes fraction', 'figure fraction', 'offset points', etc.
arrowprops Arrow properties dictionary, e.g. dict(arrowstyle='->', color='gray', lw=1.5)

The core value of annotate is that xy and xytext can specify the coordinate point and text position separately, with an arrow connecting the two, something text() cannot do.

Common arrow styles for arrowprops

Style effect
'->' Solid triangle arrow
'-' No line
'<->' Double-headed arrow
'-[widthB=...,lengthB=...]' Custom rectangle arrow
'fancy' Elegant curved arrow
'simple' Simple straight arrow

Usage examples

Example 1: Basic text addition (text)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

10

,

100

)

y

=

np.

sin

(

x

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

4

)

,

layout

=

'constrained'

)

ax.

plot

(

x

,

y

,

'steelblue'

,

linewidth

=

2

)

Add a text marker at the peak

peak_idx

=

np.

argmax

(

y

)

ax.

text

(

x

[

peak_idx

]

,

y

[

peak_idx

]

0.1

,

        f

'Peak: ({x[peak_idx]:.2f}, {y[peak_idx]:.2f})'

,

        fontsize

=

10

,

color

=

'red'

,

        ha

=

'center'

,

va

=

'bottom'

,

        fontweight

=

'bold'

)

Add text + background box at the valley

valley_idx

=

np.

argmin

(

y

)

ax.

text

(

x

[

valley_idx

]

,

y

[

valley_idx

]

0.15

,

        f

'Valley: ({x[valley_idx]:.2f}, {y[valley_idx]:.2f})'

,

        fontsize

=

10

,

ha

=

'center'

,

va

=

'top'

,

        bbox

=

dict

(

boxstyle

=

'round,pad=0.3'

,

                  facecolor

=

'yellow'

,

alpha

=

0.7

)

)

ax.

set_title

(

'text() - Adding Text at Specific Coordinates'

)

ax.

set_xlabel

(

'x'

)

ax.

set_ylabel

(

'sin(x)'

)

ax.

grid

(

True

,

alpha

=

0.3

)

plt.

show

(

)

Example 2: Arrow annotation (annotate)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

10

,

50

)

y

=

np.

exp

(

-x/

3

)

sin

(

2

)

 

Damped oscillation

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

5

)

,

layout

=

'constrained'

)

ax.

plot

(

x

,

y

,

'steelblue'

,

linewidth

=

2

,

marker

=

'o'

,

markersize

=

4

)

Annotate the first peak (arrow points from the text to the data point)

peak1_idx

=

np.

argmax

(

y

)

ax.

annotate

(

'1st Peak'

,

            xy

=

(

x

[

peak1_idx

]

,

y

[

peak1_idx

]

)

,

         

The point the arrow points to

            xytext

=

(

x

[

peak1_idx

]

1.5

,

y

[

peak1_idx

]

0.2

)

,

 

Text position

            arrowprops

=

dict

(

arrowstyle

=

'->'

,

                            color

=

'red'

,

lw

=

1.5

)

,

            fontsize

=

11

,

color

=

'red'

,

fontweight

=

'bold'

)

Annotate the decay region

ax.

annotate

(

'Decay region'

,

            xy

=

(

.7

,

.3

)

,

xycoords

=

'axes fraction'

,

   

Use axes coordinates

            xytext

=

(

0.5

,

0.8

)

,

textcoords

=

'axes fraction'

,

            arrowprops

=

dict

(

arrowstyle

=

'fancy'

,

                            color

=

'green'

,

                            connectionstyle

=

'arc3,rad=0.3'

)

,

            fontsize

=

11

,

color

=

'green'

,

            bbox

=

dict

(

boxstyle

=

'round'

,

facecolor

=

'wheat'

,

alpha

=

0.5

)

)

ax.

set_title

(

'annotate() - Annotations with Arrows'

)

ax.

set_xlabel

(

'Time (s)'

)

ax.

set_ylabel

(

'Amplitude'

)

ax.

grid

(

True

,

alpha

=

0.3

)

plt.

show

(

)

Example 3: Formula annotation and coordinate systems

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

4

*np.

pi

,

200

)

y1

=

np.

sin

(

x

)

y2

=

np.

cos

(

x

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

5

)

,

layout

=

'constrained'

)

ax.

plot

(

x

,

y1

,

'blue'

,

label

=

'sin(x)'

)

ax.

plot

(

x

,

y2

,

'red'

,

label

=

'cos(x)'

)

Annotate with a mathematical formula at a fixed position in the chart

ax.

text

(

0.02

,

0.95

,

        r

'$f(x) = sin(x)$'

,

        transform

=

ax.

transAxes

,

   

Use Axes relative coordinates (0-1)

        fontsize

=

14

,

color

=

'blue'

,

        verticalalignment

=

'top'

,

        bbox

=

dict

(

boxstyle

=

'round'

,

facecolor

=

'lightblue'

,

alpha

=

0.5

)

)

ax.

text

(

0.02

,

0.82

,

        r

'$g(x) = cos(x)$'

,

        transform

=

ax.

transAxes

,

        fontsize

=

14

,

color

=

'red'

,

        verticalalignment

=

'top'

,

        bbox

=

dict

(

boxstyle

=

'round'

,

facecolor

=

'lightcoral'

,

alpha

=

0.5

)

)

ax.

set_title

(

r

'Math Formula with LaTeX: $sum_{i=1}^{n} x_i$'

)

ax.

set_xlabel

(

'x (radians)'

)

ax.

legend

(

)

ax.

grid

(

True

,

alpha

=

0.3

)

plt.

show

(

)

print

(

"runoob: math annotation displayed"

)


Common questions

What is the difference between text and annotate?

text() Only places text at specified coordinates, suitable for adding labels or descriptions.

annotate() Can add an arrow connecting text and a data point, suitable for precisely annotating key positions.

How to use mathematical formulas in text?

Use LaTeX syntax:r'$alpha + beta$'. The r prefix denotes a raw string, and content within $...$ is rendered as a mathematical formula.

Requires LaTeX installed on the system or the use of Matplotlib's built-in mathtext renderer.

Matplotlib Reference Documentation Matplotlib Reference Documentation