我在彩色 map 旁边放置了一个颜色栏。因为要绘制的数据是离散的而不是连续的值,所以我使用了LinearSegmentedColormap(使用the recipe from the scipy cookbook),并使用最大计数值+ 1对其进行了初始化,以显示0的颜色。但是,现在有了两个问题:
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])
最佳答案
您正在遭受一个一对一的错误。您有10个刻度标签分布在11种颜色中。您可以使用np.linspace
而不是np.arange
来纠正错误。使用np.linspace
,第三个参数是所需值的数量。这减少了避免一次失误所需要的精神体操的数量:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.colors as mcolors
def colorbar_index(ncolors, cmap):
cmap = cmap_discretize(cmap, ncolors)
mappable = cm.ScalarMappable(cmap=cmap)
mappable.set_array([])
mappable.set_clim(-0.5, ncolors+0.5)
colorbar = plt.colorbar(mappable)
colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
colorbar.set_ticklabels(range(ncolors))
def cmap_discretize(cmap, N):
"""Return a discrete colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: number of colors.
Example
x = resize(arange(100), (5,100))
djet = cmap_discretize(cm.jet, 5)
imshow(x, cmap=djet)
"""
if type(cmap) == str:
cmap = plt.get_cmap(cmap)
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N+1)
cdict = {}
for ki,key in enumerate(('red','green','blue')):
cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
for i in xrange(N+1) ]
# Return colormap object.
return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
fig, ax = plt.subplots()
A = np.random.random((10,10))*10
cmap = plt.get_cmap('YlGnBu')
ax.imshow(A, interpolation='nearest', cmap=cmap)
colorbar_index(ncolors=11, cmap=cmap)
plt.show()
关于python - 校正Matplotlib色条刻度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18704353/