1
votes

I am trying to add multiple ribbons to a graph using ggplot2, and also label the shaded regions. For example, say I'm trying to write code to generate a graphic of a normal distribution, and to shade everything above a certain value and below a certain value (shade both tails).

This is what I have so far:

library(ggplot2)

x<-seq(-3,3,length=100)

y1<-dnorm(x,mean=0,sd=1);

df<-data.frame(x,y1)

qplot(x,y1,data=df, geom="line")+geom_ribbon(data=subset(df,x > 2),
aes(ymax=y1),ymin=0, fill="red", colour=NA, alpha=0.5)
+geom_ribbon(data=subset(df,x < -2),
aes(ymax=y1),ymin=0, fill="red", colour=NA, alpha=0.5)

This code will shade the right tail, but not the left. (Stack exchange won't allow me to add pictures)

So, how do I add shading for the other tail in the same picture? as well, how do I label both shaded parts?

1
Probably because you included an erroneous line break just before the second geom_ribbon call. - joran
For the labels, try either geom_text or annotate. - joran
got it; thanks. putting the plus sign before the break also works.... - user2192320
@Gavin Simpson I've reverted you improvements since they actually removed the source of the error. - Roland

1 Answers

0
votes

You can use the annotate function to add the labeling:

p <- qplot(x,y1,data=df, geom="line") +
    geom_ribbon(data=subset(df,x > 2),
          aes(ymax=y1),ymin=0, fill="red", colour=NA, alpha=0.5) +
    geom_ribbon(data=subset(df,x < -2),
          aes(ymax=y1),ymin=0, fill="red", colour=NA, alpha=0.5)

p + annotate('text', x = c(-2.5,2.5), y = 0.07, label =  c('lowest \n 2.5 %', 
    'highest \n 2.5 %'),  col = 'red', alpha =0.5)