1

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.

1 Answer 1

2

When you print the plots, i == 3 and your function evaluates the parameters only then and with this value of i. Use the proper stat_function syntax instead:

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)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.