25

I want to use geom_ribbon in ggplot2 to draw shaded confidence ranges. But if one of the lines goes outside the set y limits, the ribbon is cut off without extending to the edge of the plot.

Minimal example

x <- 0:100
y1 <- 10+x
y2 <- 50-x

ggplot() + theme_bw() +
  scale_x_continuous(name = "x", limits = c(0,100)) +
  scale_y_continuous(name = "y", limits = c(-20,100)) +
  geom_ribbon(aes(x=x, ymin=y2-20, ymax=y2+20), alpha=0.2, fill="#009292") +      
  geom_line(aes(x=x , y=y1)) +
  geom_line(aes(x=x , y=y2)) 

enter image description here

What I want is to reproduce the same behaviour as I get with plotting in base R, where the shading extends to the edge

plot(x, y1, type="l", xlim=c(0,100),ylim=c(-20,100))
lines(x,y2)
polygon(c(x,rev(x)), c(y2-20,rev(y2+20)), col="#00929233", border=NA)

enter image description here

dww
  • 30,425
  • 5
  • 68
  • 111
  • 1
    using `oob=scales::squish` in the `scale_y_continuous()` call is helpful but creates some of its own artifacts ... – Ben Bolker Aug 04 '16 at 21:52
  • Possible duplicate of [Limit ggplot2 axes without removing data (outside limits): zoom](http://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom) – aosmith Aug 04 '16 at 21:52

1 Answers1

36

The problem is that limits is removing all data which are not within its range. What you want is to first plot and then zoom in. This can be done by using coord_cartesian.

ggplot() + theme_bw() +
  geom_ribbon(aes(x = x, ymin = y2 - 20, ymax = y2 + 20), alpha = 0.2, fill = "#009292") +      
  geom_line(aes(x = x, y = y1)) +
  geom_line(aes(x = x, y = y2)) + 
  coord_cartesian(ylim = c(-25, 100), xlim = c(0,100)) 

enter image description here

Alex
  • 4,925
  • 2
  • 32
  • 48