【发布时间】: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 绘图线。
【问题讨论】: