R:加权 Joyplot/Ridgeplot/Density 情节?

R: Weighted Joyplot/Ridgeplot/Density Plot?

我正在尝试使用 ggridges 包(基于 ggplot2)创建一个欢乐图。一般的想法是 joyplot 创建很好缩放的堆叠密度图。但是,我似乎无法使用加权密度生成其中之一。在创建 joyplot 时,是否可以通过某种方式将采样权重(用于加权密度)纳入密度计算?

这是 ggridges 包文档的 link: https://cran.r-project.org/web/packages/ggridges/ggridges.pdf 我知道很多基于 ggplot 的包可以接受额外的美学,但我不知道如何为此类几何对象添加权重。

此外,这里有一个 ggplot 中未加权的 joyplot 示例。我正在尝试将其转换为密度根据 pweight 加权的加权图。

# Load package, set seed
library(ggplot)
set.seed(1)

# Create an example dataset
dat <- data.frame(group = c(rep("A",100), rep("B",100)),
                  pweight = runif(200),
                  val = runif(200))

# Create an example of an unweighted joyplot
ggplot(dat, aes(x = val, y = group)) + geom_density_ridges(scale= 0.95)

看起来这样做的方法是使用 stat_density 而不是默认的 stat_density_ridges。根据您链接到的文档:

Note that the default stat_density_ridges makes joint density estimation across all datasets. This may not generate the desired result when using faceted plots. As an alternative, you can set stat = "density" to use stat_density. In this case, it is required to add the aesthetic mapping height = ..density.. (see examples).

幸运的是,stat_density(与 stat_density_ridges 不同)理解美学 weight 并将其传递给底层 density 调用。你最终会得到类似的东西:

ggplot(dat, aes(x = val, y = group)) +
  geom_density_ridges(aes(height=..density..,  # Notice the additional
                          weight=pweight),     # aes mappings
                      scale= 0.95,
                      stat="density") # and use of stat_density

..density..变量由stat_density自动生成。

注意: 看起来当您使用 stat_density 时,x-axis 范围的行为略有不同:它将 trim 密度图到数据范围并放下 nice-looking 尾巴。您可以通过手动扩展 x-axis 轻松更正此问题,但我认为值得一提。