Custom Ticks in Matplotlib
Learn how to customize tick positions on the X-axis and Y-axis. Understand tick placement, spacing, intervals, and the use of Matplotlib tick functions to create clear and readable charts.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand ticks and tick positions in Matplotlib.
- Customize X-axis and Y-axis tick positions.
- Use
plt.xticks()andplt.yticks(). - Set custom tick intervals using NumPy.
- Customize ticks using the Object-Oriented API.
- Use major and minor ticks.
- Control tick appearance and spacing.
2. Introduction to Custom Ticks
Ticks are the small marks displayed along the X-axis and Y-axis of a chart. They help users understand the values and positions represented in a visualization.
Matplotlib automatically selects tick positions based on the data and available plotting space. However, sometimes the automatically generated ticks are not suitable for our requirements.
Custom ticks allow us to define exactly where tick marks should appear. We can choose specific positions and control the intervals between them.
What are Custom Ticks?
Custom ticks are manually selected positions along an axis. They help display meaningful values and improve the readability of charts.
Tick marks indicate selected numerical positions along the chart axes.
3. Understanding X-Axis Ticks Using xticks()
The plt.xticks() function is used to get or set the tick positions
and labels on the X-axis.
By passing a list of numerical values, you can specify exactly where the X-axis tick marks should appear.
Syntax
plt.xticks(ticks)
Example: Set Custom X-Axis Ticks
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [10, 20, 15, 30, 25, 35]
plt.plot(x, y, marker="o")
plt.xticks([1, 2, 3, 4, 5, 6])
plt.title("Custom X-Axis Ticks")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed.
The X-axis shows tick positions at 1, 2, 3, 4, 5, and 6.
The Y-axis ticks are selected automatically.
Each data point is represented by a circular marker.
Example: Custom X-Axis Tick Positions
import matplotlib.pyplot as plt
x = [0, 5, 10, 15, 20, 25]
y = [10, 15, 20, 25, 30, 35]
plt.plot(x, y, marker="o")
plt.xticks([0, 10, 20, 25])
plt.title("Selected X-Axis Tick Positions")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The X-axis displays only four selected tick positions:
0, 10, 20, and 25.
Other possible tick positions are not displayed.
4. Understanding Y-Axis Ticks Using yticks()
The plt.yticks() function is used to customize tick positions
on the Y-axis.
You can pass a list of numerical values to determine where the vertical axis tick marks should appear.
Syntax
plt.yticks(ticks)
Example: Set Custom Y-Axis Ticks
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y, marker="o")
plt.yticks([0, 10, 20, 30, 40, 50])
plt.title("Custom Y-Axis Ticks")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed.
The Y-axis shows tick positions at:
0, 10, 20, 30, 40, and 50.
The X-axis ticks are selected automatically.
Example: Select Specific Y-Axis Ticks
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [15, 30, 45, 60, 75]
plt.plot(x, y, marker="o", color="green")
plt.yticks([0, 25, 50, 75])
plt.title("Selected Y-Axis Ticks")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The chart displays a green line.
The Y-axis contains tick marks at 0, 25, 50, and 75.
The X-axis tick positions are generated automatically.
5. Custom Tick Labels
Sometimes numerical tick positions are not meaningful enough. For example, a chart may represent months, weekdays, product names, or other categories.
Matplotlib allows you to provide custom text labels for tick positions. The tick positions and their labels should correspond to each other.
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(
[1, 2, 3, 4, 5, 6],
["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 labels are Jan, Feb, Mar, Apr, May, and Jun.
The Y-axis displays sales values.
Each month is represented by a point on the line.
Numerical X-axis positions are displayed with meaningful month labels.
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("Custom Y-Axis Labels")
plt.xlabel("X Values")
plt.ylabel("Performance")
plt.show()
Expected Output
The Y-axis displays text labels instead of numerical values:
Low, Medium, High, and Very High.
The line chart uses the original numerical data values.
6. Setting Tick Intervals Using NumPy
When working with larger datasets, manually writing every tick position can be time-consuming. NumPy provides useful functions for generating regular numerical sequences.
The np.arange() function generates values at a specified interval.
These values can be used directly as custom tick positions.
Example: Using np.arange()
import matplotlib.pyplot as plt
import numpy as np
x = [0, 5, 10, 15, 20, 25, 30]
y = [10, 15, 20, 25, 30, 35, 40]
plt.plot(x, y, marker="o")
plt.xticks(np.arange(0, 31, 5))
plt.title("Custom Tick Intervals")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The X-axis displays ticks at:
0, 5, 10, 15, 20, 25, and 30.
The interval between consecutive tick positions is 5.
Understanding np.arange()
np.arange(start, stop, step)
| Parameter | Description | Example |
|---|---|---|
| start | Starting value of the sequence. | 0 |
| stop | Value at which sequence generation stops. | 31 |
| step | Difference between consecutive values. | 5 |
Example: Different Tick Intervals
import numpy as np
print(np.arange(0, 11, 2))
print(np.arange(0, 21, 5))
print(np.arange(10, 51, 10))
Expected Output
[ 0 2 4 6 8 10]
[ 0 5 10 15 20]
[10 20 30 40 50]
np.arange() when you need regular
tick intervals such as every 2, 5, 10, or 100 units.
7. Custom Ticks Using the Object-Oriented API
Matplotlib also supports custom ticks through the Object-Oriented API. Instead of using pyplot functions, you can configure ticks directly through the Axes object.
| Pyplot Function | Axes Method | Purpose |
|---|---|---|
plt.xticks() |
ax.set_xticks() |
Set X-axis tick positions. |
plt.yticks() |
ax.set_yticks() |
Set Y-axis tick positions. |
plt.xticks(labels=...) |
ax.set_xticklabels() |
Set X-axis tick labels. |
plt.yticks(labels=...) |
ax.set_yticklabels() |
Set Y-axis tick labels. |
Example: Using set_xticks() and set_yticks()
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y, marker="o")
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([0, 10, 20, 30, 40])
ax.set_title("Custom Ticks Using Axes")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed.
The X-axis contains tick positions from 1 to 5.
The Y-axis contains tick positions at 0, 10, 20, 30, and 40.
Tick positions are configured through the Axes object.
Example: Set Positions and Labels Together
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 130, 180, 200, 220]
ax.plot(months, sales, marker="o")
ax.set_xticks(
[1, 2, 3, 4, 5, 6],
labels=["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
)
ax.set_title("Monthly Sales")
ax.set_xlabel("Months")
ax.set_ylabel("Sales")
plt.show()
Expected Output
A line chart displays monthly sales.
The X-axis displays Jan, Feb, Mar, Apr, May, and Jun.
The labels are assigned directly while setting tick positions.
set_xticks(positions, labels=...) or
set_yticks(positions, labels=...) to set positions and
labels together. This avoids mismatches between tick positions and labels.
8. Major and Minor Ticks
Matplotlib supports two common types of ticks: major ticks and minor ticks. Major ticks are the primary marks displayed along an axis. Minor ticks provide additional smaller divisions between major ticks.
Major Ticks
Major ticks represent the main divisions of an axis. They are commonly accompanied by visible tick labels.
Minor Ticks
Minor ticks represent smaller divisions between major ticks. They are useful when more detailed measurements are required.
Example: Enable Minor Ticks
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y, marker="o")
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([0, 10, 20, 30, 40])
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.grid(which="major", linestyle="-", alpha=0.5)
ax.grid(which="minor", linestyle=":", alpha=0.3)
ax.set_title("Major and Minor Ticks")
plt.show()
Expected Output
A line chart displays major and minor tick divisions.
Major ticks represent the primary axis values.
Minor ticks add smaller divisions between major ticks.
The chart displays separate major and minor grid lines.
Major ticks show the primary values, while minor ticks add smaller divisions.
9. Controlling Tick Appearance
In addition to changing tick positions, Matplotlib allows you to customize the appearance of ticks. You can change their direction, length, width, color, and label size.
The tick_params() method provides a convenient way to customize
tick marks and tick labels.
Example: Customize Tick Appearance
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y, marker="o")
ax.tick_params(
axis="both",
direction="in",
length=8,
width=2,
colors="blue",
labelsize=12
)
ax.set_title("Customized Tick Appearance")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed with customized ticks.
Tick marks point inward.
Tick marks have a length of 8 and a width of 2.
Tick marks and tick labels use blue coloring.
Tick label text uses a font size of 12.
Common tick_params() Settings
| Parameter | Description | Example |
|---|---|---|
| axis | Selects the axis to customize. | "x", "y", "both" |
| direction | Controls tick direction. | "in", "out", "inout" |
| length | Controls tick mark length. | 8 |
| width | Controls tick mark width. | 2 |
| colors | Sets tick and label color. | "blue" |
| labelsize | Sets tick label font size. | 12 |
tick_params() when you want to improve
the appearance of axis ticks without changing their positions.
10. Removing Tick Marks
Sometimes a chart looks cleaner without tick marks or tick labels. Matplotlib allows you to remove them by setting empty tick positions.
Example: Remove X-Axis and Y-Axis Ticks
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([])
plt.yticks([])
plt.title("Chart Without Tick Marks")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed without X-axis and Y-axis tick marks.
The axis labels and chart title remain visible.
Example: Remove Ticks Using Axes
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_xticks([])
ax.set_yticks([])
ax.set_title("No Axis Ticks")
plt.show()
Expected Output
The chart is displayed without tick marks or tick labels.
The line and chart title remain visible.
11. Common Mistakes
| Mistake | Explanation | Correct Approach |
|---|---|---|
| Using xticks() for Y-axis | xticks() controls only horizontal tick positions. | Use yticks() for vertical tick positions. |
| Incorrect label count | The number of labels does not match the tick positions. | Provide matching positions and labels. |
| Too many tick positions | Excessive tick marks can make the chart difficult to read. | Choose suitable intervals. |
| Confusing ticks with axis limits | Ticks specify positions, while limits define the visible range. | Use xlim() and ylim() for limits. |
| Using tick labels without positions | Labels need corresponding tick positions. | Set positions and labels together. |
12. Practical Activity
Activity: Create a Monthly Sales Chart
Create a line chart showing sales for six months. Customize the X-axis and Y-axis ticks to make the chart easy to understand.
Requirements
- Create sales data for six months.
- Display the data using a line plot.
- Use month names as X-axis tick labels.
- Set Y-axis ticks at intervals of 50.
- Customize tick direction and size.
- Add a chart title and axis labels.
Sample Solution
import matplotlib.pyplot as plt
import numpy as np
months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 200, 180, 250, 300]
fig, ax = plt.subplots()
ax.plot(
months,
sales,
marker="o",
color="blue",
linewidth=2
)
ax.set_xticks(
months,
labels=["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
)
ax.set_yticks(np.arange(0, 351, 50))
ax.tick_params(
axis="both",
direction="out",
length=6,
width=1.5,
labelsize=11
)
ax.set_title("Monthly Sales Report")
ax.set_xlabel("Months")
ax.set_ylabel("Sales")
plt.show()
Expected Output
A line chart displays monthly sales for six months.
The X-axis displays Jan, Feb, Mar, Apr, May, and Jun.
The Y-axis displays values at intervals of 50.
Tick marks are customized with an outward direction.
The chart displays its title and axis labels.
13. Practice Questions
Basic Questions
- What are ticks in Matplotlib?
- Which function customizes X-axis tick positions?
- Which function customizes Y-axis tick positions?
- What is the purpose of custom tick labels?
- What are major and minor ticks?
Intermediate Questions
- How can you set custom X-axis tick positions?
- How can you set custom Y-axis tick labels?
- How can NumPy help generate regular tick intervals?
- What is the difference between set_xticks() and set_xlim()?
- What is the purpose of tick_params()?
Practical Questions
- Create a chart with custom X-axis tick positions.
- Display month names instead of numerical X-axis labels.
- Generate Y-axis ticks using np.arange().
- Enable major and minor ticks on both axes.
- Customize tick length, direction, width, and label size.
Summary
Ticks are marks displayed along the X-axis and Y-axis that help users understand the values represented in a chart. Matplotlib automatically selects tick positions, but custom ticks allow developers to control exactly where these marks appear.
The pyplot functions xticks() and yticks() are used to customize horizontal and vertical tick positions. Custom text labels can also be assigned to tick positions to represent categories, months, or other meaningful values.
NumPy functions such as arange() help generate regular tick intervals. The Object-Oriented API provides set_xticks() and set_yticks() methods for configuring tick positions through an Axes object.
Matplotlib also supports major and minor ticks, and tick_params() provides control over tick direction, length, width, color, and label size. Properly customized ticks improve chart readability and presentation.