使matplotlib颜色条在数据限制之外打勾以与boundary关键字一起使用 [英] getting a matplotlib colorbar tick outside data limits for use with boundaries keyword
问题描述
我正在尝试使用颜色栏标记使用imshow绘制的离散编码值.我可以使用 boundaries
和 values
关键字实现所需的颜色条,这实际上使颜色条的最大值比要绘制的数据的最大值大1.
I am trying to use a colorbar to label discrete, coded values plotted using imshow. I can achieve the colorbar that I want using the boundaries
and values
keywords, which makes the maximum value of the colorbar effectively 1 greater than the maximum value of the data being plotted.
现在,我希望刻度线位于颜色栏中每个颜色范围的中间,但是无法为颜色栏中的最大颜色块指定刻度位置,这似乎是因为它超出了数据值限制.
Now I want ticks to be in the middle of each color range in the colorbar, but cannot specify a tick position for the largest color block in the colorbar, seemingly because it is outside of the data value limits.
以下是演示该问题的快速代码块:
Here's a quick block of code to demonstrate the problem:
data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
ax.imshow(data[None], aspect='auto')
cax = fig.add_subplot(122)
cbar = fig.colorbar(ax.images[0], cax=cax, boundaries=[0,1,2,3,4], values=[0,1,2,3])
cbar.set_ticks([.5, 1.5, 2.5, 3.5])
cbar.set_ticklabels(['one', 'two', 'three', 'four'])
请注意缺失的刻度线应位于四个"的位置.什么是正确的方法?
Note the missing tick where 'four' should be. What's the right way to do this?
推荐答案
总而言之,这对我有用:
To summarize, this works for me:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import colors
data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
cmap = cm.get_cmap('jet', 4)
bounds = np.arange(5)
vals = bounds[:-1]
norm = colors.BoundaryNorm(bounds, cmap.N)
ax.imshow(data[None], aspect='auto', interpolation='nearest', cmap=cmap, norm=norm)
cax = fig.add_subplot(122)
cbar = fig.colorbar(ax.images[0], cax=cax, boundaries=bounds, values=vals)
cbar.set_ticks(vals + .5)
cbar.set_ticklabels(['one', 'two', 'three', 'four'])
解决方案是使用 get_cmap
为图像显式指定颜色图,并以 BoundaryNorm
为边界.然后指定刻度位置就可以了.结果图为:
The solution was to specify the colormap explicitly for the image using get_cmap
and bounded by BoundaryNorm
. Then specifying the tick positions just works. The resulting plot is:
这篇关于使matplotlib颜色条在数据限制之外打勾以与boundary关键字一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!