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
The solution provided here looks as follows:
This is a perfectly fine solution, but I found myself writing similar code over and over, so I wrote
geom_density_line()
. It works likegeom_density()
but draws a line with a filled area instead of a polygon around a filled area. It's part of the current development version of the package ggridges:In case it might also be useful to someone else, the solution was to add
scale_fill_manual()
and change numeric1
and2
values ingroup
variable into character values"1"
and"2"
respectively as follows:Change
1
to"1"
and2
to"2"
as follows:and run: