【问题标题】:Custom binned colorbar: can't set tick labels自定义分箱颜色条:无法设置刻度标签
【发布时间】:2020-06-27 11:05:19
【问题描述】:

我正在尝试创建自己的分箱颜色条,但我无法设置自己的刻度标签,该标签保持不变。

plt.figure(figsize = (10, 1))

cmapor = plt.get_cmap('jet')
cmap = mcolors.ListedColormap([ i for i in cmapor(np.linspace(0, 1, 5))])
bounds = np.linspace(0, 1, 6)[:-1]
labels = ['0', '2.5', '5', '7.5', '10']
cb2 = mcolorbar.ColorbarBase(plt.gca(), cmap = cmap, orientation = 'horizontal', spacing='proportional', extendfrac='auto')
cb2.ax.set_xticks = bounds
cb2.ax.set_xticklabels = labels

plt.tight_layout()
plt.show()

给

我希望最后一个没有刻度标签,而其他的标签如labels 中所述。

还要注意,0.2 和 0.4 的刻度并不完全集中在颜色之间的分隔上.. ?

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:

    主要问题是在cb2.ax.set_xticks = bounds 中,set_xticks 是一个函数。通过执行等式赋值,您可以将该函数替换为一个数组。但是你真正想做的是调用这个函数,所以你需要cb2.ax.set_xticks(bounds)。 set_xticklabels 也是如此。

    对于颜色条,而不是 cb2.ax.set_xticks(bounds),最新版本的 matplotlib 更喜欢您调用 cb2.set_ticks(bounds)(尽管旧方法仍然有效)。同样,现在首选cb2.set_ticklabels(labels) 来设置标签。

    关于“0.2 和 0.4 的刻度不完全集中在分隔符上”:这似乎是一些舍入错误。省略spacing='proportional' 在这里会有所帮助。

    修改后的代码(包括导入库)如下所示:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors as mcolors
    from matplotlib import colorbar as mcolorbar
    
    plt.figure(figsize=(10, 1))
    
    cmapor = plt.get_cmap('jet')
    cmap = mcolors.ListedColormap([i for i in cmapor(np.linspace(0, 1, 5))])
    cb2 = mcolorbar.ColorbarBase(plt.gca(), cmap=cmap, orientation='horizontal', extendfrac='auto')
    bounds = np.linspace(0, 1, 6)[:-1]
    
    labels = ['0', '2.5', '5', '7.5', '10']
    cb2.set_ticks(bounds)
    cb2.set_ticklabels(labels)
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2020-02-18
      相关资源
      最近更新 更多