Adding Text to a Plot
In this lesson, we will learn how to add text to a plot, and how to change the style of the text.
What is text
?
Text is basically a simpler version of annotate
. Unlike annotate
, we don’t need to anchor our text to one specific data location. The text feature is useful when we want to add some text to a diagram without linking it to any specified data. For example, if we want to present some textual information or provide an explanation.
Although the purpose of tex
t is simple, it is a rich feature. Just like with annotate
, we can control the appearance of the text by setting a number of options, most of which are related to presentation style. Some of the most common options will be introduced in this lesson.
How to add text to a plot
text()
is the main function we can use to add text to a plot.
We start by adding the string “function” with fontsize=12
to the location (10, 20). By default, the location is given in data coordinates. The coordinate system can be changed using the transform
parameter.
text(10, 20, "function", fontsize=12)
The default transform specifies that the text location is given in data coords. Alternatively, we can specify the text location in axis coords (0,0 is lower-left and 1,1 is upper-right
). The example below places the text in the center of the axes.
text(0.5, 0.5, 'function', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes)
If we want to put a frame around the text, we can use the option bbox
. The example code below adds a box with a red background to our text.
text(10, 20, "function", bbox=dict(facecolor='red', alpha=0.5))
import numpy as npimport matplotlib.pyplot as pltpoints = np.linspace(-5, 5, 256)y1 = np.tanh(points) + 0.5y2 = np.sin(points) - 0.2fig, axe = plt.subplots(figsize=(7, 3.5), dpi=300)axe.plot(points, y1)axe.plot(points, y2)axe.legend(["tanh", "sin"])axe.text(-2.5, 0.5, "two functions", bbox=dict(facecolor='red', alpha=0.5))fig.savefig("output/output.png")plt.close(fig)
Adding multi-line text to a plot
Sometimes, we will need to place a lot of text onto our chart. If our text spans more than one line, all we need to do is add a new line symbol, \n
, like in the example below.
text(10, 20, "function\nfunction2\nfunction3", fontsize=12)
Changing the style of the text
In order to set the style of the text, we pass a dictionary to the option fontdict, like in the example code below. The text style has many properties, so more details on how to customize text can be found on the official Matplotlib page, Text style and properties.
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
text(10, 20, "function", fontdict=font)
Support mathematical formula
Many papers and articles in scientific journals require including mathematical formulas on figures in order to help readers better understand them. Fortunately, mathematical formulas are well supported by Matplotlib.
Notice: In this demo, we use
$
to wrap our scientific formulas atline 12
, which is a feature that can support some mathematical notations. We don’t need to install additional software to display mathematical formulas. However, if we want to use LaTeX, we will need to install the LaTeX package. Please refer to the official LaTeX site for more information.
import numpy as npimport matplotlib.pyplot as pltpoints = np.linspace(-5, 5, 256)y1 = np.tanh(points) + 0.5y2 = np.sin(points) - 0.2fig, axe = plt.subplots(figsize=(7, 3.5), dpi=800)axe.plot(points, y1)axe.plot(points, y2)axe.legend(["tanh", "sin"])eq = r"$\int_a^b{\sin(x)} dx$"axe.text(-3, 0.18, eq, {'color': 'C0', 'fontsize': 13})fig.savefig("output/output.png")plt.close(fig)
In the next lesson, we will learn about grid
, which can help us locate data points. Grid can also help us place the text
, legend
, or annotations
in the right place