Tick Labels in Matplotlib
Learn how to customize tick labels in Matplotlib. Understand label formatting, rotation, font size, alignment, colors, and formatting numerical values to make charts more readable.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand tick labels in Matplotlib.
- Set custom labels on the X-axis and Y-axis.
- Change tick label font size, color, and rotation.
- Control horizontal and vertical label alignment.
- Format numerical tick labels.
- Use formatters from
matplotlib.ticker. - Customize tick labels using the Object-Oriented API.
2. Introduction to Tick Labels
Tick labels are the text values displayed next to tick marks on the X-axis and Y-axis. They help users understand the meaning of numerical positions represented in a chart.
For example, a sales chart may display month names such as January, February, and March instead of numerical values such as 1, 2, and 3. Tick labels make the information easier to understand.
What are Tick Labels?
Tick labels are text representations associated with tick positions. They can contain numbers, dates, category names, percentages, currency values, or other meaningful information.
Tick labels display meaningful month names below their corresponding tick positions.
3. Setting Custom Tick Labels
Matplotlib allows you to assign custom text labels to tick positions.
You can use the plt.xticks() and plt.yticks()
functions to define positions and their corresponding labels.
Example: Custom X-Axis Labels
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 130, 180, 200, 220]
plt.plot(months, sales, marker="o")
plt.xticks(
months,
["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
)
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.show()
Expected Output
A line chart displays monthly sales.
The X-axis displays Jan, Feb, Mar, Apr, May, and Jun.
Each label is positioned below its corresponding tick.
The Y-axis displays the sales values.
Example: Custom Y-Axis Labels
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y, marker="o")
plt.yticks(
[10, 20, 30, 40],
["Low", "Medium", "High", "Very High"]
)
plt.title("Performance Levels")
plt.xlabel("X Values")
plt.ylabel("Performance")
plt.show()
Expected Output
A line chart displays four data points.
The Y-axis labels are Low, Medium, High, and Very High.
The original numerical data values remain unchanged.
4. Changing Tick Label Font Size
You can change the font size of tick labels to make them easier to read. This is especially useful when creating presentation charts or charts containing many labels.
The fontsize argument can be used with plt.xticks()
and plt.yticks().
Example: Change X-Axis Font Size
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5]
sales = [100, 150, 130, 180, 200]
plt.plot(months, sales, marker="o")
plt.xticks(
months,
["Jan", "Feb", "Mar", "Apr", "May"],
fontsize=14
)
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.show()
Expected Output
The X-axis displays month names.
The tick labels use a font size of 14.
The line chart and its data remain unchanged.
Example: Change Y-Axis Font Size
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [20, 40, 60, 80, 100]
plt.plot(x, y)
plt.yticks(fontsize=14)
plt.title("Customized Y-Axis Labels")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The Y-axis tick labels are displayed with a font size of 14.
The X-axis tick label font size remains at its default setting.
5. Changing Tick Label Colors
Matplotlib allows you to change the color of tick labels. This helps distinguish important axis information and match the chart's overall visual style.
Example: Set X-Axis Label Color
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y, marker="o")
plt.xticks(color="blue")
plt.title("Colored X-Axis Labels")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The X-axis tick labels are displayed in blue.
The Y-axis tick labels keep their default color.
The plotted line remains unchanged.
Example: Customize Both Axis Label Colors
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y)
plt.xticks(color="blue")
plt.yticks(color="green")
plt.title("Colored Tick Labels")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
X-axis tick labels appear in blue.
Y-axis tick labels appear in green.
The chart displays the original plotted data.
6. Rotating Tick Labels
When tick labels are long or closely spaced, they may overlap. Rotation changes the angle of tick labels to improve readability.
The rotation argument can be used with plt.xticks()
or plt.yticks().
Example: Rotate X-Axis Labels
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 130, 180, 200, 220]
plt.plot(months, sales, marker="o")
plt.xticks(
months,
["January", "February", "March",
"April", "May", "June"],
rotation=45
)
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.show()
Expected Output
The X-axis displays full month names.
Each month label is rotated by 45 degrees.
The rotated labels reduce horizontal overlap.
Rotated labels help display longer category names without horizontal overlap.
Example: Rotate Labels by 90 Degrees
import matplotlib.pyplot as plt
categories = ["Product One", "Product Two",
"Product Three", "Product Four"]
values = [100, 150, 120, 180]
plt.bar(categories, values)
plt.xticks(rotation=90)
plt.title("Product Sales")
plt.xlabel("Products")
plt.ylabel("Sales")
plt.show()
Expected Output
A bar chart displays four product categories.
The X-axis labels are rotated vertically by 90 degrees.
Long category names become easier to distinguish.
7. Horizontal and Vertical Alignment
Alignment controls the position of tick label text relative to its tick mark. Matplotlib provides horizontal and vertical alignment options.
The ha argument controls horizontal alignment, while
va controls vertical alignment.
| Parameter | Common Values | Purpose |
|---|---|---|
| ha | left, center, right |
Controls horizontal alignment. |
| va | top, center, bottom, baseline |
Controls vertical alignment. |
Example: Horizontal Alignment
import matplotlib.pyplot as plt
categories = ["January", "February", "March",
"April", "May"]
values = [100, 150, 130, 180, 200]
plt.plot(range(1, 6), values, marker="o")
plt.xticks(
range(1, 6),
categories,
rotation=45,
ha="right"
)
plt.title("Tick Label Alignment")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.show()
Expected Output
The X-axis month labels are rotated by 45 degrees.
The labels are aligned to the right of their tick positions.
The label layout is easier to read.
Example: Vertical Alignment
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_xticks(
[1, 2, 3, 4],
labels=["One", "Two", "Three", "Four"],
rotation=30,
ha="right",
va="top"
)
ax.set_title("Vertical and Horizontal Alignment")
plt.show()
Expected Output
The X-axis labels are rotated by 30 degrees.
The labels use right horizontal alignment.
The labels use top vertical alignment.
8. Formatting Numerical Tick Labels
Sometimes numerical tick labels need a particular format. For example, a chart may display currency values, percentages, or numbers with thousands separators.
Matplotlib provides formatting tools through the
matplotlib.ticker module.
Example: Display Currency Values
import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
fig, ax = plt.subplots()
months = [1, 2, 3, 4, 5]
sales = [1000, 2500, 3000, 4500, 5000]
ax.plot(months, sales, marker="o")
ax.yaxis.set_major_formatter(
StrMethodFormatter('Rs. {x:,.0f}')
)
ax.set_title("Sales with Currency Formatting")
ax.set_xlabel("Months")
ax.set_ylabel("Sales Amount")
plt.show()
Expected Output
The Y-axis displays sales values with a currency prefix.
Example tick labels:
Rs. 1,000
Rs. 2,000
Rs. 3,000
Rs. 4,000
Rs. 5,000
The exact tick positions are selected by Matplotlib.
Example: Display Percentage Values
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
fig, ax = plt.subplots()
months = [1, 2, 3, 4, 5]
growth = [0.10, 0.25, 0.40, 0.55, 0.70]
ax.plot(months, growth, marker="o")
ax.yaxis.set_major_formatter(
PercentFormatter(xmax=1)
)
ax.set_title("Monthly Growth Percentage")
ax.set_xlabel("Months")
ax.set_ylabel("Growth")
plt.show()
Expected Output
The Y-axis displays percentage labels.
Values are formatted as percentages such as:
10%, 20%, 30%, 40%, 50%, 60%, and 70%.
The plotted data remains in decimal form.
StrMethodFormatter for custom text and
numerical formats. Use PercentFormatter when displaying percentage values.
9. Using FuncFormatter
The FuncFormatter class allows you to create your own
formatting function for tick labels.
This is useful when built-in formatters do not provide the exact output required by your chart.
Example: Custom Tick Formatting
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
def format_sales(value, position):
return f"Sales: {value:.0f}"
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [100, 200, 300, 400, 500]
ax.plot(x, y, marker="o")
ax.yaxis.set_major_formatter(
FuncFormatter(format_sales)
)
ax.set_title("Custom Tick Formatter")
ax.set_xlabel("X Values")
ax.set_ylabel("Sales")
plt.show()
Expected Output
The Y-axis tick labels display the text "Sales:"
followed by the corresponding numerical value.
Example:
Sales: 100
Sales: 200
Sales: 300
Sales: 400
Sales: 500
Actual tick positions are selected by Matplotlib.
Understanding FuncFormatter
The formatting function receives two arguments. The first argument represents the tick value, and the second argument represents the tick position.
def format_sales(value, position):
return f"Sales: {value:.0f}"
The function returns a string that Matplotlib displays as the corresponding tick label.
10. Custom Tick Labels Using the Object-Oriented API
The Object-Oriented API provides methods for controlling tick labels through the Axes object.
You can use set_xticks() and set_yticks()
to assign positions and labels. You can also customize existing
tick label objects using tick_params().
Example: Set Custom Labels Using Axes
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
months = [1, 2, 3, 4, 5]
sales = [100, 150, 130, 180, 200]
ax.plot(months, sales, marker="o")
ax.set_xticks(
months,
labels=["Jan", "Feb", "Mar", "Apr", "May"]
)
ax.tick_params(
axis="x",
labelsize=12,
labelcolor="blue"
)
ax.set_title("Customized Tick Labels")
ax.set_xlabel("Months")
ax.set_ylabel("Sales")
plt.show()
Expected Output
A line chart displays monthly sales.
The X-axis displays month names.
The X-axis tick labels use blue color and font size 12.
The chart is configured through the Axes object.
Example: Customize Y-Axis Labels
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
ax.plot(x, y)
ax.set_yticks(
[10, 20, 30, 40, 50],
labels=["Low", "Medium", "Good", "High", "Excellent"]
)
ax.tick_params(
axis="y",
labelsize=11,
labelcolor="green"
)
ax.set_title("Performance Levels")
ax.set_xlabel("X Values")
ax.set_ylabel("Performance")
plt.show()
Expected Output
The Y-axis displays custom performance labels.
The labels appear in green with font size 11.
The line chart displays the original numerical values.
11. Common Mistakes
| Mistake | Explanation | Correct Approach |
|---|---|---|
| Incorrect label count | The number of labels does not match the tick positions. | Provide matching positions and labels. |
| Overlapping labels | Long labels may overlap when they are close together. | Use rotation or adjust label spacing. |
| Using incorrect formatter | The formatter may not match the actual data representation. | Choose the correct formatter for the data. |
| Confusing tick positions and labels | Tick positions are numerical locations, while labels are displayed text. | Configure positions and labels separately or together. |
| Using very small font size | Small labels can be difficult to read. | Choose a suitable font size. |
12. Practical Activity
Activity: Create a Monthly Revenue Chart
Create a line chart that displays monthly revenue. Customize the tick labels to make the chart professional and readable.
Requirements
- Create revenue data for six months.
- Display month names on the X-axis.
- Display currency values on the Y-axis.
- Change X-axis tick label font size.
- Rotate month labels by 45 degrees.
- Customize Y-axis tick label color.
- Add a title and axis labels.
Sample Solution
import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
months = [1, 2, 3, 4, 5, 6]
revenue = [10000, 15000, 13000, 18000, 20000, 25000]
fig, ax = plt.subplots()
ax.plot(
months,
revenue,
marker="o",
color="blue",
linewidth=2
)
ax.set_xticks(
months,
labels=["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
)
ax.yaxis.set_major_formatter(
StrMethodFormatter('Rs. {x:,.0f}')
)
ax.tick_params(
axis="x",
labelsize=11,
rotation=45
)
ax.tick_params(
axis="y",
labelsize=11,
labelcolor="green"
)
ax.set_title("Monthly Revenue Report")
ax.set_xlabel("Months")
ax.set_ylabel("Revenue")
plt.tight_layout()
plt.show()
Expected Output
A line chart displays revenue for six months.
The X-axis displays month abbreviations.
Month labels are rotated by 45 degrees.
The Y-axis displays revenue with the Rs. prefix.
Y-axis tick labels are green.
The chart displays its title and axis labels.
13. Practice Questions
Basic Questions
- What are tick labels in Matplotlib?
- How can you set custom X-axis labels?
- How can you change tick label font size?
- What is the purpose of the rotation parameter?
- What are horizontal and vertical alignments?
Intermediate Questions
- How can you display month names instead of numbers?
- How can you format tick labels as currency?
- What is the purpose of StrMethodFormatter?
- What is the difference between PercentFormatter and FuncFormatter?
- How can you customize tick labels using tick_params()?
Practical Questions
- Create a chart with custom month labels.
- Rotate X-axis labels by 45 degrees.
- Change Y-axis tick label color and font size.
- Format Y-axis values as percentages.
- Create a custom formatter that displays currency values.
Summary
Tick labels are the text values displayed next to tick marks on the X-axis and Y-axis. They help users understand the meaning of values and categories represented in a chart.
Matplotlib provides xticks() and yticks() functions for assigning custom labels. Font size, color, rotation, and alignment can also be customized to improve chart readability.
The matplotlib.ticker module provides formatting tools such as StrMethodFormatter, PercentFormatter, and FuncFormatter. These formatters help display currency, percentage, and custom numerical labels.
The Object-Oriented API provides set_xticks(), set_yticks(), and tick_params() for configuring labels through an Axes object. Properly formatted tick labels make visualizations clearer, more informative, and easier to understand.