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
Selected Reading
How to set "step" on axis X in my figure in Matplotlib Python 2.6.6?
To set step on X-axis in a figure in Matplotlib Python, you can control the tick positions and labels using several methods. This allows you to customize how data points are displayed along the X-axis.
Using set_xticks() and set_xticklabels()
The most direct approach is to use set_xticks() to define tick positions and set_xticklabels() to set custom labels ?
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4] y = [1.2, 1.9, 3.1, 4.2] plt.plot(x, y) ax1 = plt.subplot() ax1.set_xticks(x) ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45) plt.show()
[Displays a plot with custom X-axis labels "one", "two", "three", "four" rotated at 45 degrees]
Using plt.xticks() Method
You can also use plt.xticks() for a more concise approach ?
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [2.1, 3.2, 1.8, 4.5, 2.7, 3.9]
plt.figure(figsize=(8, 4))
plt.plot(x, y, marker='o')
# Set custom step and labels
plt.xticks([1, 3, 5], ['Jan', 'Mar', 'May'])
plt.ylabel('Values')
plt.title('Custom X-axis Steps')
plt.show()
[Displays a plot with X-axis ticks only at positions 1, 3, and 5 with labels "Jan", "Mar", "May"]
Setting Regular Step Intervals
For regular intervals, you can use range() to create evenly spaced ticks ?
import matplotlib.pyplot as plt
x = range(0, 21) # 0 to 20
y = [i**2 for i in x]
plt.figure(figsize=(10, 5))
plt.plot(x, y)
# Set ticks every 5 units
plt.xticks(range(0, 21, 5)) # 0, 5, 10, 15, 20
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Regular Step Intervals')
plt.show()
[Displays a quadratic plot with X-axis ticks at 0, 5, 10, 15, and 20]
Key Parameters
- positions − List or array of tick positions
- labels − List of custom labels for each tick
- rotation − Angle to rotate tick labels (useful for long labels)
- fontsize − Size of tick label text
Conclusion
Use set_xticks() and set_xticklabels() for precise control over X-axis steps and labels. For simpler cases, plt.xticks() provides a convenient shorthand method.
Advertisements
