使用matplotlib或seaborn绘制热图?

时间:2018-06-14 05:39:58

标签: python pandas matplotlib heatmap 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。颜色由值决定。标签需要在每个网格中显示。所以,这个数字看起来像这样:

enter image description here

那么如何使用matplotlib或seaborn呢?谢谢。请提供您的所有代码,以便我了解所有细节。

2 个答案:

答案 0 :(得分:1)

首先set_indexunstack重新塑造DataFrame

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,展示标签的提示来自this answer

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

heatmap

答案 1 :(得分:0)

我认为你误解了热图是什么。热图是M行乘N列的矩形数组,其中某些索引(m,n)处的计数表示为颜色。

根据您的问题,'value:'的形状不等于'ReturnType:'Payment:'的乘积。