每个时间序列的多个图表

时间:2018-02-19 16:52:31

标签: r plot time-series

我有以下数据框,每个用户有288个观察结果:

                          User5   User8   User10
   2015-01-01 00:00:00    12.3    10.3     17.5
   2015-01-01 00:30:00    20.1    12.7     20.9
   2015-01-01 01:00:00    12.8     9.2     17.8
   2015-01-01 01:30:00    11.5     6.9     12.5
   2015-01-01 02:00:00    12.2     9.2      7.5
   2015-01-01 02:30:00    9.2     14.2      9.0
   ....................   ....    ....     ....
   2015-01-01 23:30:00    11.2    10.7     16.8

如何制作包含每个时间序列的多个图表的图表?

2 个答案:

答案 0 :(得分:0)

假设最后Note中的数据框DF将其读入动物园对象然后绘图。假设“多个图形”表示每个用户一个面板,可以使用以下3个选项中的任何一个。如果“多个图形”表示一个面板中有三行,每个用户一个,则将screen = 1参数添加到前两个,facet = NULL添加到第三个。

library(zoo)
z <- read.zoo(DF, tz = "")

# 1
plot(z)

# 2
library(lattice)
xyplot(z)

# 3
library(ggplot2)
autoplot(z)

注意

Lines <- "
Time,User5,User8,User10
2015-01-01 00:00:00,12.3,10.3,17.5
2015-01-01 00:30:00,20.1,12.7,20.9
2015-01-01 01:00:00,12.8,9.2,17.8
2015-01-01 01:30:00,11.5,6.9,12.5
2015-01-01 02:00:00,12.2,9.2,7.5
2015-01-01 02:30:00,9.2,14.2,9
2015-01-01 23:30:00,11.2,10.7,16.8"
DF <- read.csv(text = Lines)

答案 1 :(得分:0)

另一种选择是从宽格式转换为长格式,然后在同一图表中绘制所有内容。以下是使用@G发布的DF的代码。格罗滕迪克

library(tidyverse)
library(scales)

# Convert Time from factor to Date/Time 
DF$Time <- as.POSIXct(DF$Time)

# Convert from wide to long format (`tidyr::gather`)
df_long <- DF %>% gather(key = "user", value = "value", -Time)

# Plot all together, color based on User
# We use pretty_breaks() from scales package for automatic Date/Time labeling
ggplot(df_long, aes(Time, value, group = user, color = user)) +
  geom_line() +
  scale_x_datetime(breaks = pretty_breaks()) +
  theme_bw()

enter image description here

编辑:要在单独的面板中绘制每个用户,请使用facet_grid

ggplot(df_long, aes(Time, value, group = user, color = user)) +
  geom_line() +
  scale_x_datetime(breaks = pretty_breaks()) +
  theme_bw() +
  facet_grid(user ~ .)

enter image description here