簡體   English   中英

使用 matplotlib 或 seaborn 繪制熱圖?

[英]Heatmap drawing using matplotlib or seaborn?

我是 Python 的新手。 我需要使用如下數據框在每個網格中繪制帶有注釋的熱圖:

t=pd.DataFrame({'ReturnType':['ReturnWithoutReceipt','Return With Receipt',
                          'ReturnWithoutReceipt','Return With Proof Of Purchase','Return With Proof Of Purchase',
                'Return With Receipt'],
                'Payment':['Card','Cash','Cash','Cash','Card','Card'],
                'Hour':[11,12,12,14,16,16],
                'value':[1,26,3,67,17,37],
                'Label':['1.0--11','26.0--12','3.0--12','67.0--14','17.0--16','37.0--16']})

在我的熱圖中,行是 ReturnType,列是 Payment。 顏色是由價值決定的。 標簽需要顯示在每個網格中。 因此,該圖將如下所示:

在此處輸入圖片說明

那么如何使用 matplotlib 或 seaborn 來實現呢?

首先重塑DataFrameset_indexunstack

df = t.set_index(['ReturnType','Payment']).unstack()
print (df)
                              Hour      value          Label          
Payment                       Card Cash  Card Cash      Card      Cash
ReturnType                                                            
Return With Proof Of Purchase   16   14    17   67  17.0--16  67.0--14
Return With Receipt             16   12    37   26  37.0--16  26.0--12
ReturnWithoutReceipt            11   12     1    3   1.0--11   3.0--12

xs選擇每個DataFrame (因為列中有MultiIndex

df1 = df.xs('value', axis=1, level=0)
lab = df.xs('Label', axis=1, level=0)
print (df1)
Payment                        Card  Cash
ReturnType                               
Return With Proof Of Purchase    17    67
Return With Receipt              37    26
ReturnWithoutReceipt              1     3

print (lab)
Payment                            Card      Cash
ReturnType                                       
Return With Proof Of Purchase  17.0--16  67.0--14
Return With Receipt            37.0--16  26.0--12
ReturnWithoutReceipt            1.0--11   3.0--12

最后將第二個DataFrame傳遞給參數annot ,顯示標簽的想法來自這個答案

ax = sns.heatmap(df1, annot=lab, fmt="")

熱圖

我認為您誤解了熱圖是什么。 熱圖是 M 行 N 列的矩形陣列,其中某個索引 (m, n) 的計數表示為顏色。

根據您的問題, 'value:'的形狀不等於'ReturnType:'Payment:'的乘積。

暫無
暫無

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

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