How to set the location of small ticks in matplotlib

I want to draw a grid along the x axis on the matplotlib chart at the positions of minor ticks, but not at the positions of the main ticks. My mayor clerks are at positions 0, 1, 2, 3, 4, 5 and should stay there. I want the grid to be 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, as it gives locations at 0.5, 1.0, 1.5, ... How can I manually set the positions of minor ticks?

+5
source share
1 answer

You can use matplotlib.ticker.AutoMinorLocator . This automatically places the small N-1 ticks in places equally spaced between your main ticks.

For example, if you used AutoMinorLocator(5) , then this will place 4 minor ticks at an equal distance between each pair of main ticks. For your use case, you want AutoMinorLocator(2) simply place it in the middle.

 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 you need to scale your data, for example, so that your main ticks are at [0, 10, 20, 30, 40, 50] , then your minor ticks will be scaled to positions [5, 15, 25, 35, 45] .

If you really need hard locations, even after scaling / resizing, check out matplotlib.ticker.FixedLocator . With this, you can pass a fixed list, for example FixedLocator([0.5, 1.5, 2.5, 3.5, 4.5]) .

+13
source

Source: https://habr.com/ru/post/1214475/


All Articles