Python 使用seaborn的密度图
我试着画出每小时需求的密度图: “hr”表示不同的时间,“cnt”表示需求 我知道如何绘制密度图,例如:Python 使用seaborn的密度图,python,seaborn,Python,Seaborn,我试着画出每小时需求的密度图: “hr”表示不同的时间,“cnt”表示需求 我知道如何绘制密度图,例如: sns.kdeplot(bike['hr']) 但是,这仅在不同时间的需求未知时有效。因此,我可以把每一小时都算作它的需求。现在我知道了每小时的需求量,我如何才能对这些数据绘制密度图?密度图旨在显示对分布的估计。为了绘制一张显示每小时需求密度的图表,我们确实希望看到许多iid需求样本,带有时间戳,即每个样本一行。那么密度图就有意义了 但在这里的数据类型中,需求(“cnt”)定期采样并在该
sns.kdeplot(bike['hr'])
但是,这仅在不同时间的需求未知时有效。因此,我可以把每一小时都算作它的需求。现在我知道了每小时的需求量,我如何才能对这些数据绘制密度图?密度图旨在显示对分布的估计。为了绘制一张显示每小时需求密度的图表,我们确实希望看到许多iid需求样本,带有时间戳,即每个样本一行。那么密度图就有意义了 但在这里的数据类型中,需求(“cnt”)定期采样并在该采样周期(小时)内聚合,密度图没有直接意义。但柱状图作为柱状图是有意义的,它以小时为单位 下面我将展示如何使用pandas函数生成这样一个图——非常简单。作为参考,我还展示了如何通过重建“原始”样本来生成密度图
夜间对自行车的需求似乎很低。。。但也很明显,它们可能用于通勤,高峰时间为上午8点和下午5-6点。非常感谢!
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')