【问题标题】:how to group pandas timestamps plot several plots in one figure and stack them together in matplotlib?如何将熊猫时间戳分组在一个图中绘制多个图并将它们堆叠在matplotlib中?
【发布时间】:2017-09-17 21:21:19
【问题描述】:

我有一个带有完美组织的时间戳的数据框,如下所示:

这是一个网络日志,时间戳贯穿全年。我想将它们分成每一天,并显示每个小时内的访问量,并将它们绘制成同一个图形并将它们全部堆叠在一起。就像下图所示:

我在将它们分成几天并单独绘制一天的访问方面做得很好,但是我在绘制它们并将它们堆叠在一起时遇到了麻烦。我使用的主要工具是 Pandas 和 Matplotlib

有什么意见和建议吗?非常感谢!


已编辑:

我的代码如下:

时间戳为:https://gist.github.com/adamleo/04e4147cc6614820466f7bc05e088ac5

数据框如下所示:

我使用下面的代码绘制了整个时期的时间戳密度:

timestamps_series_all = pd.DatetimeIndex(pd.Series(unique_visitors_df.time_stamp))
timestamps_series_all_toBePlotted = pd.Series(1, index=timestamps_series_all)
timestamps_series_all_toBePlotted.resample('D').sum().plot()

得到了结果:

我使用代码绘制了一天内的时间戳:

timestamps_series_oneDay = pd.DatetimeIndex(pd.Series(unique_visitors_df.time_stamp.loc[unique_visitors_df["date"] == "2014-08-01"]))
timestamps_series_oneDay_toBePlotted = pd.Series(1, index=timestamps_series_oneDay)
timestamps_series_oneDay_toBePlotted.resample('H').sum().plot()

结果:

现在我被卡住了。

非常感谢您的帮助!

【问题讨论】:

  • 你考虑过分享你的一些代码吗?
  • @StephenRauch 嘿伙计,我刚刚更新了帖子。请看一看。谢谢。

标签: pandas matplotlib machine-learning data-visualization data-analysis


【解决方案1】:

我觉得你需要pivot:

#https://gist.github.com/adamleo/04e4147cc6614820466f7bc05e088ac5 to L
df = pd.DataFrame({'date':L})
print (df.head())
                  date
0  2014-08-01 00:05:46
1  2014-08-01 00:14:47
2  2014-08-01 00:16:05
3  2014-08-01 00:20:46
4  2014-08-01 00:23:22

#convert to datetime if necessary
df['date']  = pd.to_datetime(df['date'] )
#resample by Hours, get count and create df
df = df.resample('H', on='date').size().to_frame('count')
#extract date and hour
df['days'] = df.index.date
df['hours'] = df.index.hour
#pivot and plot
#maybe check parameter kind='density' from http://stackoverflow.com/a/33474410/2901002
#df.pivot(index='days', columns='hours', values='count').plot(rot='90')
#edit: last line change to below:
df.pivot(index='hours', columns='days', values='count').plot(rot='90')

【讨论】:

  • 非常感谢你的朋友,这个答案真的很有帮助。但是最后一行有点扭曲,所以我改为df.pivot(index='hours', columns='days', values='count').plot(rot='90'),它运行良好。赞赏!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 2019-10-31
  • 2022-10-08
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多