rfor-loopggplot2gridextrageom-vline

Creating graphs in a loop: one graph different from the others


I have an elaborate code to create a series of graphs. I would like to put a vertical line in one of the many graphs I create.

Consider the following simple code:

library(ggplot2)
library(grid)
library(gridExtra)


plots <- list()

for (i in 1:4) {
  V1 <- rnorm(1000)
  V2 <- seq(1000)
  df <- data.frame(V1, V2)

plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
    geom_point()+
    geom_vline(xintercept = 500, color="red")
}


grid.arrange(grobs=plots, nrow=2)

I would like to have the red vertical line for graph 4 but not the others. How would I do this efficiently?


Solution

  • just split your plot production and set a condition :)

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    
    plots <- list()
    
    for (i in 1:4) {
        V1 <- rnorm(1000)
        V2 <- seq(1000)
        df <- data.frame(V1, V2)
        
        plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
            geom_point()
        if (i == 4) plots[[i]] <- plots[[i]] + geom_vline(xintercept = 500, color="red")
    }
    
    
    grid.arrange(grobs=plots, nrow=2)