【发布时间】:2013-09-13 07:16:48
【问题描述】:
我在等值线图旁边放置了一个颜色条。因为要绘制的数据是离散值而不是连续值,所以我使用了一个 LinearSegmentedColormap(使用the recipe from the scipy cookbook),我用我的最大计数值 + 1 对其进行了初始化,以显示 0 的颜色。但是,我现在有两个问题:
-
刻度标签的间距不正确(5 个或多或少除外)——它们应该位于它们所识别颜色的中间;即 0 - 4 应该上移,6 - 10 应该下移。
-
如果我用
drawedges=True初始化颜色条,以便我可以设置其dividers属性的样式,我会得到:
我正在像这样创建我的颜色图和颜色条:
cbmin, cbmax = min(counts), max(counts)
# this normalises the counts to a 0,1 interval
counts /= np.max(np.abs(counts), axis=0)
# density is a discrete number, so we have to use a discrete color ramp/bar
cm = cmap_discretize(plt.get_cmap('YlGnBu'), int(cbmax) + 1)
mappable = plt.cm.ScalarMappable(cmap=cm)
mappable.set_array(counts)
# set min and max values for the colour bar ticks
mappable.set_clim(cbmin, cbmax)
pc = PatchCollection(patches, match_original=True)
# impose our colour map onto the patch collection
pc.set_facecolor(cm(counts))
ax.add_collection(pc,)
cb = plt.colorbar(mappable, drawedges=True)
所以我想知道将计数转换为 0,1 间隔是否是问题之一。
更新:
尝试了 Hooked 的建议后,0 值是正确的,但后续值会逐渐设置得更高,达到 9 应该是 10 的点:
这是我使用的代码:
cb = plt.colorbar(mappable)
labels = np.arange(0, int(cbmax) + 1, 1)
loc = labels + .5
cb.set_ticks(loc)
cb.set_ticklabels(labels)
为了确认,labels 肯定有正确的值:
In [3]: np.arange(0, int(cbmax) + 1, 1)
Out[3]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
【问题讨论】:
-
看来问题必须出在您基本上使用 PatchCollection“手动”创建的颜色条上。是否有任何理由不像您链接的 scipy 页面那样使用线性离散颜色图?
-
您的意思是创建颜色图,将 PatchCollection 作为
cmap参数传递,然后将pc.set_array传递给计数? -
不,我的意思是在页面上使用
cmap_discretizewiki.scipy.org/Cookbook/Matplotlib/ColormapTransformations 。这就是我生成不受奇怪位置影响的示例的方式。
标签: python matplotlib color-mapping