简体   繁体   English

如何用ggplot在一个区间内填充密度图?

[英]How to fill density plot within an interval with ggplot?

The code below fills each of the two densities with color under the area of the curve:下面的代码用曲线区域下的颜色填充两个密度中的每一个:

library(ggplot2)

#fake data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 2, 0.5))
                   , group = rep(c("C", "P"), each = 100))

#fill the area under the curve
ggplot(dat, aes(x = dens, fill = group)) + geom_density(alpha = 0.75)

How can I achieve the following two goals?我怎样才能实现以下两个目标?

1) Only fill each curve within a specified interval. 1) 仅填充指定间隔内的每条曲线。 For example, interval [-1.5, 2.0] for group 'C' and [0.5, 2.8] for group 'P'.例如,“C”组的间隔为 [-1.5, 2.0],“P”组的间隔为 [0.5, 2.8]。

2) Add a vertical segment (from x-axis to the curve) for each density. 2) 为每个密度添加一个垂直线段(从 x 轴到曲线)。 For example, at x=0.2 for group 'C' and at x=1.9 for group 'P'.例如,“C”组的 x=0.2 和“P”组的 x=1.9。

To get you stared, here's your first question:为了让你眼前一亮,这是你的第一个问题:

library(dplyr)
library(purrr)
library(tidyr)
library(ggplot2)

as.data.frame.density <- function(x) data.frame(x = x$x, y = x$y)

densities <- dat %>% 
  group_nest(group) %>% 
  mutate(dens = map(data, ~as.data.frame(density(.$dens)))) %>% 
  unnest(dens)

ggplot(densities, aes(x = x, y = y, group = group)) + 
  geom_density(stat = 'identity') +
  geom_density(
    aes(fill = group),
    . %>% filter((group == "C" & between(x, -1.5, 2.0)) | (group == "P" & between(x, 0.5, 2.8))),
    stat = 'identity',
    alpha = 0.75
  )

在此处输入图片说明

There are other ways of calculating the densities per group, using dplyr is just one way.还有其他计算每组密度的方法,使用dplyr只是一种方法。 It is probably good to set an equal bandwidth to the two density estimations.为两个密度估计设置相等的带宽可能是好的。

Adding the segments is similar to this approach, you just need to find the correct values in the densities data.frame.添加段类似于这种方法,你只需要找到在正确的价值观densities data.frame。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM