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:
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, 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"))
This is a perfectly fine solution, but I found myself writing similar code over and over, so I wrote geom_density_line()
. It works like geom_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:
# current development version is needed for this to work
library(ggridges) # install.github("clauswilke/ggridges")
ggplot(data, aes(x=x, y=y, group=group, fill=group)) +
geom_density_line(stat = "identity", size=.5, alpha=0.3) +
scale_fill_manual(name='', values=c("1" = "green4", "2" = "red"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With