使用ggplot从数据框中绘制不规则时间序列(多个)
Plotting irregular time-series (multiple) from dataframe using 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(?),但我想知道是否还有 efficient/elegant 前进的方向。
我觉得你需要pivot
or set_index
and unstack
with DataFrame.plot
:
df.pivot('Time', 'UnitNo','Sensor').plot()
或者:
df.set_index(['Time', 'UnitNo'])['Sensor'].unstack().plot()
如果有些重复:
df = df.groupby(['Time', 'UnitNo'])['Sensor'].mean().unstack().plot()
df = df.pivot_table(index='Time', columns='UnitNo',values='Sensor', aggfunc='mean').plot()
df.set_index('Time').groupby('UnitNo').Sensor.plot();
我有一个 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(?),但我想知道是否还有 efficient/elegant 前进的方向。
我觉得你需要pivot
or set_index
and unstack
with DataFrame.plot
:
df.pivot('Time', 'UnitNo','Sensor').plot()
或者:
df.set_index(['Time', 'UnitNo'])['Sensor'].unstack().plot()
如果有些重复:
df = df.groupby(['Time', 'UnitNo'])['Sensor'].mean().unstack().plot()
df = df.pivot_table(index='Time', columns='UnitNo',values='Sensor', aggfunc='mean').plot()
df.set_index('Time').groupby('UnitNo').Sensor.plot();