python - 在 seaborn 中自定义颜色条 - 热图
问题描述
我有一个热图来表示离散值。
import seaborn as sns
import pandas as pd
data = np.array([[2, 1, 1, 1, 2, 3, 3, 3, 3, 3],
[3, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],])
x_labels = ['a', 'b', 'c', 'd']
dataFrame = pd.DataFrame(data.T)
#get discrete colormap
cmap = colors.ListedColormap(['blue','red','black','yellow'])
ax = sns.heatmap(dataFrame, cmap=cmap, linewidths=.5, linecolor='lightgray')
ax.set_xticklabels(x_labels)
ax.set_yticklabels(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
# Manually specify colorbar labelling after it's been generated
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([1.3, 1.7, 2.2, 2.7])
colorbar.set_ticklabels(['A', 'B', 'C', 'NA'])
plt.show()
如何指定这些颜色以表示颜色 = {1: 'A', 2: 'B', 3: 'C', 4: 'NA'} in data
解决方案
它遵循您给出的命令。由于您的代码有
cmap = ListedColormap(['red','black','yellow', 'blue'])
colorbar.set_ticklabels(['A', 'B', 'C', 'NA'])
颜色映射到这些类别。例如,将顺序更改为,['red','black', 'blue','yellow']
标签将相应更改。
推荐阅读
- python - 使用 openpyxl 查找包含具有特定值的单元格的行
- c++ - 为什么 FlowMonitor 不为 ns3 中的 dsr.cc 收集数据?
- html -
用set引用当前目录 - java - 为什么我不能在 Android 项目上更改用户图像
- django - 如何在 Django Rest 中从不相关的表中添加额外的数据?
- qt - 启动基于 Qt Qml 的应用程序
- c# - 带返回值的生产者消费者模式
- java - 使用 antlr4 进行条件解析 - 跳过输入
- styled-components - styled-components:基于其他样式的动态css属性(margin基于font-size)
- javascript - 在客户端 JavaScript 上编码数据并在服务器端 PHP 上解码