rerrorbargeom-hline

How do i make an errorbar for a geom_hline using geom_ribbon in ggplot2?


I want to have an error bar for my geom_hline and thought that a geom_ribbon with opacity would look best. but i cant figure out how to make it reach the ends of the plot. I want the geom_ribbon to touch the sides of the plot as the geom_hline does. Here is the example code:

library('ggplot2')

x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(1,2,3,4,5,6,7,8,9,10)

data <- data.frame(x,y)

p1 <- ggplot(data,aes(x = x, y = y)) + geom_line() + geom_hline(yintercept=5)

p1 + geom_ribbon(aes(y = y[5],ymin = y[5]-0.5, ymax = y[5]+0.5, fill = 'red'), alpha = 0.4) 

enter image description here


Solution

  • Couple options:

    1) Use geom_hline instead of geom_ribbon like so (probably best option):

    p1 + geom_hline(yintercept = y[5], color = 'red', size = 8, alpha = 0.4)
    

    enter image description here

    2) Remove area between plot area and axis by adding scale_x_continuous(expand=c(0,0)) like so (credit to https://stackoverflow.com/a/22945857/5727278):

    p1 + geom_ribbon(aes(y = y[5],ymin = y[5]-0.5, ymax = y[5]+0.5, fill = 'red'), alpha = 0.4) +
    scale_x_continuous(expand=c(0,0))
    

    enter image description here