-
Book Overview & Buying
-
Table Of Contents
Matplotlib for Python Developers
We are going to introduce additional features to allow even more plot decorations.
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 the following screenshot:

The location specified in the text() function is in data coordinates, and it's relative to the data currently plotted. There's a similar function, figtext(), that draws a given string at a position in figure coordinates...