Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make xticks evenly spaced despite their values? (Matplotlib)
When plotting data with irregular x-values, Matplotlib automatically spaces ticks according to their actual values. To create evenly spaced ticks regardless of the underlying values, we can use set_ticks() and set_ticklabels() methods.
The Problem
By default, Matplotlib positions x-ticks based on their actual values. If your data has irregular spacing (like [1, 1.5, 3, 5, 6]), the ticks will be unevenly distributed on the plot.
Solution: Using set_ticks() and set_ticklabels()
We can override the default behavior by setting custom tick positions and labels ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([1, 1.5, 3, 5, 6])
y = np.power(2, x)
fig, (ax1, ax2) = plt.subplots(2, 1)
# Default behavior - ticks based on actual x values
ax1.plot(x, y)
ax1.xaxis.set_ticks(x)
ax1.set_title("Default: Unevenly spaced ticks")
# Even spacing - use sequential positions with original labels
ax2.plot(x, y)
ax2.xaxis.set_ticks(range(len(x)))
ax2.xaxis.set_ticklabels(x)
ax2.set_title("Even spacing: Sequential positions")
plt.show()
How It Works
The key is to separate tick positions from tick labels:
-
set_ticks(range(len(x)))− Creates evenly spaced positions: [0, 1, 2, 3, 4] -
set_ticklabels(x)− Uses original values as labels: [1, 1.5, 3, 5, 6]
Alternative Approach: Using plt.xticks()
For single plots, you can use the shorthand plt.xticks() function ?
import numpy as np
from matplotlib import pyplot as plt
x = np.array([1, 1.5, 3, 5, 6])
y = np.power(2, x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, marker='o')
plt.xticks(range(len(x)), x)
plt.title("Even spacing using plt.xticks()")
plt.grid(True, alpha=0.3)
plt.show()
Comparison
| Method | Tick Spacing | Best For |
|---|---|---|
Default set_ticks(x)
|
Based on actual values | Numerical data with meaningful spacing |
set_ticks(range(len(x))) |
Even spacing | Categorical data or irregular intervals |
plt.xticks(range(len(x)), x) |
Even spacing | Quick solution for single plots |
Conclusion
Use set_ticks(range(len(x))) with set_ticklabels(x) to create evenly spaced ticks regardless of actual x-values. This approach is particularly useful for categorical data or when you want consistent visual spacing.
