首页 > 解决方案 > 自定义分箱颜色条:无法设置刻度标签

问题描述

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

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 的刻度并不完全集中在颜色之间的分隔上.. ?

标签: pythonmatplotlibcolorbar

解决方案


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

对于 colorbars,而不是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()

结果图


推荐阅读