1

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?

M--
  • 25,431
  • 8
  • 61
  • 93
Stata_user
  • 562
  • 3
  • 14

2 Answers2

2

You don't need a for-loop and if-statement for this matter. You can use faceting;

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

set.seed(123) ## set the seed for random numbers to be reproducible
df <- bind_rows(lapply(1:4, function(x) 
                              data.frame(V1=rnorm(1000), V2=seq(1000))), .id = 'facet')

ggplot(df, aes(x= V2, y=V1)) +
  geom_point() +
  facet_wrap(~facet) +
  geom_vline(data=data.frame(xint=500,facet=4), aes(xintercept = xint), color = "red")

M--
  • 25,431
  • 8
  • 61
  • 93
0

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)
sambold
  • 807
  • 5
  • 15
  • HI @sambold, Thanks for your help. I've just posted a related question. Would you mind taking a look at that one too? https://stackoverflow.com/questions/62594080/ggplot-labeling-graphs-in-a-loop – Stata_user Jun 26 '20 at 11:49