Question

I am creating charts where a white line breaks the bar in front of bar (sorry can't post Image). I have gotten the code to do it once but I am not great with looping yet.

library(ggplot2)

count <- c(61.8,18.8)
name <- c("A","B")
yes <- data.frame(count,name)

j <-   ggplot(yes, aes(x=name, y=count)) + 
geom_bar(stat="identity", position="dodge") 

To add just one line I created this function...

b <- function (yx){
j + annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

b(8)

This is where I'm stuck, I'd like to make a loop that could run through a vector like...

yx <- c(8,10,20)

and create a line at 8, 10 and 20. The one tricky point is that all the data other than the terminal one (last) needs to have a "+" at the end. Has anyone tried this?

Thanks

Was it helpful?

Solution

Your function is already vectorised, so you don't need to change a thing,

add_lines <- function(yx){
  annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

j + add_lines(c(8,10,20))

Conceptually, however, if you wanted to add lines one by one, you could simply use a list:

add_oneline <- function(yx){
  annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

lines <- lapply(c(8,10,20), add_oneline)
j + lines

but that's less efficient and more convoluted than the first option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top