Book Image

matplotlib Plotting Cookbook

By : Alexandre Devert
Book Image

matplotlib Plotting Cookbook

By: Alexandre Devert

Overview of this book

Table of Contents (15 chapters)
matplotlib Plotting Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding text


So far, we have seen how to set text at preset locations, such as title and axes. In this recipe, we are going to see how to add text at any location using text boxes.

How to do it...

matplotlib has a very flexible function called pyplot.text(), that displays text:

import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-4, 4, 1024)
Y = .25 * (X + 4.) * (X + 1.) * (X - 2.)

plt.text(-0.5, -0.25, 'Brackmard minimum')

plt.plot(X, Y, c = 'k')
plt.show()

This script displays text next to a curve:

How it works...

We use the pyplot.text() function that takes a position and the text to display. The position is given in the graphic coordinates, specifying the position of the left border and the vertical baseline of the text.

There's more...

matplotlib's text rendering is very flexible. Let's explore the important options available.

Alignment control

The text is bound by a box. This box is used to relatively align the text to the coordinates passed to pyplot.text(). Using the verticalalignment...