Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minor ticks in matplotlib's colorbar

I'm currently trying to set minor ticks in the colorbar but simply can't make it work. There are 3 approaches which I've tried (see code below), but all of them didn't appear to be working. Is it actually possible to have minor ticks in the colorbar?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.ticker import FixedLocator, FormatStrFormatter

# fill grid
x = np.linspace(1,10,10)
y = np.linspace(1,10,10)

X, Y = np.meshgrid(x,y)
Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)

# plot
f, ax = subplots(1)
p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)

minor_ticks = np.arange(1,10,2)
#cb.set_ticks(minor_ticks, minor=True) # error: doesn't support keyword argument 'minor'
#cb.ax.xaxis.set_ticks(minor_ticks, minor=True) # plots an extremely small colorbar, with wrong ticks
#cb.ax.xaxis.set_minor_locator(FixedLocator(minor_ticks)) # nothing happens
plt.show()
like image 423
nilfisque Avatar asked Nov 19 '13 18:11

nilfisque


Video Answer


1 Answers

You're on the right track, you just need cb.ax.minorticks_on().

For example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# fill grid
x = np.linspace(1,10,10)
y = np.linspace(1,10,10)

X, Y = np.meshgrid(x,y)
Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)

# plot
f, ax = plt.subplots()
p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)

cb.ax.minorticks_on()

plt.show()

enter image description here


If you want just the ticks that you specify, you still set them in the "normal" way, but be aware that the colorbar axes coordinate system ranges from 0-1 regardless of the range of your data.

For that reason, to set the specific values that you want, we need to call the normalize the tick locations using the same norm instance that the image is using.

For example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# fill grid
x = np.linspace(1,10,10)
y = np.linspace(1,10,10)

X, Y = np.meshgrid(x,y)
Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)

# plot
f, ax = plt.subplots()
p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)

# We need to nomalize the tick locations so that they're in the range from 0-1...
minorticks = p.norm(np.arange(1, 10, 2))
cb.ax.xaxis.set_ticks(minorticks, minor=True)

plt.show()  

enter image description here

like image 58
Joe Kington Avatar answered Sep 22 '22 08:09

Joe Kington