Basic Text in Matplotlib
Learn how to add text inside Matplotlib figures and charts. Understand text positioning, font properties, alignment, rotation, and how to make your visualisations more informative.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand why text is used in Matplotlib visualisations.
- Use
plt.text()to add text to a plot. - Use
ax.text()with the object-oriented interface. - Control text position using X and Y coordinates.
- Customize font size, colour, family, and weight.
- Apply horizontal and vertical alignment.
- Rotate text and add background boxes.
- Place text inside charts to highlight important information.
2. Introduction to Text in Matplotlib
Text is an important part of data visualisation. A chart may contain correct data, but without proper information, users may not understand what the chart represents.
Matplotlib provides text functions that allow us to display messages, labels, descriptions, and additional information at specific positions inside a figure or axes.
Why do we use text?
- To explain important values in a chart.
- To highlight maximum and minimum values.
- To display additional information.
- To make charts easier to understand.
- To identify important points in a visualisation.
Text labels help users understand important values in a chart.
3. Using plt.text()
The plt.text() function is used to add text at a specific
X and Y coordinate in the current axes.
Its basic syntax is:
plt.text(x, y, text)
Here:
xrepresents the horizontal position.yrepresents the vertical position.textrepresents the message to display.
Example: Adding basic text
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 15, 30])
plt.text(2, 20, "Important Point")
plt.title("Basic Text Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Output
Line chart displayed with the text
"Important Point" at coordinate (2, 20).
Title: Basic Text Example
X-axis: X Values
Y-axis: Y Values
4. Using ax.text()
Matplotlib also provides ax.text(), which belongs to the
object-oriented interface. It adds text to a particular Axes object.
This approach is useful when working with multiple charts or subplots because we can control exactly which axes receives the text.
Example: Using ax.text()
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.text(2, 20, "Sales Increased")
ax.set_title("Sales Performance")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
plt.show()
Output
A line chart is displayed with the title
"Sales Performance".
The text "Sales Increased" appears
at the coordinate (2, 20).
plt.text() vs ax.text()
| plt.text() | ax.text() |
|---|---|
| Uses the current axes. | Uses a specific Axes object. |
| Works with the pyplot interface. | Works with the object-oriented interface. |
| Useful for simple plots. | Useful for multiple axes and complex figures. |
Syntax: plt.text() |
Syntax: ax.text() |
5. Understanding Text Position
Text position is controlled using X and Y coordinates. These coordinates determine where the text appears inside the axes.
For example, plt.text(2, 10, "Hello") displays the text
at X coordinate 2 and Y coordinate 10.
The X and Y coordinates determine the text anchor position.
Example: Multiple text positions
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 30, 40])
plt.text(1, 10, "Point One")
plt.text(2, 20, "Point Two")
plt.text(3, 30, "Point Three")
plt.text(4, 40, "Point Four")
plt.title("Multiple Text Positions")
plt.show()
Output
A line chart is displayed with four text labels:
Point One at (1, 10)
Point Two at (2, 20)
Point Three at (3, 30)
Point Four at (4, 40)
6. Customizing Text Font Properties
Matplotlib allows us to customize the appearance of text using different font properties. We can change font size, colour, family, and weight.
6.1 Font Size
Use fontsize to control the size of the text.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.text(1, 15, "Small Text", fontsize=10)
plt.text(1, 20, "Medium Text", fontsize=16)
plt.text(1, 25, "Large Text", fontsize=22)
plt.title("Font Size Example")
plt.show()
Output
The chart displays three text labels
with different font sizes:
Small Text - 10
Medium Text - 16
Large Text - 22
6.2 Font Colour
Use color to change the text colour. Matplotlib supports
common colour names, hexadecimal values, and other colour formats.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.text(1, 15, "Red Text", color="red")
plt.text(1, 20, "Blue Text", color="blue")
plt.text(1, 25, "Green Text", color="green")
plt.title("Text Colour Example")
plt.show()
Output
The chart displays three text labels:
Red Text - Red colour
Blue Text - Blue colour
Green Text - Green colour
6.3 Font Weight
The fontweight property controls the thickness of the text.
Common values include normal, bold,
and light.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.text(1, 15, "Normal Text", fontweight="normal")
plt.text(1, 20, "Bold Text", fontweight="bold")
plt.text(1, 25, "Light Text", fontweight="light")
plt.title("Font Weight Example")
plt.show()
Output
The chart displays text with different font weights:
Normal Text - Normal thickness
Bold Text - Bold thickness
Light Text - Light thickness
6.4 Font Family
Use fontfamily to specify the font family for text.
The available fonts depend on the fonts installed on your system.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.text(1, 15, "Serif Font",
fontfamily="serif")
plt.text(1, 20, "Sans Serif Font",
fontfamily="sans-serif")
plt.text(1, 25, "Monospace Font",
fontfamily="monospace")
plt.title("Font Family Example")
plt.show()
Output
The chart displays three text labels
using different font families:
Serif Font
Sans Serif Font
Monospace Font
plt.text() or ax.text() call.
7. Text Alignment
Text alignment controls how text is positioned around its anchor coordinate. Matplotlib provides horizontal and vertical alignment.
7.1 Horizontal Alignment
Use horizontalalignment or its shorter form
ha to align text horizontally.
| Value | Description |
|---|---|
left |
Text starts from the anchor position. |
center |
Text is centered around the anchor position. |
right |
Text ends at the anchor position. |
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.text(2, 15, "Left Aligned",
ha="left")
plt.text(2, 20, "Center Aligned",
ha="center")
plt.text(2, 25, "Right Aligned",
ha="right")
plt.title("Horizontal Alignment")
plt.show()
Output
The chart displays three text labels
with different horizontal alignments:
Left Aligned
Center Aligned
Right Aligned
7.2 Vertical Alignment
Use verticalalignment or va to control
the vertical position of text around its anchor.
| Value | Description |
|---|---|
top |
Aligns the top of the text with the anchor. |
center |
Centers the text vertically around the anchor. |
bottom |
Aligns the bottom of the text with the anchor. |
baseline |
Aligns the text baseline with the anchor. |
center_baseline |
Aligns the center of the text's baseline area. |
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
ax.text(2, 15, "Top Aligned",
va="top")
ax.text(2, 20, "Center Aligned",
va="center")
ax.text(2, 25, "Bottom Aligned",
va="bottom")
ax.set_title("Vertical Alignment")
plt.show()
Output
The chart displays text using different
vertical alignment settings:
Top Aligned
Center Aligned
Bottom Aligned
8. Rotating Text
Matplotlib allows us to rotate text using the rotation
property. This is useful when labels need to fit into limited space.
The rotation value is specified in degrees. For example,
rotation=45 rotates text by 45 degrees.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 30, 40])
plt.text(1, 10, "Normal Text",
rotation=0)
plt.text(2, 20, "Rotated 45",
rotation=45)
plt.text(3, 30, "Rotated 90",
rotation=90)
plt.title("Text Rotation Example")
plt.show()
Output
The chart displays three text labels:
Normal Text - 0 degrees
Rotated 45 - 45 degrees
Rotated 90 - 90 degrees
9. Adding Background Boxes to Text
The bbox property adds a background box behind text.
It helps important messages stand out from the chart.
You can customize the box using properties such as
facecolor, edgecolor,
boxstyle, and alpha.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.text(
2,
20,
"Important Information",
fontsize=12,
color="darkblue",
bbox={
"facecolor": "yellow",
"edgecolor": "black",
"boxstyle": "round",
"alpha": 0.7
}
)
ax.set_title("Text Background Example")
plt.show()
Output
A line chart is displayed with the text
"Important Information".
The text appears inside a rounded yellow
background box with a black border.
Background boxes can highlight important text in a visualisation.
10. Complete Example: Student Performance Chart
Let's combine the concepts we have learned and create a student performance chart. We will add text labels, font properties, alignment, and a background box.
import matplotlib.pyplot as plt
students = ["Amit", "Rahul", "Priya", "Sneha", "Neha"]
marks = [65, 78, 92, 85, 70]
fig, ax = plt.subplots(figsize=(9, 5))
ax.bar(students, marks, color="skyblue")
ax.text(
2,
95,
"Highest Score",
ha="center",
fontsize=12,
fontweight="bold",
color="green",
bbox={
"facecolor": "white",
"edgecolor": "green",
"boxstyle": "round"
}
)
for index, mark in enumerate(marks):
ax.text(
index,
mark + 1,
str(mark),
ha="center",
fontsize=11,
fontweight="bold"
)
ax.set_title("Student Performance")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")
ax.set_ylim(0, 110)
plt.show()
Output
Bar chart displayed:
Amit - 65
Rahul - 78
Priya - 92
Sneha - 85
Neha - 70
Title: Student Performance
Each bar displays its marks above it.
"Highest Score" appears above Priya's bar
inside a highlighted text box.
11. Important Text Parameters
The following table contains commonly used parameters for
plt.text() and ax.text().
| Parameter | Purpose | Example |
|---|---|---|
x |
Horizontal text position. | x=2 |
y |
Vertical text position. | y=20 |
fontsize |
Controls text size. | fontsize=16 |
color |
Changes text colour. | color="red" |
fontweight |
Controls font thickness. | fontweight="bold" |
fontfamily |
Sets font family. | fontfamily="serif" |
ha |
Horizontal alignment. | ha="center" |
va |
Vertical alignment. | va="center" |
rotation |
Rotates text. | rotation=45 |
bbox |
Adds a background box. | bbox={"facecolor": "yellow"} |
alpha |
Controls transparency. | alpha=0.7 |
12. Practical Activity
Activity: Create a Monthly Sales Chart
Create a bar chart showing monthly sales and add text labels above every bar.
Given data:
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [12000, 15000, 18000, 14000, 22000]
Your tasks:
- Create a bar chart using the given data.
- Add a title named Monthly Sales Report.
- Display each sales value above its bar.
- Use bold text for the sales values.
- Highlight the highest sales value using a background box.
- Set appropriate X-axis and Y-axis labels.
13. Practice Questions
- What is the purpose of text in Matplotlib?
- What is the difference between
plt.text()andax.text()? - How do you specify the X and Y position of text?
- Which parameter changes the font size?
- How can you make text bold?
- What is the purpose of horizontal alignment?
- How can you rotate text by 45 degrees?
- What is the use of the
bboxparameter? - How can you change the text colour?
- Why is text useful in data visualisation?
Summary
In this lesson, we learned how to add text to Matplotlib charts using
plt.text() and ax.text(). These functions
allow us to display messages and additional information at specific
coordinates inside an axes.
We explored text positioning through X and Y coordinates and learned how to customize font size, font colour, font family, and font weight. These properties help us make text clear and readable.
We also covered horizontal and vertical alignment, text rotation,
and background boxes using the bbox property. These
features are useful when highlighting important information in charts.
Finally, we combined these concepts in a student performance chart and practiced adding labels to individual bars. In the next lesson, we will learn how to create smart annotations that point to specific data points and explain important chart information.