There are many ways to add text (plot text) in Matplot, and it is useful for adding descriptions, labels, annotations, and more to your plots. Below I’ll list the main ways to work with text in Matplotlib, along with one example each.
1. Add basic text: plt.text()
plt.text() is a function that adds text to a specific location on the plot.
plt.text(x, y, text, fontsize=12, color='black', ha='center', va='center')
- x, y: Coordinates where the text will be located.
- text: The text to add.
- fontsize: Text size.
- color: Text color.
- ha: Horizontal alignment (‘center’, ‘left’, ‘right’).
- va: Vertical alignment (‘center’, ‘top’, ‘bottom’).
2. Adding annotations: plt.annotate()
plt.annotate() is used to add text and arrows together to describe a specific data point.
plt.annotate(text, xy, xytext, arrowprops=dict(arrowstyle='->'))
- text: Annotation text.
- xy: Coordinates where the arrow will point.
- xytext: Coordinates where the text will be located.
- arrowprops: Arrow style settings.
3. add title and label
- Title: plt.title()
- X-axis label: plt.xlabel()
- Y-axis label: plt.ylabel()
4. Setting text properties
Can set many different styles for text. The main properties are
- fontsize: Text size.
- color: Text color.
- fontweight: Font weight (‘bold’, ‘normal’).
- fontstyle: Font style (‘italic’, ‘normal’).
- bbox: Add a box around the text.
5. Add a math expression (LaTeX)
Matplotlib supports LaTeX syntax, which allows you to add math expressions.
Simply write the LaTeX syntax inside $…$.
plt.text(2, 5, r'$\alpha = \beta^2 + \gamma$', fontsize=14, color='green')
6. Rotating text
Can use the rotation parameter to rotate text.
plt.text(2, 5, 'Rotated Text', fontsize=12, color='purple', rotation=45)
7. Adjust text positioning
ha
: horizontal alignment ('left'
,'center'
,'right'
).va
: vertical alignment ('top'
,'center'
,'bottom'
).
8. Adding multiple lines of text
Can use \n to add multiple lines of text.
9. Adding a background to text
Can use the bbox parameter to add a background around your text.
plt.text(2, 5, 'Text with Background', fontsize=12, color='white',
bbox=dict(facecolor='black', alpha=0.7))
10. Specify text locations in Figure coordinates instead of data coordinates
Use the transform parameter to specify the text position in Figure coordinates (in the range 0 to 1).
plt.text(0.5, 0.5, 'Figure Text', fontsize=12, color='navy',
transform=plt.gcf().transFigure)
- plt.text(): Add text at specific coordinates.
- plt.annotate(): Add text and an arrow together.
- plt.title(), plt.xlabel(), plt.ylabel(): Add title and axis labels.
- LaTeX syntax: Add math expressions.
- BBOX, ROTATION, HA, VA: Adjust text style and position.
Plot text Code
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o')
for i, txt in enumerate(['A', 'B', 'C', 'D', 'E']):
plt.text(x[i], y[i], txt, fontsize=12, rotation=-5)
plt.title('Multiple Text Example')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
