0

I'm trying to add multiple geom_vlines to my ggobject but it seems that only the last one is kept. How do i add multiple geom_vlines in this function?. I need to add these lines from the vector received as_vert_line, thanks in advance.

make_histogram <- function(data, title, xlabel, ylabel, as_vert_line, color_list){
  #storgis rule
  minDiff = min(data)
  maxDiff = max(data)
  m = round(1+3.3*log(length(data), exp(1)))
  ran = maxDiff - minDiff
  amp = ran/m
  nC = round(ran/amp)

  #histogram
  plotobj <- ggplot(data.frame(seq(1:length(data)), data), aes(x=data))+
    geom_histogram(bins=nC, color="white")+
    theme_classic()+
    ggtitle(title)+
    xlab(xlabel)+
    ylab(ylabel)+
    theme(legend.position = "none")
    

  #vlines
  for(i in 0:(length(as_vert_line)-1)){
    plotobj <- plotobj + geom_vline(aes(xintercept=as_vert_line[i+1], color=color_list[i%%(length(color_list))+1]), size=1.2)
  }

  print(plotobj)
  return(plotobj)
}
diddierh
  • 11
  • 3
  • Use `!!i` rather than `i` to capture the current value during the loop. `plotobj <- plotobj + geom_vline(aes(xintercept=as_vert_line[!!i+1], color=color_list[!!i%%(length(color_list))+1]), size=1.2)`. Also, in the future, please add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample data and a sample call to the function that we can just copy/paste to test with in R. – MrFlick Sep 02 '21 at 22:11
  • That solved, the issue, thank you. – diddierh Sep 02 '21 at 22:30

0 Answers0