使用Seaborn的密度图

Pei Li

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

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

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

sns.kdeplot(bike['hr'])

但是,这仅在未知不同小时的需求时有效。因此,我可以将每小时作为其需求。现在我知道了每小时的需求量,如何绘制此类数据的密度图?

Bonlenfum

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

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

下面我展示了如何使用熊猫函数生成这样的图-真的很简单。作为参考,我还展示了如何通过某种“原始”样本的重构来产生密度图。

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点。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章