使用ggplot从数据帧绘制不规则的时间序列(多个)

时间:2017-05-25 19:54:13

标签: python pandas plot time-series python-ggplot

我有一个df结构如下:

   UnitNo        Time           Sensor
0   1.0   2016-07-20 18:34:44    19.0
1   1.0   2016-07-20 19:27:39    19.0
2   3.0   2016-07-20 20:45:39    17.0
3   3.0   2016-07-20 23:05:29    17.0
4   3.0   2016-07-21 01:23:30    11.0
5   2.0   2016-07-21 04:23:59    11.0
6   2.0   2016-07-21 17:33:29    2.0
7   2.0   2016-07-21 18:55:04    2.0

我想创建一个时间序列图,其中每个UnitNo都有自己的行(颜色),y轴值对应Sensor,x轴是Time 。我想在ggplot中执行此操作,但我无法确定如何有效地执行此操作。我已经查看过前面的例子,但它们都有规则的时间序列,即每个变量的观察在同一时间发生,这使得创建时间索引变得容易。我想我可以循环并将数据添加到plot(?)中,但我想知道是否有更高效/更优雅的前进方式。

2 个答案:

答案 0 :(得分:2)

我认为您需要pivotset_index以及unstackDataFrame.plot

df.pivot('Time', 'UnitNo','Sensor').plot()

或者:

df.set_index(['Time', 'UnitNo'])['Sensor'].unstack().plot()

graph

如果有些重复:

df = df.groupby(['Time', 'UnitNo'])['Sensor'].mean().unstack().plot()
df = df.pivot_table(index='Time', columns='UnitNo',values='Sensor', aggfunc='mean').plot()

答案 1 :(得分:2)

df.set_index('Time').groupby('UnitNo').Sensor.plot();

enter image description here

相关问题