Ggplot tape cut off within y

I want to use geom_ribbon in ggplot2 to draw shaded confidence ranges. But if one of the lines goes beyond the specified y values, the tape is cut off before reaching the edge of the graph.

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

I want to reproduce the same behavior as when building in the R base, where the shading continues 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

+6
source share
1 answer

The problem is that limits deletes all data that is not in its range. What you want is a sketch first and then an increase. This can be done 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

+9
source

All Articles