python - 使用 seaborn 的密度图
问题描述
我正在尝试制作每小时需求的密度图: 数据
'hr' 表示不同的时间,'cnt' 表示需求。
我知道如何制作密度图,例如:
sns.kdeplot(bike['hr'])
但是,这仅在不同时间的需求未知时才有效。因此,我可以将每小时算作它的需求。现在我知道了每个小时的需求量,我如何制作这些数据的密度图?
解决方案
密度图旨在显示分布的估计值。为了制作显示每小时需求密度的图表,我们真的希望看到许多带有时间戳的 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 点。
推荐阅读
- android - 使用 Android 上的 Flutter 应用程序链接到 C++ 运行时
- vba - 每天自动将今天的 Outlook 约会导出到 Excel
- sql - 无法在 Postgres 上向新用户授予所有权限
- json - 如何正确地将 xml 数据从响应中提取到另一个请求 / POSTMAN
- angular - 名称为“eventGraphicAttachment”的表单控件没有值访问器
- jquery - 在 Jquery 中显示从 asIconPicker 的下拉列表中搜索到的图标中选择了一个值
- c++ - 将 C++ 代码转换为 x87 内联汇编代码
- python - PyMC3 小批量 ADVI
- twitter-bootstrap - Vue 从 API 获取数据
- java - 从 Realm 查询返回对象会引发实例关闭状态异常