首页 > 解决方案 > Pandas 绘制合并/覆盖多个数据帧的图形

问题描述

我有多个数据框,其中包含大约 2 周的日期和事件窗口,如下所示:

date, name, event
2020-01-07 19:43:56  johnnyB 82
2020-01-07 19:14:01  johnnyB 181
2020-01-07 19:12:55  johnnyB 11
2020-01-08 19:12:29  johnnyB 10
2020-01-09 17:59:37  johnnyB 12
2020-01-16 16:40:04  johnnyB 10
2020-01-15 15:32:23  johnnyB 9
2020-01-15 15:23:50  johnnyB 7
2020-01-19 15:12:37  johnnyB 8
2020-01-21 12:18:07  johnnyB 1


date, name, event
2020-02-14 19:43:56  matthew 82
2020-02-23 19:14:01  matthew 132
2020-02-22 19:12:55  matthew 173
2020-02-21 19:12:29  matthew 137
2020-02-17 17:59:37  matthew 13
2020-02-28 16:40:04  matthew 173
2020-02-23 15:32:23  matthew 23
2020-02-28 15:23:50  matthew 39
2020-02-26 15:12:37  matthew 9
2020-02-24 12:18:07  matthew 72

我知道对于每个单独的 df,我可以找到数据框的第一个日期或起点,如下所示:

start = df.index.min()

在绘制单个 df 时,我使用基于天的 timedelta 来绘制 16 天的时间段。

如何根据 16 天期间的日期将多个 df 合并到可以绘制的位置,类似于覆盖?

另外,我认为条形图不适用于覆盖样式视图。哪种替代类型的图表可以更好地显示像这样的大量数据帧的叠加?

目前我正在绘制单个数据框,如下所示:

# Set start point of df + 16 days 
start = df.index.min()
end = start + pd.Timedelta(days=16)
mask = (df.index > start) & (df.index <= end)
df = df.loc[mask]
# resample based on the day with the events column 
daily = df.resample('D', level=0)['events'].count()

# Plotting 
plt.style.use('ggplot')
fig, ax = plt.subplots()
fig.autofmt_xdate()
ax.bar(daily.index.strftime("%d-%b"), daily)
plt.grid(True)
plt.tight_layout()
plt.show()

标签: pythonpython-3.xpandasmatplotlib

解决方案


推荐阅读