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()
我想在最后一个上没有刻度标签,而其他标签上的标签如labels
.
另请注意,0.2 和 0.4 的刻度并不完全集中在颜色之间的分隔上.. ?
解决方案
主要问题是 incb2.ax.set_xticks = bounds
是set_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()
推荐阅读
- python - Pygame 帧循环
- javascript - NodeJS 请求,等待 java-script 注入内容
- python - 将列表与索引一起加入
- php - 将 php 文件中的内容写入另一个生成的文件
- java - 使用 Selenium java 长时间运行 webdriver 时内存增加
- android - 导航抽屉内项目的字体大小没有改变
- python - SVM 分类任务中 word2vec 特征的输入格式是什么?
- c# - 客户立柱显示文本水平滚动连续C#
- javascript - 用 javascript 创建一个表
- firebase - 如何在云功能中了解 Firebase 身份验证的提供者