Controlling tick spacing
In matplotlib, ticks are small marks on both the axes of a figure. So far, we let matplotlib handle the position of the ticks on the axes legend. As we will see in this recipe, we can manually override this mechanism.
How to do it...
In this script, we will manipulate the gap between the ticks on the x axis:
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker X = np.linspace(-15, 15, 1024) Y = np.sinc(X) ax = plt.axes() ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(1)) plt.plot(X, Y, c = 'k') plt.show()
Now, smaller ticks are seen between the usual ticks:
How it works...
We forced the horizontal ticks to appear by steps of 5 units. Moreover, we also added small ticks, appearing by steps of 1 unit. To do so, we perform the following steps:
We get an instance of the
Axes
object: the object that manages the axes of a figure. This is the purpose ofax = plot.axes()
.For the x axis...