首页 > 解决方案 > 如何创建一个直方图,其中每个条形图都是相应 bin 的热图?

问题描述

我有一个数据框:

df.head()[['price', 'volumen']]

    price   volumen
48  45      3
49  48      1
50  100     2
51  45      1
52  56      1

它表示具有特定价格的对象的数量。我根据volume列创建了一个直方图:

在此处输入图像描述

我想添加有关每个箱的价格分布的信息。我的想法是使用热图而不是单色列。例如,红色代表高价,黄色代表低价。

这是一个示例图来说明总体思路:

在此处输入图像描述

标签: pythonpandasmatplotlibseaborn

解决方案


您可以使用 Seaborn 生成热图。bin / 首先塑造数据框。这是随机数据,所以热图不是那么有趣。

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

s = 50
df = pd.DataFrame({"price":np.random.randint(30,120, s),"volume":np.random.randint(1,5, s)})

fig, ax = plt.subplots(2, figsize=[10,6])

df.loc[:,"volume"].plot(ax=ax[0], kind="hist", bins=3)
# reshape for a heatmap... put price into bins and make 2D
dfh = df.assign(pbin=pd.qcut(df.price,5)).groupby(["pbin","volume"]).mean().unstack(1).droplevel(0,axis=1)
axh = sns.heatmap(dfh, ax=ax[1])

在此处输入图像描述


推荐阅读