There are a few posts regarding the use of shaded areas in ggplot2, but I don't think any exactly answer my question. I have two slopes for lines across a number of conditions, and I would like to shade the region between them. Here is example data:
dat <- data.frame(cond1=c("a","a","b","b"),
cond2=c("c","d","c","d"),
x=c(1,5),
y=c(1,5),
sl=c(1,1.2,0.9,1.1),
int=c(0,0.1,0.1,0),
slopeU=c(1.1,1.3,1.2,1.2),
slopeL=c(.9,1,0.7,1))
Here, sl
is the mean slope parameter from a separate fitting procedure, and slopeU
and slopeL
represent upper and lower confidence regions on the slope estimate in each condition. The intercepts are constrained to be the same. The following code plots the best fitting lines for each condition using some faceting:
p <- ggplot(dat,aes(x=x,y=y,colour=cond1))
p <- p + facet_grid(. ~ cond2)
p <- p + geom_blank()
p <- p + geom_abline(aes(intercept=int,slope=sl,colour=cond1),data=dat)
p
I would like to add the lines defined by intercept=int, slope=slopeU
and intercept=int, slope=slopeL
to the plot and shade the region between them (e.g. at alpha=.5
in the corresponding cond1 colour).
I recognise that with a little manipulation I could create a data frame specifying values of these lines for at least two x values, then plot the corresponding geom_ribbon or geom_polygon to create the shaded region, however I would like to find a more elegant solution. Or is manually specifying some coordinates from the slopes and intercepts the only way? How would I best create the required data frame (which will need to have more rows than the original frame to account for all combinations of conditions and x,y pairs).