如何使用MatPlotLib将Pandas中的Binned计数显示为热图?

2024-04-19 07:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

产生:

^{pr2}$

Tags: 数据bymatplotlib数字效应pricepoints计数
1条回答
网友
1楼 · 发布于 2024-04-19 07:17:24

可以使用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更轻松地获取带注释的热图:

^{pr2}$

Seaborn heat map

Seaborn在自动格式化文本底纹方面做得很好,这样它在不断变化的背景颜色下是可见的。在

相关问题 更多 >