自定义分格颜色栏:无法设置勾号标签

2024-09-30 00:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建自己的装箱颜色栏,但我无法设置自己的勾号标签,这些标签保持不变

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()

给出enter image description here

我希望最后一个标签上没有勾号标签,其他的标签如labels中所述

还要注意的是,0.2和0.4的刻度并非完全集中在颜色之间的间隔上


Tags: labels颜色npplt标签axcmapfigure
1条回答
网友
1楼 · 发布于 2024-09-30 00:26:23

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

对于颜色条,最新版本的matplotlib不使用cb2.ax.set_xticks(bounds),而是更喜欢调用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()

resulting plot

相关问题 更多 >

    热门问题