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):
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.
importmatplotlib.pyplotaspltimportmatplotlibfig=plt.figure()ax=fig.add_subplot()fig.subplots_adjust(top=0.85)# Set titles for the figure and the subplot respectivelyfig.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()
Labels for x- and y-axis
Specifying the labels for the x- and y-axis is straightforward, via the
set_xlabel and set_ylabel
methods.
The x- and y-labels are automatically placed so that they clear the x- and
y-ticklabels. Compare the plot below with that above, and note the y-label
is to the left of the one above.
If you want to move the labels, you can specify the labelpad keyword
argument, where the value is points (1/72", the same unit used to specify
font sizes).
Alternatively, the labels accept all the Text keyword arguments, including
position, via which we can manually specify the label positions. Here we
put the xlabel to the far left of the axis. Note, that the y-coordinate of
this position has no effect - to adjust the y-position we need to use the
labelpad keyword argument.
Subplot titles are set in much the same way as labels, but there is
the loc keyword argument that can change the position and justification
(the default value is "center").
Placing ticks and ticklabels is a very tricky aspect of making a figure.
Matplotlib does its best to accomplish the task automatically, but it also
offers a very flexible framework for determining the choices for tick
locations, and how they are labelled.
Terminology
Axes have a matplotlib.axis.Axis object for the ax.xaxis and
ax.yaxis that contain the information about how the labels in the axis
are laid out.
The axis API is explained in detail in the documentation to
axis.
It is often convenient to simply define the
tick values, and sometimes the tick labels, overriding the default
locators and formatters. However, this is discouraged because it breaks
interactive navigation of the plot. It also can reset the axis limits: note
that the second plot has the ticks we asked for, including ones that are
well outside the automatic view limits.
Matplotlib can accept datetime.datetime and numpy.datetime64
objects as plotting arguments. Dates and times require special
formatting, which can often benefit from manual intervention. In
order to help, dates have special locators and formatters,
defined in the matplotlib.dates module.
The following simple example illustrates this concept. Note how we
rotate the tick labels so that they don't overlap.
We can of course fix this after the fact, but it does highlight a
weakness of hard-coding the ticks. This example also changes the format
of the ticks:
And of course we could have used a non-default locator to set the
tick locations. Note we still pass in the tick values, but the
x-limit fix used above is not needed.
The default formatter is the matplotlib.ticker.MaxNLocator called as
ticker.MaxNLocator(self,nbins='auto',steps=[1,2,2.5,5,10]).
The steps argument contains a list of multiples that can be used for
tick values. In this case, 2, 4, 6 would be acceptable ticks,
as would 20, 40, 60 or 0.2, 0.4, 0.6. However, 3, 6, 9 would not be
acceptable because 3 doesn't appear in the list of steps.
Setting nbins=auto uses an algorithm to determine how many ticks will
be acceptable based on the axis length. The fontsize of the
ticklabel is taken into account, but the length of the tick string
is not (because it's not yet known.) In the bottom row, the
ticklabels are quite large, so we set nbins=4 to make the
labels fit in the right-hand plot.
We can pass a format to matplotlib.dates.DateFormatter. If two tick labels
are very close together, we can use the dates.DayLocator class, which
allows us to specify a list of days of the month to use. Similar formatters
are listed in the matplotlib.dates module.