Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
smurd Avatar asked Mar 02 '15 12:03

smurd


People also ask

What are tick locations in MatPlotLib?

Ticks are the markers denoting data points on the axes and tick labels are the name given to ticks. By default matplotlib itself marks the data points on the axes but it has also provided us with setting their own axes having ticks and tick labels of their choice. Methods used: plt.

How do I center a tick label in MatPlotLib?

However there is no direct way to center the labels between ticks. To fake this behavior, one can place a label on the minor ticks in between the major ticks, and hide the major tick labels and minor ticks. Here is an example that labels the months, centered between the ticks.

How do I change the number of ticks in MatPlotLib?

Method 1: Using xticks() and yticks() xticks() and yticks() is the function that lets us customize the x ticks and y ticks by giving the values as a list, and we can also give labels for the ticks, matters, and as **kwargs we can apply text effects on the tick labels. Parameter: ticks – The list of x ticks.


1 Answers

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

like image 133
Ffisegydd Avatar answered Oct 01 '22 03:10

Ffisegydd