3

The following code produces two lines as desired

p <- ggplot()
p <- p + geom_line(aes(x=c(0,1),y=c(0,1)))
p <- p + geom_line(aes(x=c(0,1),y=c(0,2)))

enter image description here

Replacing this with a loop only results in one line

p <- ggplot()
for(i in 1:2){
    p <- p + geom_line(aes(x=c(0,1),y=c(0,i)))
}

enter image description here

How can I fix this? I want to add an arbitrary number of lines to my plot.

slabofguinness
  • 773
  • 1
  • 9
  • 19
  • 1
    Does this help: https://stackoverflow.com/questions/55627528/how-can-i-pass-individual-curvature-arguments-in-ggplot2-geom-curve-functi ? Add a list to your plot and use `lapply` to create that list. `p + lapply(1:2, function(i) { geom_line(aes(x=c(0,1),y=c(0,i))) })` The link provides some examples. – markus May 16 '19 at 09:08

1 Answers1

2

Loop saves 2 lines, but with variable i, not value of i, and when you call p, i==2 so both lines are identical. You can insert value instead of variable name by !! from dplyr

library(ggplot2)
library(dplyr)
p <- ggplot()
for(i in 1:3) {
  p <- p + geom_line(aes(x=c(0,1),y=c(0,!!i)))
}

enter image description here

Yuriy Barvinchenko
  • 1,465
  • 1
  • 12
  • 17