首页 > 解决方案 > 使用 seaborn 的密度图

问题描述

我正在尝试制作每小时需求的密度图: 数据

'hr' 表示不同的时间,'cnt' 表示需求。

我知道如何制作密度图,例如:

sns.kdeplot(bike['hr'])

但是,这仅在不同时间的需求未知时才有效。因此,我可以将每小时算作它的需求。现在我知道了每个小时的需求量,我如何制作这些数据的密度图?

标签: pythonseaborn

解决方案


密度图旨在显示分布的估计值。为了制作显示每小时需求密度的图表,我们真的希望看到许多带有时间戳的 iid 需求样本,即每个样本一行。那么密度图就有意义了。

但是在此处的数据类型中,需求('cnt')定期采样并在该采样周期(小时)内汇总,密度图没有直接意义。但是作为直方图的条形图确实有意义,使用小时作为箱。

下面我将展示如何使用 pandas 函数来生成这样的图——非常简单。作为参考,我还展示了我们如何通过“原始”样本的一种重建来生成密度图。

df = pd.read_csv("../data/hour.csv") # load dataset, inc cols hr, cnt, no NaNs

# using the bar plotter built in to pandas objects
fig, ax = plt.subplots(1,2)
df.groupby('hr').agg({'cnt':sum}).plot.bar(ax=ax[0]) 

# reconstructed samples - has df.cnt.sum() rows, each one containing an hour of a rental.
samples = np.hstack([ np.repeat(h, df.cnt.iloc[i]) for i, h in enumerate(df.hr)])

# plot a density estimate
sns.kdeplot(samples, bw=0.5, lw=3, c="r", ax=ax[1])
    
# to make a useful comparison with a density estimate, we need to have our bar areas 
# sum up to 1, so we use groupby.apply to divide by the total of all counts.
tot = float(df.cnt.sum())
df.groupby('hr').apply(lambda x: x['cnt'].sum()/tot).plot.bar(ax=ax[1], color='C0')  

分布估计

夜间对自行车的需求似乎很低......但也很明显,它们可能用于通勤,高峰时间为上午 8 点和下午 5 点至下午 6 点。


推荐阅读