Note
Go to the endto download the full example code.
Text in Matplotlib#
Matplotlib has extensive text support, including support formathematical expressions, truetype support for raster andvector outputs, newline separated text with arbitraryrotations, and Unicode support.
Because it embeds fonts directly in output documents, e.g., for postscriptor PDF, what you see on the screen is what you get in the hardcopy.FreeType supportproduces very nice, antialiased fonts, that look good even at smallraster sizes. Matplotlib includes its ownmatplotlib.font_manager
(thanks to Paul Barrett), whichimplements a cross platform,W3Ccompliant font finding algorithm.
The user has a great deal of control over text properties (font size, fontweight, text location and color, etc.) with sensible defaults set intherc file.And significantly, for those interested in mathematicalor scientific figures, Matplotlib implements a large number of TeXmath symbols and commands, supportingmathematical expressions anywhere in your figure.
Basic text commands#
The following commands are used to create text in the implicit and explicitinterfaces (seeMatplotlib Application Interfaces (APIs) for an explanation of the tradeoffs):
implicit API | explicit API | description |
---|---|---|
Add text at an arbitrary location ofthe | ||
Add an annotation, with an optionalarrow, 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 ofthe | ||
Add a title to the |
All of these functions create and return aText
instance, which can beconfigured with a variety of font and other properties. The example belowshows all of these commands in action, and more detail is provided in thesections 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 theset_xlabel
andset_ylabel
methods.
importmatplotlib.pyplotaspltimportnumpyasnpx1=np.linspace(0.0,5.0,100)y1=np.cos(2*np.pi*x1)*np.exp(-x1)fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.15,left=0.2)ax.plot(x1,y1)ax.set_xlabel('Time (s)')ax.set_ylabel('Damped oscillation (V)')plt.show()

The x- and y-labels are automatically placed so that they clear the x- andy-ticklabels. Compare the plot below with that above, and note the y-labelis to the left of the one above.
fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.15,left=0.2)ax.plot(x1,y1*10000)ax.set_xlabel('Time (s)')ax.set_ylabel('Damped oscillation (V)')plt.show()

If you want to move the labels, you can specify thelabelpad keywordargument, where the value is points (1/72", the same unit used to specifyfont sizes).
fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.15,left=0.2)ax.plot(x1,y1*10000)ax.set_xlabel('Time (s)')ax.set_ylabel('Damped oscillation (V)',labelpad=18)plt.show()

Alternatively, the labels accept all theText
keyword arguments, includingposition, via which we can manually specify the label positions. Here weput the xlabel to the far left of the axis. Note, that the y-coordinate ofthis position has no effect - to adjust the y-position we need to use thelabelpad keyword argument.
fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.15,left=0.2)ax.plot(x1,y1)ax.set_xlabel('Time (s)',position=(0.,1e6),horizontalalignment='left')ax.set_ylabel('Damped oscillation (V)')plt.show()

All the labelling in this tutorial can be changed by manipulating thematplotlib.font_manager.FontProperties
method, or by named keywordarguments toset_xlabel
.
frommatplotlib.font_managerimportFontPropertiesfont=FontProperties(family='Times New Roman',style='italic')fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.15,left=0.2)ax.plot(x1,y1)ax.set_xlabel('Time (s)',fontsize='large',fontweight='bold')ax.set_ylabel('Damped oscillation (V)',fontproperties=font)plt.show()

Finally, we can use native TeX rendering in all text objects and havemultiple lines:
fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(bottom=0.2,left=0.2)ax.plot(x1,np.cumsum(y1**2))ax.set_xlabel('Time (s)\n This was a long experiment')ax.set_ylabel(r'$\int\ Y^2\ dt\ \ (V^2 s)$')plt.show()

Titles#
Subplot titles are set in much the same way as labels, but there istheloc keyword argument that can change the position and justification(the default value is "center").

Vertical spacing for titles is controlled viarcParams["axes.titlepad"]
(default:6.0
).Setting to a different value moves the title.
fig,ax=plt.subplots(figsize=(5,3))fig.subplots_adjust(top=0.8)ax.plot(x1,y1)ax.set_title('Vertically offset title',pad=30)plt.show()

Ticks and ticklabels#
Placing ticks and ticklabels is a very tricky aspect of making a figure.Matplotlib does its best to accomplish the task automatically, but it alsooffers a very flexible framework for determining the choices for ticklocations, and how they are labelled.
Terminology#
Axes have amatplotlib.axis.Axis
object for theax.xaxis
andax.yaxis
that contain the information about how the labels in the axisare laid out.
The axis API is explained in detail in the documentation toaxis
.
An Axis object has major and minor ticks. The Axis hasAxis.set_major_locator
andAxis.set_minor_locator
methods that use thedata being plotted to determine the location of major and minor ticks. Thereare alsoAxis.set_major_formatter
andAxis.set_minor_formatter
methodsthat format the tick labels.
Simple ticks#
It is often convenient to simply define thetick values, and sometimes the tick labels, overriding the defaultlocators and formatters. However, this is discouraged because it breaksinteractive navigation of the plot. It also can reset the axis limits: notethat the second plot has the ticks we asked for, including ones that arewell outside the automatic view limits.

We can of course fix this after the fact, but it does highlight aweakness of hard-coding the ticks. This example also changes the formatof the ticks:
fig,axs=plt.subplots(2,1,figsize=(5,3),tight_layout=True)axs[0].plot(x1,y1)axs[1].plot(x1,y1)ticks=np.arange(0.,8.1,2.)# list comprehension to get all tick labels...tickla=[f'{tick:1.2f}'fortickinticks]axs[1].xaxis.set_ticks(ticks)axs[1].xaxis.set_ticklabels(tickla)axs[1].set_xlim(axs[0].get_xlim())plt.show()

Tick locators and formatters#
Instead of making a list of all the ticklabels, we could haveusedmatplotlib.ticker.StrMethodFormatter
(new-stylestr.format()
format string) ormatplotlib.ticker.FormatStrFormatter
(old-style '%'format string) and passed it to theax.xaxis
. Amatplotlib.ticker.StrMethodFormatter
can also be created by passing astr
without having to explicitly create the formatter.

And of course we could have used a non-default locator to set thetick locations. Note we still pass in the tick values, but thex-limit fix used above isnot needed.

The default formatter is thematplotlib.ticker.MaxNLocator
called asticker.MaxNLocator(self,nbins='auto',steps=[1,2,2.5,5,10])
.Thesteps
argument contains a list of multiples that can be used fortick 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 beacceptable because 3 doesn't appear in the list of steps.
Settingnbins=auto
uses an algorithm to determine how many ticks willbe acceptable based on the axis length. The fontsize of theticklabel is taken into account, but the length of the tick stringis not (because it's not yet known.) In the bottom row, theticklabels are quite large, so we setnbins=4
to make thelabels fit in the right-hand plot.
fig,axs=plt.subplots(2,2,figsize=(8,5),tight_layout=True)forn,axinenumerate(axs.flat):ax.plot(x1*10.,y1)formatter=matplotlib.ticker.FormatStrFormatter('%1.1f')locator=matplotlib.ticker.MaxNLocator(nbins='auto',steps=[1,4,10])axs[0,1].xaxis.set_major_locator(locator)axs[0,1].xaxis.set_major_formatter(formatter)formatter=matplotlib.ticker.FormatStrFormatter('%1.5f')locator=matplotlib.ticker.AutoLocator()axs[1,0].xaxis.set_major_formatter(formatter)axs[1,0].xaxis.set_major_locator(locator)formatter=matplotlib.ticker.FormatStrFormatter('%1.5f')locator=matplotlib.ticker.MaxNLocator(nbins=4)axs[1,1].xaxis.set_major_formatter(formatter)axs[1,1].xaxis.set_major_locator(locator)plt.show()

Finally, we can specify functions for the formatter usingmatplotlib.ticker.FuncFormatter
. Further, likematplotlib.ticker.StrMethodFormatter
, passing a function willautomatically create amatplotlib.ticker.FuncFormatter
.
defformatoddticks(x,pos):"""Format odd tick positions."""ifx%2:returnf'{x:1.2f}'else:return''fig,ax=plt.subplots(figsize=(5,3),tight_layout=True)ax.plot(x1,y1)locator=matplotlib.ticker.MaxNLocator(nbins=6)ax.xaxis.set_major_formatter(formatoddticks)ax.xaxis.set_major_locator(locator)plt.show()

Dateticks#
Matplotlib can acceptdatetime.datetime
andnumpy.datetime64
objects as plotting arguments. Dates and times require specialformatting, which can often benefit from manual intervention. Inorder to help, dates have special locators and formatters,defined in thematplotlib.dates
module.
The following simple example illustrates this concept. Note how werotate the tick labels so that they don't overlap.
importdatetimefig,ax=plt.subplots(figsize=(5,3),tight_layout=True)base=datetime.datetime(2017,1,1,0,0,1)time=[base+datetime.timedelta(days=x)forxinrange(len(x1))]ax.plot(time,y1)ax.tick_params(axis='x',rotation=70)plt.show()

We can pass a format tomatplotlib.dates.DateFormatter
. If two tick labelsare very close together, we can use thedates.DayLocator
class, whichallows us to specify a list of days of the month to use. Similar formattersare listed in thematplotlib.dates
module.
importmatplotlib.datesasmdateslocator=mdates.DayLocator(bymonthday=[1,15])formatter=mdates.DateFormatter('%b%d')fig,ax=plt.subplots(figsize=(5,3),tight_layout=True)ax.xaxis.set_major_locator(locator)ax.xaxis.set_major_formatter(formatter)ax.plot(time,y1)ax.tick_params(axis='x',rotation=70)plt.show()

Legends and annotations#
Total running time of the script: (0 minutes 6.559 seconds)