我想使用 ggplot2 来说明两个相似密度分布之间的差异。这是我拥有的数据类型的玩具示例:
library(ggplot2)
# Make toy data
n_sp <- 100000
n_dup <- 50000
D <- data.frame(
event=c(rep("sp", n_sp), rep("dup", n_dup) ),
q=c(rnorm(n_sp, mean=2.0), rnorm(n_dup, mean=2.1))
)
# Standard density plot
ggplot( D, aes( x=q, y=..density.., col=event ) ) +
geom_freqpoly()
而不是单独绘制每个类别的密度(dup
and sp
)如上所述,我如何绘制一条线来显示这些分布之间的差异?
在上面的玩具示例中,如果我减去dup
密度分布由sp
密度分布,结果线将在图左侧高于零(因为存在大量较小的sp
值)并且右侧低于 0(因为存在大量更大的dup
值)。并不是说可能有不同数量的观察类型dup
and sp
.
更一般地说,显示相似密度分布之间差异的最佳方法是什么?
在 ggplot 中可能有一种方法可以做到这一点,但通常情况下,预先进行计算是最简单的。在这种情况下,请致电density
在每个子集上q
在相同范围内,然后减去 y 值。使用 dplyr (如果您愿意,可以转换为基本 R 或 data.table),
library(dplyr)
library(ggplot2)
D %>% group_by(event) %>%
# calculate densities for each group over same range; store in list column
summarise(d = list(density(q, from = min(.$q), to = max(.$q)))) %>%
# make a new data.frame from two density objects
do(data.frame(x = .$d[[1]]$x, # grab one set of x values (which are the same)
y = .$d[[1]]$y - .$d[[2]]$y)) %>% # and subtract the y values
ggplot(aes(x, y)) + # now plot
geom_line()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)