python - 使用 seaborn 的密度图

标签 python seaborn

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

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

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

sns.kdeplot(bike['hr'])

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

最佳答案

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

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

下面我将展示如何使用 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')  

distribution estimates

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

关于python - 使用 seaborn 的密度图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52952298/

相关文章:

python - TensorFlow 对象检测 API 奇怪的行为

python - 如何从没有索引的列中获取数据

python - Seaborn 中的 FacetGrid 数据标签

python - 时间序列的简单 tsplot

python - 更改 seaborn 面网格中的线条样式

python - 在体内创建变量时正确使用 tf.while_loop

python - 如何加速百万元素的 Python 嵌套循环

python - 使用 Python 中的聚类进行 ScatterPlot 着色和标记

python - 替换未知的先验组数 - 正则表达式 python

python - 异步定义和调用堆栈