Signup/Sign In

Working with Text in Matplotlib

In this tutorial, we will cover working with the text in Matplotlib.

There is extensive text support in Matplotlib that includes support for mathematical expressions, the Truetype support for raster, and vector outputs, also there is a newline-separated text with arbitrary rotations, and Unicode support.

Working with Text

The Matplotlib library has its own matplotlib.font_manager that is used to implement a cross-platform, W3C compliant font finding algorithm.

  • In this, the user has great control over text properties such as font size, font weight, text location, and color, etc.

  • The Matplotlib library implements a large number of TeX math symbols and commands that provide the support for mathematical expressions anywhere in your figure.

Given below is a list of commands that are used to create text in the Pyplot interface as well as in Object-oriented interface:

pyplot Interface Object-Oriented Interface Description
text text This command is used to add text at an arbitrary location of the Axes.
annotate annotate This command is used to add an annotation, having an optional arrow, at an arbitrary location of theAxes.
xlabel set_xlabel This command is used to add a label to the Axes’s x-axis.
ylabel set_ylabel This command is used to add a label to the Axes’s y-axis.
title set_title This command is used to add a title to the Axes.
figtext text This command is used to add text at an arbitrary location of the Figure.
suptitle suptitle This command is used to add a title to the Figure.

All these functions create and return a Text instance, which can be configured with a variety of font and other related properties.

Time For example!!

Now its time to cover an example in which we will add different text info in different styles to our figure:

import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

ax.text(3, 8, 'This is boxed italics text in data coords', style='italic', 
bbox = {'facecolor': 'orange'})

ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 16)

ax.text(4, 0.05, 'This is colored text in axes coords',
verticalalignment = 'bottom', color = 'maroon', fontsize = 15)

ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'maroon', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()

Following is the output for the above code:

adding custom style text to matplotlib figure



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.