Modifying the interval of axis ticks in matplotlib can be easily done using the xticks() or yticks() methods. Examples
Default values of xticks
First, let's create a simple plot as a reference.
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
plt.grid()
plt.title('How to modify the interval of the axis ticks in matplotlib ?')
plt.savefig('modify_interval_of_the_axis_ticks_in_matplotlib_01.png')
plt.show()
Modify the interval of the axis ticks using xticks()
One solution for adjusting the ticks on the x-axis is using the function xticks() and providing a list of values as an argument.
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
xticks_pos = [i/2.0 for i in range(12)]
plt.xticks(xticks_pos)
plt.grid()
plt.title('How to modify the interval of the axis ticks in matplotlib ?')
plt.savefig('modify_interval_of_the_axis_ticks_in_matplotlib_02.png')
plt.show()
Output
Rotating xtick labels
Please note that you can use the method "xtick" to rotate the tick labels:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
xticks_pos = [i/3.0 for i in range(18)]
plt.xticks(xticks_pos, rotation=90)
plt.grid()
plt.title('How to modify the interval of the axis ticks in matplotlib ?')
plt.savefig('modify_interval_of_the_axis_ticks_in_matplotlib_03.png')
plt.show()
Changing xtick labels
Finally, you can also customize the labels:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
xticks_pos = [i/2.0 for i in range(12)]
xticks_labels = [l for l in 'abcdefghijkl' ]
plt.xticks(xticks_pos,xticks_labels)
plt.grid()
plt.title('How to modify the interval of the axis ticks in matplotlib ?')
plt.savefig('modify_interval_of_the_axis_ticks_in_matplotlib_04.png')
plt.show()
References
Links | Site |
---|---|
matplotlib.pyplot.xticks | matplotlib.org |
Rotating custom tick labels | matplotlib.org |