O'Reilly logo

Matplotlib for Python Developers by Sandro Tosi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Text inside figure, annotations, and arrows

We are going to introduce additional features to allow even more plot decorations.

Text inside figure

We already saw how to use xlabel(), ylabel(), and title() to add text around the figure, but we can do something more, namely, add text inside the figure.

The text() function does that—writes a string (text) at an arbitrary position (specified by (x,y) ):

plt.text(x, y, text)

Let's plot the sine function, and add a note that says sin(0) is equal to 0.

In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np
In [3]: x = np.arange(0, 2*np.pi, .01)
In [4]: y = np.sin(x)
In [5]: plt.plot(x, y);
In [6]: plt.text(0.1, -0.04, 'sin(0)=0');
In [7]: plt.show()

The output of this code snippet is shown in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required