Note
Go to the end to download the full example code.
Text in Matplotlib#
Matplotlib has extensive text support, including support for mathematical expressions, truetype support for raster and vector outputs, newline separated text with arbitrary rotations, and Unicode support.
Because it embeds fonts directly in output documents, e.g., for postscript
or PDF, what you see on the screen is what you get in the hardcopy.
FreeType support
produces very nice, antialiased fonts, that look good even at small
raster sizes. Matplotlib includes its own
matplotlib.font_manager
(thanks to Paul Barrett), which
implements a cross platform, W3C
compliant font finding algorithm.
The user has a great deal of control over text properties (font size, font weight, text location and color, etc.) with sensible defaults set in the rc file. And significantly, for those interested in mathematical or scientific figures, Matplotlib implements a large number of TeX math symbols and commands, supporting mathematical expressions anywhere in your figure.
Basic text commands#
The following commands are used to create text in the implicit and explicit interfaces (see Matplotlib Application Interfaces (APIs) for an explanation of the tradeoffs):
implicit API |
explicit API |
description |
---|---|---|
Add text at an arbitrary location of
the |
||
Add an annotation, with an optional
arrow, at an arbitrary location of the
|
||
Add a label to the
|
||
Add a label to the
|
||
Add a title to the
|
||
Add text at an arbitrary location of
the |
||
Add a title to the |
All of these functions create and return a Text
instance, which can be
configured with a variety of font and other properties. The example below
shows all of these commands in action, and more detail is provided in the
sections that follow.
import matplotlib.pyplot as plt
import matplotlib
fig = plt.figure()
ax = fig.add_subplot()
fig.subplots_adjust(top=0.85)
# Set titles for the figure and the subplot respectively
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
# Set both x- and y-axis limits to [0, 10] instead of default [0, 1]
ax.axis([0, 10, 0, 10])
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
ax.text(3, 2, 'Unicode: Institut für Festkörperphysik')
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()