ggplot2 shade area under curve by group

by Alex   Last Updated January 15, 2018 20:26 PM

I'm trying to shade the area under two curves; I want to get exactly the same plots (without thresholds though) as in previous post, with the only difference that I want to use geom_line() instead of stat_density(). Is there any way to do this? Thanks in advance.

I've tried what was suggested in that post, but it does not work when I use geom_line(). Also, I have tried something different, but this is not quite what I want, as I want to shade using different colors for different groups. Here is the initial code:

library(ggplot2)
x <- seq(0,1,0.005)
y1 <- dbeta(x,3,3)
data1<-data.frame('x'=x,'y'=y1)
data1$group<-1

y2 <- dbeta(x,10,4)
data2<-data.frame('x'=x,'y'=y2)
data2$group<-2

data<-rbind(data1, data2)
ggplot(data, aes(x=x, y=y, group=group, col=group, fill=group)) +  geom_line(size=1) +geom_ribbon(data=subset(data,x>0 &x<1),aes(x=x,ymax=y),ymin=0, fill="green4",alpha=0.3)

In case the above link doesn't work: ggplot2 shade area under density curve by group

Tags : r plot ggplot2 gplots


Answers 1


In case it might also be useful to someone else, the solution was to add scale_fill_manual() as follows:

ggplot(data, aes(x=x, y=y, group=group, fill=group)) 
+  geom_line(size=.5)
+  geom_ribbon(data=subset(data,x>0 & x<1),aes(x=x,ymax=y),ymin=0,alpha=0.3)
+  scale_fill_manual(name='', values=c("1" = "green4", "2" = "red"))
Alex
Alex
January 15, 2018 19:55 PM

Related Questions


ggplot2 density-plot with discrete data

Updated December 17, 2017 18:26 PM

Change colors of raster plot in ggplot2

Updated April 06, 2015 20:11 PM

Display percentage by column on a stacked bar graph

Updated April 19, 2017 09:26 AM

Play 3d graphic on ggplot2

Updated May 06, 2017 09:26 AM

how can I plot a complex data structure

Updated June 15, 2017 02:26 AM