smurd
smurd

Reputation: 233

How can i set the location of minor ticks in matplotlib

I want to draw a grid on the x-axis in a matplotlib plot at the positions of the minor ticks but not at the positions of the major ticks. My mayor ticks are at the positions 0, 1, 2, 3, 4, 5 and have to remain there. I want the grid at 0.5, 1.5, 2.5, 3.5, 4.5.

....
from matplotlib.ticker import MultipleLocator
....
minorLocator   = MultipleLocator(0.5)
ax.xaxis.set_minor_locator(minorLocator)
plt.grid(which='minor')

The code above does not work since it gives the locations at 0.5, 1.0, 1.5, ... How can I set the positions of the minor ticks manually?

Upvotes: 19

Views: 37767

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53668

You can use matplotlib.ticker.AutoMinorLocator. This will automatically place N-1 minor ticks at locations spaced equally between your major ticks.

For example, if you used AutoMinorLocator(5) then that will place 4 minor ticks equally spaced between each pair of major ticks. For your use case you want AutoMinorLocator(2) to just place one at the mid-point.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.ticker import AutoMinorLocator

N = 1000
x = np.linspace(0, 5, N)
y = x**2

fig, ax = plt.subplots()

ax.plot(x, y)

minor_locator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator)
plt.grid(which='minor')

plt.show()

Example plot

Using AutoMinorLocator has the advantage that should you need to scale your data up, for example so your major ticks are at [0, 10, 20, 30, 40, 50], then your minor ticks will scale up to positions [5, 15, 25, 35, 45].

If you really need hard-set locations, even after scaling/changing, then look up matplotlib.ticker.FixedLocator. With this you can pass a fixed list, for example FixedLocator([0.5, 1.5, 2.5, 3.5, 4.5]).

Upvotes: 29

Related Questions