Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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()

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]).

Beware! This will silently do the wrong thing if your major ticks are not equally spaced. You need to use FixedLocator. Also, that breaks if your ticks are dates, apparently you need to pass them through matplotlib.dates.date2num first (stackoverflow.com/a/37162866/3538165). Whyyyyyy.... – Resigned June 2023 May 20, 2020 at 16:05

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.