R:加权Joyplot/Ridgeplot /密度图?

use*_*648 1 r ggplot2 gplots density-plot ggridges

我正在尝试使用ggridges包创建一个joyplot (基于ggplot2).一般的想法是,一个joyplot创建了精确缩放的堆积密度图.但是,我似乎无法使用加权密度生成其中一个.是否有一些方法可以在计算密钥套的创建中计算密度时采用抽样权重(加权密度)?

这里是该ggridges软件包文档的链接:https://cran.r-project.org/web/packages/ggridges/ggridges.pdf我知道很多基于ggplot的软件包可以接受额外的美学,但我不知道知道如何为这种类型的geom添加权重.

另外,这是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)
Run Code Online (Sandbox Code Playgroud)

And*_*gan 5

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

请注意,默认stat_density_ridges值会对所有数据集进行联合密度估计.使用多面图时,这可能无法生成所需的结果.作为替代方案,您可以设置 stat = "density"使用stat_density.在这种情况下,需要添加美学映射height = ..density..(参见示例).

幸运的是,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
Run Code Online (Sandbox Code Playgroud)

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

注意:当您使用stat_densityx轴范围时,行为似乎有点不同:它会将密度图调整到数据范围并丢弃漂亮的尾部.你可以通过手动扩展x轴来轻松纠正这个问题,但我认为值得一提.