2

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that is a really cool way to look at it. Thanks! This is exactly what I wanted cause I drop it directly into the ggplot, I didn't think that was possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.