【问题标题】:Correcting matplotlib colorbar ticks更正 matplotlib 颜色条刻度
【发布时间】:2013-09-13 07:16:48
【问题描述】:

我在等值线图旁边放置了一个颜色条。因为要绘制的数据是离散值而不是连续值,所以我使用了一个 LinearSegmentedColormap(使用the recipe from the scipy cookbook),我用我的最大计数值 + 1 对其进行了初始化,以显示 0 的颜色。但是,我现在有两个问题:

  1. 刻度标签的间距不正确(5 个或多或少除外)——它们应该位于它们所识别颜色的中间;即 0 - 4 应该上移,6 - 10 应该下移。

  2. 如果我用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_discretize wiki.scipy.org/Cookbook/Matplotlib/ColormapTransformations 。这就是我生成不受奇怪位置影响的示例的方式。

标签: python matplotlib color-mapping


【解决方案1】:

您遇到了一个错误。您有 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()

【讨论】:

    【解决方案2】:

    您可以手动控制位置和标签。我将从cmap_discretizethe page you linked 上生成的线性cmap 开始:

    import numpy as np
    import pylab as plt
    
    # The number of divisions of the cmap we have
    k = 10
    
    # Random test data
    A = np.random.random((10,10))*k
    c = cmap_discretize('jet', k)
    
    # First show without
    plt.subplot(121)
    plt.imshow(A,interpolation='nearest',cmap=c)
    plt.colorbar()
    
    # Now label properly
    plt.subplot(122)
    plt.imshow(A,interpolation='nearest',cmap=c)
    
    cb = plt.colorbar()
    labels = np.arange(0,k,1)
    loc    = labels + .5
    cb.set_ticks(loc)
    cb.set_ticklabels(labels)
    
    plt.show()
    

    【讨论】:

    • 嗯,它仍然不正确,但方式不同。见编辑。
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 2017-01-22
    • 2020-02-18
    • 1970-01-01
    • 2019-09-21
    • 2020-01-05
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多