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

时间:2015-02-27 06:03:36

标签: r plot ggplot2

我有一个包含多个变量(大约50个)的大型数据框,第一列为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))

我想在不同图表中的变量ab的相同图表中分别为所有三个ID分别绘制时间序列图。

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

3 个答案:

答案 0 :(得分: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')

enter image description here

<强>附录

# 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()

您还可以将relation='free'添加到scales,以便为每个地图单独计算y轴限制。

答案 1 :(得分:1)

以下是如何在ggplot中执行此操作,使用tidyr包以正确的格式获取它:

library(ggplot2)
library(tidyr)
library(dplyr)

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))

然后使用dplyr的group_by和do函数,我们可以保存多个图。

df %>%
  gather(variable, value, -date, -id) %>%
  mutate(id = factor(id)) %>%
  group_by(variable) %>%
  do(
    qplot(data = ., x = date, y = value, geom = "line", group = id, color = id, main = paste("variable =", .$variable)) +
          ggsave(filename = paste0(.$variable, ".png")
             )
    ) 

答案 2 :(得分:1)

修改:阅读完评论后,您可能会尝试这样的事情:

library(tidyr)
df2 <- gather(df, variable, value, -date, -id)
vars <- unique(df2$variable)

library(ggplot2)
for (i in 1:length(vars)) {
  ggplot() + 
    geom_line(data = subset(df2, variable == vars[[i]]), 
              aes(date, value, group = id, color = factor(id))) +
    ylab(as.character(vars[[i]])) +
    ggsave(file = paste0(vars[[i]], ".png"))
}

这应该为数据框中的每个变量保存一个PNG(并且根据您的请求将每个图的y标签更改为变量名