[R] ggplot2: discontinuous ribbon

sbihorel Sebastien.Bihorel at cognigencorp.com
Wed Oct 21 11:20:27 CEST 2015


Hi

I would like to use ggplot2 to create a 2d plot showing a series of 
shaded areas that are not continuous with respect to the x-axis 
variable. The expected result is illustrated below using lattice/grid 
functions.

-------------
pdata <- data.frame(
   x=c(1,2,2,1,NA,3,4,4,3,NA,5,6,6,5),
   y=c(3,3,2,2,NA,2,2,1,1,NA,2.5,3,2,2))

lattice::xyplot((1:6)~(1:6),panel=function(pdata=pdata){
   grid::grid.polygon(pdata$x,pdata$y,
                default.units='native',
                gp=grid::gpar(fill=1,col=NULL,lty=0))
},pdata=pdata)
-------------

Here is my attempt to reproduce this plot in ggplot.

-------------
library(ggplot2)
data <- data.frame(
   x=c(1,2,NA,3,4,NA,5,6),
   ymin=c(2,2,NA,1,1,NA,2,2),
   ymax=c(3,3,NA,2,2,NA,2.5,3)
)

ggplot(data,aes(x=x))+geom_ribbon(aes(ymin=ymin,ymax=ymax))
-------------

Obviously, either geom_ribbon expects continuity in the data or I need 
to setup my data and/or call differently...

Thanks for your help

Sebastien



More information about the R-help mailing list