我目前正在尝试在颜色栏中设置较小的刻度,但无法使其正常工作。我尝试了3种方法(请参见下面的代码),但它们似乎都没有起作用。实际上是否可能在颜色栏中出现较小的滴答声?
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()
即可。
例如:
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。
因此,要设置所需的特定值,我们需要使用图像使用的相同
norm
实例来调用标准化滴答位置。例如:
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()
关于python - matplotlib的颜色栏中的小刻度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20079270/