Fponken
Fponken

Reputation: 23

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

Upvotes: 2

Views: 1988

Answers (3)

Axeman
Axeman

Reputation: 35392

Use annotate with infinite x-values:

ggplot(data, aes(x, y)) + 
  geom_line() + 
  geom_hline(yintercept = 5) +
  annotate('ribbon', x = c(-Inf, Inf), ymin = 5 - 0.5, ymax = 5 + 0.5, 
           alpha = 0.4, fill = 'red')

enter image description here

If you need a legend, use geom_ribbon directly, like so:

ggplot(data, aes(x, y)) + 
  geom_line() + 
  geom_hline(yintercept = 5) +
  geom_ribbon(
    aes(x, y = NULL, ymin = ymin, ymax = ymax, fill = 'my_label'), 
    data.frame(x = c(-Inf, Inf), ymin = 5 - 0.5, ymax = 5 + 0.5),
    alpha = 0.4
  )

Upvotes: 4

David Rubinger
David Rubinger

Reputation: 3948

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

Upvotes: -1

hoggue
hoggue

Reputation: 147

There is no way in geom_hline() to set xlim, instead the horizontal line goes from end of the plot to the other. You can use geom_segment instead, which allows you to control the x-range and y-range of the line by specifying segment's start coordinate (x, y) and end coordinate (xend, yend)

This works:

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_segment(aes(x = x[1], xend = x[10], y = y[5], yend = y[5]))

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

Upvotes: 1

Related Questions