簡體   English   中英

帶有自定義圖例的 Seaborn 熱圖

[英]Seaborn heatmap with a custom legend

我有一個大型數據集,我將針對這個問題對其進行簡化。 我希望根據列值制作自定義圖例。 讓我用一個例子來解釋。

   df2 = DataFrame(np.array([[1.0, 2.0, 3.0, 'sensitve'], [4.0, 5.0, 6.0, 'sensitive'], [7.0, 8.0, 9.0, 'not sensitive']]),
                   columns=['a', 'b', 'c', 'd'], index = ['A', 'B', 'C'])

我希望制作一個熱圖並在頂部有一個圖例,以查看行是否敏感。

首先,我對值進行了排序

df2 = df2.sort_values('d')

並刪除了最后一列,因為它不是數字並且不能處於熱 map 中。

df2 = df2.iloc[:, :-1].astype(float).T

在我用 sns 創建熱圖后:

sns.heatmap(df2, yticklabels = False)#, cmap="viridis")

如何在哪些列是敏感的或不敏感的列的頂部制作符號? 像這樣的東西?

在此處輸入圖像描述

您可以 plot 在熱圖上方的子圖中包含這些值的表格。

df2 = pd.DataFrame(np.array([[1.0, 2.0, 3.0, 'sensitve'], [4.0, 5.0, 6.0, 'sensitive'], [7.0, 8.0, 9.0, 'not sensitive']]),
               columns=['a', 'b', 'c', 'd'], index = ['A', 'B', 'C'])
df2 = df2.sort_values('d')

d_col = df2['d'].T
df2 = df2.iloc[:, :-1].astype(float).T

# set subplot height ratios to avoid large empty space above the table
fig, (ax_table,ax_heatmap) = plt.subplots(2,1, figsize = [8,8], gridspec_kw = {'height_ratios':[1,9]})
sns.heatmap(df2, linewidth = 1, ax = ax_heatmap)
# only using 2 unique d_col values and setting colWidths to fit your drawing
ax_table.table([d_col.unique()], colWidths = [1/3,2/3], cellLoc = 'center')
ax_table.axis('off')

# setting table size to fit heatmap following https://stackoverflow.com/questions/66825885/centering-a-table-with-a-heatmap
bbox_heatmap = ax_heatmap.get_position()
bbox_table = ax_table.get_position()    
left = bbox_heatmap.x0
bottom = bbox_table.y0
width = bbox_heatmap.x0 + (bbox_heatmap.width * 0.8)
height = bbox_table.height * 1.2    
ax_table.set_position([left, bottom, width, height])

plt.show()

哪個輸出:

在此處輸入圖像描述

查看表格文檔以進行進一步調整。

暫無
暫無

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

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