stat_函数和grid.arrangein for循环
我正在尝试使用stat_函数和grid.arrangein for循环,r,printing,ggplot2,R,Printing,Ggplot2,我正在尝试使用stat\u function使用ggplot2包绘制多个函数。因为我有几个参数的选项,我使用循环。我将绘图保存到列表变量myplot中。当我试图打印它们时,问题就出现了。使用print似乎一切正常,但当我仅使用选项,例如myplot[[1]]时,线条与myplot[[2]]等的线条相同,但点绘制正确。当我尝试使用函数grid.arrange用一个图形绘制所有图形时,也会发现同样的问题 参见我的示例: library("ggplot2") myfun <- function(
stat\u function
使用ggplot2
包绘制多个函数。因为我有几个参数的选项,我使用循环。我将绘图保存到列表变量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)
库(“ggplot2”)
myfun当您打印绘图时,i==3
,并且您的函数仅在此时使用该值i
计算参数。使用正确的stat\u函数
语法:
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))
myplot[[i]]