1

How can I add a line onto each bar in a ggplot barplot?

For example, using the built-in ggplot example:

mm <- ddply(mtcars, "cyl", summarise, mmpg = mean(mpg))
ggplot(mm, aes(x = factor(cyl), y = mmpg)) + geom_bar(stat = "identity")

produces this

enter image description here

Now I have a vector y <- c(10, 5, 5), which is the height at which I want to plot a line on each bar, producing something like this

enter image description here

How can I do it? I tried geom_hline, but that produces lines that cut across the entire chart instead.

3
  • Can you post your exact code that generates the second plot? I'm not certain there is a straightforward solution to your question, but perhaps we can work something out. In the meantime (and you've probably already consulted this), <docs.ggplot2.org/current/geom_hline.html> might help. Commented Aug 2, 2015 at 10:28
  • The "code" for second plot was Paint in Windows to add 3 white lines on the .PNG exported of the first plot :) Commented Aug 2, 2015 at 10:43
  • Oh cool. I was excited because I'd never seen anything that does that out of ggplot2 :p Commented Aug 2, 2015 at 10:46

1 Answer 1

5

This should work:

y <- c(10, 5, 5)

mm <- ddply(mtcars, "cyl", summarise, mmpg = mean(mpg))
mm <- cbind(mm, y) # get vector into data frame

ggplot(mm, aes(x = factor(cyl), y = mmpg)) + 
geom_bar(stat = "identity") +
geom_errorbar(aes(yintercept = y, ymax=y, ymin=y), 
              color = "white", size = 2)

We use geom_errorbar()to draw the lines in the data frame and then reduce their width by manually setting ymax and ymin to the yvalue.

The above code produces this result:

enter image description here

Credit goes to this source.

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

Comments

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.