for循环中的stat_function和grid.arrange

时间:2016-08-09 13:39:55

标签: r printing ggplot2

我正在尝试使用ggplot2使用stat_function包绘制多个函数。因为我有几个参数选项,我用于循环。我将我的图保存到列表变量myplot中。当我尝试打印它们时会出现问题。使用print一切似乎都可以,但是当我只使用选项时,例如myplot[[1]]这些行与myplot[[2]]等相同,但是正确绘制了点。当我尝试使用函数grid.arrange绘制所有图形时,可以观察到同样的问题。

参见我的例子:

library("ggplot2")
myfun <- function(x, group, a, b, e){
  a * x + b + group * e
}
abe <- rbind(c(1, 2, 3), c(7, 0, -4), c(-1, -5, 8))
myplot <- list()
for (i in 1:3){
  x1 <- rnorm(10, 0, 1)
  x2 <- rnorm(10, 1, 1)
  num <- runif(20, -10, 10)
  df <- cbind(rbind(data.frame(x = x1, group = "group 1"), 
                    data.frame(x = x1, group = "group 2")), 
              num) 
  myplot[[i]] <-  ggplot(df, aes_string("x", "num")) +
                  geom_point(aes_string(colour = "group")) + 
                  stat_function(aes(colour = "group 1"),
                                fun = function(x) 
                                myfun(x, 0, abe[i, 1], abe[i, 2], abe[i, 3]),
                                geom = "line") +
                  stat_function(aes(colour = "group 2"),
                                fun = function(x) 
                                myfun(x, 1, abe[i, 1], abe[i, 2], abe[i, 3]),
                                geom = "line") + 
                  ylim(c(-10, 10)) + xlim(c(-2, 2)) 
}

### everything OK
for (i in 1:3){
  print(myplot[[i]])
}
### points are changing but lines remain the same
myplot[[1]]; myplot[[2]]; myplot[[3]]
### again points are changing but lines remain the same
grid.arrange(myplot[[1]], myplot[[2]], myplot[[3]], ncol = 3)

由于我想将所有数字保存到一个文件中,我很乐意正确制作grid.arrange个情节线。

1 个答案:

答案 0 :(得分:2)

当您打印图表时,i == 3和您的函数仅评估参数,并使用此值i。请改用stat_function语法:

myplot[[i]] <-  ggplot(df, aes_string("x", "num")) +
    geom_point(aes_string(colour = "group")) + 
    stat_function(aes(colour = "group 1"),
                  fun = myfun,
                  args = list(a = abe[i, 1], b = abe[i, 2], 
                              e = abe[i, 3], group = 0),
                  geom = "line") +
    stat_function(aes(colour = "group 2"),
                  fun = myfun,
                  args = list(a = abe[i, 1], b = abe[i, 2], 
                              e = abe[i, 3], group = 1),
                  geom = "line") + 
    ylim(c(-10, 10)) + xlim(c(-2, 2))