How to add individual hlines for each bar in a plot?

Viewed 34

Given a data frame and a plot as follows:

library(dplyr)
library(ggplot2)

dat <- data.frame(grp = c("a", "b", "c"),
           val = c(30, 20, 10),
           avg = c(25, 15, 5)) 

dat %>% 
  ggplot(aes(x = grp, y = val)) +
  geom_bar(stat = "identity")

How do I amend the code above to place a unique horizontal reference line (avg) on each bar as shown below:

enter image description here

1 Answers

This could be achieved via geom_segment like so, where I first conver grp to a numeric and corresponding to the default width of a bar of .9 put the x at .45 to the left and xend at .45 to the right:

library(ggplot2)

dat <- data.frame(grp = c("a", "b", "c"),
                  val = c(30, 20, 10),
                  avg = c(25, 15, 5)) 

ggplot(dat, aes(x = grp, y = val)) +
  geom_bar(stat = "identity") +
  geom_segment(aes(y = avg, yend = avg, 
                   x = as.numeric(factor(grp)) - .45, 
                   xend = as.numeric(factor(grp)) + .45), color = "red")

EDIT Thanks to comment by @tjebo: As hard-coding is rarely a good idea one could set the width via a variable:

w <- .9
...
geom_segment(aes(y = avg, yend = avg, 
                       x = as.numeric(factor(grp)) - w/2, 
                       xend = as.numeric(factor(grp)) + w/2), color = "red")

enter image description here

Related