【问题标题】:stat_function and grid.arrange in for loopfor 循环中的 stat_function 和 grid.arrange
【发布时间】:2023-03-04 15:40:01
【问题描述】:

我正在尝试使用 stat_function 绘制带有 ggplot2 包的多个函数。因为我有几个参数选项,所以我使用 for 循环。我将绘图保存到列表变量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 绘图线。

【问题讨论】:

    标签: r printing ggplot2


    【解决方案1】:

    当您打印绘图时,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)) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2015-02-25
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多