【问题标题】:Density plot using seaborn使用 seaborn 的密度图
【发布时间】:2018-10-23 15:04:55
【问题描述】:

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

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

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

sns.kdeplot(bike['hr'])

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

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    密度图旨在显示分布的估计值。为了制作显示每小时需求密度的图表,我们真的希望看到许多带有时间戳的 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 点。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2020-08-17
    • 2015-12-01
    • 1970-01-01
    • 2020-11-22
    • 2019-09-14
    相关资源
    最近更新 更多