python - python中的两种颜色热图

标签 python heatmap

我有以下数据:

my_array = array([[0, 0, 1, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 1, 0, 1, 0]])

df.values = array([246360,  76663,  29045,  11712,   5526,   3930,   3754,   1677,
         1328])

我正在制作这样的热图:

import seaborn as sns
import matplotlib.pyplot as plt
cmap = sns.cm.rocket_r
ax = sns.heatmap(my_array, xticklabels=["A", "B", "C", "D", "E"], yticklabels=df.values, cmap = cmap)
ax.set(xlabel='Test Type', ylabel='Number', title='patterns of missingness')
fig=plt.figure(figsize=(40,30), dpi= 20, facecolor='w', edgecolor='k')
fig

我得到以下信息: enter image description here

我的问题是,如何摆脱连续的色标并只选择两种不同的颜色:0 为白色,1 为绿色?

最佳答案

您可以使用 LinearSegmentedColormap 而不是您正在使用的当前 cmap 来执行此操作。

import matplotlib as mpl
cmap = mpl.colors.LinearSegmentedColormap.from_list('my_cmap', ['white', 'green'], 2)

然后在调用 sns.heatmap 时将 ticks 参数传递给 cbar_kws 参数:

ax = sns.heatmap(my_array, xticklabels=["A", "B", "C", "D", "E"],
                 yticklabels=df.values, cmap=cmap, cbar_kws={"ticks":[0,1]})

给出:

enter image description here

如果很清楚绿色和白色代表什么,您也可以使用 cbar=False 完全关闭 cbar。

ax = sns.heatmap(my_array, xticklabels=["A", "B", "C", "D", "E"],
             yticklabels=df.values, cmap=cmap, cbar=False)

enter image description here

关于python - python中的两种颜色热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74823966/

相关文章:

python OSM xml立交桥

Python 没有创建一个新的干净实例?

python - 定期勾选标签

r - 如何修复 R heatmaply() 中的 "Factor level duplicated"错误?

android - 使用 phonegap 获取应用程序的热图分析数据

python - 并行处理两个 CSV 文件

python - 无法将大小为 47040000 的数组 reshape 为预训练神经网络的形状 (60000,32,32,1)

r - 带有 pheatmap 的多面板图

python - 如何找到 : urllib2. URLError : <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl. c :590)? 的根本原因

r - 如何在 R 中创建一个简单的热图