簡體   English   中英

在seaborn中自定義顏色條 - 熱圖

[英]Customizing color bar in seaborn - heatmap

我有一個熱圖來表示離散值。

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'}

它遵循您給出的命令。 由於您的代碼有

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

顏色映射到這些類別。 將順序更改為,例如, ['red','black', 'blue','yellow']標簽將相應更改。

默認情況下,顏色圖會縮放到您的數據范圍。 在您的情況下,您的數據是 [1-3],因此 matplotlib 將您的四色顏色圖縮放到該范圍。

由於您實際上想要將顏色圖縮放到范圍 [1-4],您必須使用參數vmin=vmax=來告訴系統要使用的數據范圍。

ax = sns.heatmap(dataFrame, cmap=cmap, linewidths=.5, linecolor='lightgray', vmin=1, vmax=4)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM