I am trying to add horizontal lines to a ggplot, based on intercepts given in a vector. Since the length of this vector will vary, and this vector will not necessarily follow any sequence, I am putting this inside a for loop, but I can only see that last line added. When I add without the for loop (which will imply a fixed vector size), I get the plot that I want.
library(ggplot2)
library(viridis)
dat = data.frame(x=runif(10), y=runif(10))
lines = c(0.1,0.2,0.3)
nlines = length(lines)
vpal = viridis(nlines,end=0.9)
## I only see the last line added:
p <- ggplot(dat,aes(x,y)) + geom_point()
for(i in 1:nlines){
p <- p + geom_hline(aes(yintercept=lines[i]), colour=vpal[i], linetype="dashed")
}
## I see all lines:
p <- ggplot(dat,aes(x,y)) + geom_point()
p <- p + geom_hline(aes(yintercept=lines[1]), colour=vpal[1], linetype="dashed")
p <- p + geom_hline(aes(yintercept=lines[2]), colour=vpal[2], linetype="dashed")
p <- p + geom_hline(aes(yintercept=lines[3]), colour=vpal[3], linetype="dashed")
Maybe I am missing something obvious, but how can I add a variable number of lines to a ggplot? Thanks!