ggplot2曲线下的阴影区域(按组) [英] ggplot2 shade area under curve by group
问题描述
我正在尝试在两条曲线下阴影区域.我想获得与上一个完全相同的图(尽管没有阈值) post ,唯一的区别是我想使用geom_line()
而不是stat_density()
.有什么办法吗?预先感谢.
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.
我已经尝试了该帖子中建议的内容,但是当我使用geom_line()
时它不起作用.另外,我尝试了一些不同的方法,但这并不是我想要的,因为我想为不同的组使用不同的颜色进行着色.这是初始代码:
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)
如果上述链接不起作用: ggplot2阴影区域组下的密度曲线下
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"))
这是一个非常好的解决方案,但是我发现自己反复编写类似的代码,所以我写了geom_density_line()
.它的作用类似于geom_density()
,但绘制的是填充区域的线,而不是填充区域周围的多边形.它是ggridges软件包当前开发版本的一部分:
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"))
这篇关于ggplot2曲线下的阴影区域(按组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!