Search code examples
rggplot2piping

print ggplot in a loop using chaining command


I am trying to make a set of ggplots in a loop and display them. I am trying use the %>% operator. Here is the toy example which plots points from 1 to 10, each with a different title.

library(magrittr)
library(ggplot2)

data1 <- data.frame('x' = 1:10, 'y' = 1:10)

for (index in 1:10){

  data1 %>% 
    ggplot(aes(x = x, y = y)) +
    geom_point() +
    ggtitle(paste("plot ",as.character(index)))
}

Now, the following code works and produces 10 plots, each with a different title

library(magrittr)
library(ggplot2)

data1 <- data.frame('x' = 1:10, 'y' = 1:10)

for (index in 1:10){


    print(ggplot(data = data1, aes(x = x, y = y)) +
    geom_point() +
    ggtitle(paste("plot ",as.character(index))))
}

but, I want to use the %>% operator to produce a series of plots. I have tried %>% print() at the end of title, it runs but does not produce plots for display. Whereas

for (index in 1:10){

  data1 %>% 
    print(data = .,ggplot(aes(x = x, y = y)) +
    geom_point() +
    ggtitle(paste("plot ",as.character(index))))

}

produces an error

Error: ggplot2 doesn't know how to deal with data of class uneval 

Is there something silly, that I am missing?

Thanks!


Solution

  • It's really a matter of order of operations between %>% and +. You can either block your ggplot stuff together like

    for (index in 1:10){
      data1 %>% {
        ggplot(., aes(x = x, y = y)) +
        geom_point() +
        ggtitle(paste("plot ",as.character(index)))
      } %>% print
    }
    

    or you can put the entire chain in the print

    for (index in 1:10) {
      print(data1 %>%
        ggplot(aes(x = x, y = y)) +
        geom_point() +
        ggtitle(paste("plot ",as.character(index)))
      )
    }