matplotlib 颜色栏中的小刻度 [英] Minor ticks in matplotlib's colorbar

查看:32
本文介绍了matplotlib 颜色栏中的小刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在颜色栏中设置小刻度,但根本无法使其工作.我尝试了 3 种方法(请参阅下面的代码),但它们似乎都不起作用.实际上是否可能在颜色栏中出现较小的滴答声?

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

推荐答案

您在正确的轨道上,只需要 cb.ax.minorticks_on().

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

例如:

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

如果您只想要您指定的刻度,您仍然以正常"方式设置它们,但请注意,无论您的数据范围如何,颜色条轴坐标系的范围都是 0-1.

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.

因此,要设置所需的特定值,我们需要使用与图像使用的相同的 norm 实例来调用刻度位置.

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.

例如:

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

这篇关于matplotlib 颜色栏中的小刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆