按组划分的密度曲线下的ggplot2阴影面积 [英] ggplot2 shade area under density curve by group
问题描述
我有这个数据框:
set.seed(1)
x <- c(rnorm(50, mean = 1), rnorm(50, mean = 3))
y <- c(rep("site1", 50), rep("site2", 50))
xy <- data.frame(x, y)
我制作了这个密度图:
library(ggplot2)
ggplot(xy, aes(x, color = y)) + geom_density()
对于 site1
,我需要对曲线下大于 1% 的数据的区域进行着色.对于 site2
,我需要对 site2
曲线下的区域进行阴影处理.75% 的数据.
For site1
I need to shade the area under the curve that > 1% of the data. For site2
I need to shade the area under the curve that < 75% of the data.
我希望情节看起来像这样(经过Photoshop处理).经历过堆栈溢出后,我知道其他人问过如何对曲线下的部分区域进行着色,但我不知道如何按组对曲线下的区域进行着色.
I'm expecting the plot to look something like this (photoshopped). Having been through stack overflow, I'm aware that others have asked how to shade part of the area under a curve, but I cannot figure out how to shade the area under a curve by group.
推荐答案
这是一种方法(而且,正如@joran 所说,这是响应的扩展 此处):
Here is one way (and, as @joran says, this is an extension of the response here):
# same data, just renaming columns for clarity later on
# also, use data tables
library(data.table)
set.seed(1)
value <- c(rnorm(50, mean = 1), rnorm(50, mean = 3))
site <- c(rep("site1", 50), rep("site2", 50))
dt <- data.table(site,value)
# generate kdf
gg <- dt[,list(x=density(value)$x, y=density(value)$y),by="site"]
# calculate quantiles
q1 <- quantile(dt[site=="site1",value],0.01)
q2 <- quantile(dt[site=="site2",value],0.75)
# generate the plot
ggplot(dt) + stat_density(aes(x=value,color=site),geom="line",position="dodge")+
geom_ribbon(data=subset(gg,site=="site1" & x>q1),
aes(x=x,ymax=y),ymin=0,fill="red", alpha=0.5)+
geom_ribbon(data=subset(gg,site=="site2" & x<q2),
aes(x=x,ymax=y),ymin=0,fill="blue", alpha=0.5)
产生这个:
这篇关于按组划分的密度曲线下的ggplot2阴影面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!