R中不同组的时间序列多重图

Raj*_*jan 3 plot r ggplot2

我有一个包含多个变量(大约50个)的大型数据框,第一列为as date,第二列为id

我的数据大致如下所示:

df <- data.frame(date = c("01-04-2001 00:00","01-04-2001 00:00","01-04-2001 00:00",
                      "01-05-2001 00:00","01-05-2001 00:00","01-05-2001 00:00",
                      "01-06-2001 00:00","01-06-2001 00:00","01-06-2001 00:00",
                      "01-07-2001 00:00","01-07-2001 00:00","01-07-2001 00:00"), 
             id = c(1,2,3,1,2,3,1,2,3,1,2,3), a = c(1,2,3,4,5,6,7,8,9,10,11,12), 
             b = c(2,2.5,3,3.2,4,4.6,5,5.6,8,8.9,10,10.6))
Run Code Online (Sandbox Code Playgroud)

我想要所有三个id的时间序列图分别在同一变量图中ab在不同图中。

我试过了,ggplot 但是没有用。请帮我

小智 5

你的意思是这样吗?

library(reshape)
library(lattice)

df2 <- melt(df, id.vars = c("date", "id"), measure.vars = c("a", "b"))

xyplot(value ~ date | variable, group = id, df2, t='l')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

附录

# The following is from a comment by jbaums. 
# It will create a single plot/file for each variable of df2
png('plots%02d.png')
xyplot(value ~ date | variable, group = id, df2, t='l', layout=c(1, 1), 
       scales=list(alternating=FALSE, tck=1:0))
dev.off()
Run Code Online (Sandbox Code Playgroud)

您还可以添加relation='free'scales以便为每个图分别计算y轴极限。