I'm trying to plot multiple functions with ggplot2 package using stat_function. As I have several parameters' options I use for loop. I save my plots into list variable myplot. The problem arises when I try to print them. Using print everything seems OK, but when I use only option e.g. myplot[[1]] the lines are the same as for myplot[[2]] etc, however points are plotted correctly. The same issue can be observed when I try to plot all my graphs with one figure using function grid.arrange.
See my example:
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)
As I want to save all figures into one file I would love to make grid.arrange plot lines correctly.