如何使用MatPlotLib在大熊猫中将装箱计数显示为热图?

时间:2019-03-14 19:08:43

标签: python pandas matplotlib

我正在处理葡萄酒数据集,并注意到当查看计数时,较大的数字会显得更暗,并产生某种热图效果。我想知道是否有一种方法可以使用MatPlotLib来增强效果。

BINS = [0, 50, 100, 150, 200, 1000]
price_by_points = first150.groupby(['points', pd.cut(first150['price'], BINS)]).size().unstack('price').fillna(0)

产生:

price   (0, 50]  (50, 100]  (100, 150]  (150, 200]  (200, 1000]
points                                                         
80        871.0       12.0         0.0         0.0          0.0
81       1444.0       23.0         0.0         0.0          2.0
82       3874.0       55.0         4.0         0.0          0.0
83       5717.0       84.0         3.0         1.0          2.0
84       9861.0      238.0        15.0         4.0          2.0
85      11313.0      262.0        21.0         7.0          1.0
86      13874.0      447.0        26.0         1.0          3.0
87      18097.0      857.0        55.0        12.0          4.0
88      14811.0     1122.0        91.0         7.0          3.0
89      10194.0     1238.0        97.0        13.0         15.0
90      11909.0     2244.0       180.0        45.0         26.0
91       6810.0     2148.0       209.0        28.0         15.0
92       5135.0     2575.0       287.0        74.0         48.0
93       2432.0     2162.0       399.0        98.0        106.0
94       1067.0     1361.0       338.0       100.0        140.0
95        322.0      696.0       205.0        81.0        162.0
96         77.0      262.0       100.0        48.0         78.0
97          9.0      117.0        59.0        29.0         88.0
98          1.0       36.0        29.0        10.0         37.0
99          0.0        8.0         5.0         5.0         21.0
100         0.0        5.0         0.0         4.0         12.0

1 个答案:

答案 0 :(得分:0)

您可以使用Matplotlib生成热图并对其进行注释:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
heatmap = plt.pcolor(df, cmap='viridis')

# Add text
for y in range(df.shape[0]):
    for x in range(df.shape[1]):
        plt.text(x + 0.5, y + 0.5, '{:.0f}'.format(df.iloc[y, x]),
                 color='w',horizontalalignment='center',
                 verticalalignment='center',)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.colorbar(heatmap)
plt.ylabel('points')
plt.xlabel('price')

Matplotlib heat map

您还可以使用seaborn来更轻松地获取带注释的热图:

import seaborn as sns

plt.figure()
sns.heatmap(df, annot=True, fmt='d')
plt.xlabel('Price')

Seaborn heat map

Seaborn在自动设置文本底纹的格式方面做得很好,因此可以通过不断变化的背景颜色看到它。

相关问题