简体   繁体   English

matplotlib的colorbar中的小刻度

[英]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. 我尝试了3种方法(见下面的代码),但所有这些方法似乎都没有起作用。 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()

You're on the right track, you just need cb.ax.minorticks_on() . 你走在正确的轨道上,你只需要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()

在此输入图像描述


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. 如果您只想要指定的刻度,您仍然可以以“正常”方式设置它们,但请注意,无论数据范围如何,颜色条轴坐标系的范围都是0-1。

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. 因此,要设置所需的特定值,我们需要使用图像使用的相同norm实例来调用标记位置。

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM