Matplotlib text

How to add text to Matplotlib?

Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module.

 It provides almost any kind of plot that we can think of. In this post, we will focus on a more specific topic which is adding text on matplotlib plot. The following commands are used to create text in the matplotlib plot.

text This is used for adding text at an arbitrary location of the Axes.
annotateThis is used for adding an annotation, with an optional arrow, at an arbitrary location of the Axes.
set_xlabelThis is used for adding label to the Axes’ x-axis.
set_ylabelThis is used for adding label to the Axes’ y-axis.
set_titleThis is used for adding title to the Axes.
textThis is used for adding text at an arbitrary location of the Figure.
 suptitleThis is used for adding title to the Figure.

We will see each of the commands one by one, first, let’s create a basic plot of Day v/s Question on which we will add various text objects. 










The output plot looks very simple. Now, let’s see some text commands to add it on our plot.

  • set_title() is used to add the title of axes. The first and mandatory argument is the title you want to give and the rest are optional to formate it.
  • Similarly, set_xlabel() and set_ylabel() are used to add titles to x-axis and y-axis. It also takes title as an argument.

It is better to adjust the range on y-axis so that we can have some space to add text later on. For this, we will use ax.axis() which allows specifying value ranges (the first two for x-axis and the other two for y-axis).

Now, let’s add its title and names of x-axis and y-axis.






Now, it looks better than the previous version. It’s the time to add text to our plot. First, let’s see about them.

axes.text() is used to add text at an arbitrary location of the Axes. For this we need to specify the location of the text and of course what the text is. For instance, the following code will add “Practice on GFG” text. It will located according to the point whose coordinates are specified ([1,13] in this case). The parameter bbox is used to capture the text with a box. As argument to bbox parameter, we pass a dictionary which includes formatting styles.



If we want to do not have to box the text then simply do not assign anything to the bbox parameter. The following code adds the specified text without a box.



We can also add text with annotations.

axes.annotate() isused to add an annotation, with an optional arrow, at an arbitrary location of the Axes. Its xy parameter contains the coordinates for arrow and xytext parameter specifies the location of the text. Arrowprops parameter is used to style the arrow.

For instance, we can mark the peak value of the Day-Question data with an annotation.



Let’s put all this together and see the final code.
















 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


Text in Matplotlib Plots¶

Introduction to plotting and working with 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 (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 pyplot interface and the object-oriented API:

All of these functions create and return a 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.

importmatplotlibimportmatplotlib.pyplotaspltfig=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))
bold figure suptitle, axes title

Labels for x- and y-axis¶

Specifying the labels for the x- and y-axis is straightforward, via the and methods.

text intro

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.

text intro

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 fontsizes).

text intro

Or, the labels accept all the 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 kwarg.

text intro

All the labelling in this tutorial can be changed by manipulating the method, or by named kwargs to

text intro

Finally, we can use native TeX rendering in all text objects and have multiple lines:

text intro


Subplot titles are set in much the same way as labels, but there is the loc keyword arguments that can change the position and justification from the default value of .

fig,axs=plt.subplots(3,1,figsize=(5,6),tight_layout=True)locs=['center','left','right']forax,locinzip(axs,locs):ax.plot(x1,y1)ax.set_title('Title with loc at '+loc,loc=loc)
Title with loc at center, Title with loc at left, Title with loc at right

Vertical spacing for titles is controlled via (default: ), which defaults to 5 points. Setting to a different value moves the title.

Vertically offset title

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 also offers a very flexible framework for determining the choices for tick locations, and how they are labelled.

Simple ticks¶

It often is convenient to simply define the tick values, and sometimes the tick labels, overriding the default locators and formatters. 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.

text intro

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:

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())
text intro

Tick Locators and Formatters¶

Instead of making a list of all the tickalbels, we could have used (new-style format string) or (old-style '%' format string) and passed it to the . A can also be created by passing a without having to explicitly create the formatter.

text intro

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.

text intro

The default formatter is the called as The steps keyword contains a list of multiples that can be used for tick values. i.e. 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.

uses an algorithm to determine how many ticks will be acceptable based on how long the axis is. The fontsize of the ticklabel is taken into account, but the length of the tick string is not (because its not yet known.) In the bottom row, the ticklabels are quite large, so we set to make the labels fit in the right-hand plot.

text intro

Finally, we can specify functions for the formatter using . Further, like , passing a function will automatically create a .

text intro


Matplotlib can accept and 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 module.

A simple example is as follows. Note how we have to rotate the tick labels so that they don't over-run each other.

text intro

We can pass a format to . Also note that the 29th and the next month are very close together. We can fix this by using the class, which allows us to specify a list of days of the month to use. Similar formatters are listed in the module.

text intro

Legends and Annotations¶

Total running time of the script: ( 0 minutes 5.111 seconds)

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery

  1. Brosnan security salary
  2. Ice fishing fish lake utah
  3. Dungeons rpg games



The text of the annotation.

xy(float, float)

The point (x, y) to annotate. The coordinate system is determined by xycoords.

xytext(float, float), default: xy

The position (x, y) to place the text at. The coordinate system is determined by textcoords.

xycoordsstr or or or callable or (float, float), default: 'data'

The coordinate system that xy is given in. The following types of values are supported:

  • One of the following strings:

    'figure points'Points from the lower left of the figure
    'figure pixels'Pixels from the lower left of the figure
    'figure fraction'Fraction of figure from lower left
    'subfigure points'Points from the lower left of the subfigure
    'subfigure pixels'Pixels from the lower left of the subfigure
    'subfigure fraction'Fraction of subfigure from lower left
    'axes points'Points from lower left corner of axes
    'axes pixels'Pixels from lower left corner of axes
    'axes fraction'Fraction of axes from lower left
    'data'Use the coordinate system of the object being annotated (default)
    'polar'(theta, r) if not native 'data' coordinates

    Note that 'subfigure pixels' and 'figure pixels' are the same for the parent figure, so users who want code that is usable in a subfigure can use 'subfigure pixels'.

  • An : xy is interpreted as a fraction of the artist's . E.g. (0, 0) would be the lower left corner of the bounding box and (0.5, 1) would be the center top of the bounding box.

  • A to transform xy to screen coordinates.

  • A function with one of the following signatures:


    where renderer is a subclass.

    The result of the function is interpreted like the and cases above.

  • A tuple (xcoords, ycoords) specifying separate coordinate systems for x and y. xcoords and ycoords must each be of one of the above described types.

See Advanced Annotations for more details.

textcoordsstr or or or callable or (float, float), default: value of xycoords

The coordinate system that xytext is given in.

All xycoords values are valid as well as the following strings:

'offset points'Offset (in points) from the xy value
'offset pixels'Offset (in pixels) from the xy value
arrowpropsdict, optional

The properties used to draw a arrow between the positions xy and xytext. Note that the edge of the arrow pointing to xytext will be centered on the text itself and may not point directly to the coordinates given in xytext.

If arrowprops does not contain the key 'arrowstyle' the allowed keys are:

widthThe width of the arrow in points
headwidthThe width of the base of the arrow head in points
headlengthThe length of the arrow head in points
shrinkFraction of total length to shrink from both ends
?Any key to

If arrowprops contains the key 'arrowstyle' the above keys are forbidden. The allowed values of are:


Valid keys for are:

arrowstylethe arrow style
connectionstylethe connection style
relposdefault is (0.5, 0.5)
patchAdefault is bounding box of the text
patchBdefault is None
shrinkAdefault is 2 points
shrinkBdefault is 2 points
mutation_scaledefault is text size (in points)
mutation_aspectdefault is 1.
?any key for

Defaults to None, i.e. no arrow is drawn.

annotation_clipbool or None, default: None

Whether to draw the annotation when the annotation point xy is outside the axes area.

  • If True, the annotation will only be drawn when xy is within the axes.
  • If False, the annotation will always be drawn.
  • If None, the annotation will only be drawn when xy is within the axes and xycoords is 'data'.

Additional kwargs are passed to .



Other Parameters:
**kwargs properties.

Other miscellaneous text parameters.

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
scalar or None
dict with properties for
Patch or (Path, Transform) or None
or ccolor
or family{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
or font or font_properties or or
or sizefloat or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
or stretch{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
or style{'normal', 'italic', 'oblique'}
or variant{'normal', 'small-caps'}
or weight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
or ha{'center', 'right', 'left'}
float (multiple of font size)
or ma{'left', 'right', 'center'}
None or bool or float or callable
(float, float)
float or {'vertical', 'horizontal'}
{None, 'default', 'anchor'}
(scale: float, length: float, randomness: float)
bool or None
bool or None
or va{'center', 'top', 'bottom', 'baseline', 'center_baseline'}

Text matplotlib

I thought that women are the greatest craftswomen to create harmony, if they need it and to create disorder, if they are. Not at all interested in it. The things from her bag were thrown to the floor.

Houses and cars flashed outside the window. Night. Darkness.

Now discussing:

Natasha quickly finished her portion, tidied up the table and quietly went into her room. Katya was lying on her bed, stuck in the headphones, and did not. React to the entering sister.

133 134 135 136 137