首页 > 解决方案 > 在 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

标签: pythonpandasdataframeseabornheatmap

解决方案


它遵循您给出的命令。由于您的代码有

cmap = ListedColormap(['red','black','yellow', 'blue'])
colorbar.set_ticklabels(['A', 'B', 'C', 'NA'])

颜色映射到这些类别。例如,将顺序更改为,['red','black', 'blue','yellow']标签将相应更改。


推荐阅读