本文介绍了R:加权Joyplot/Ridgeplot/密度图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggridges包(基于ggplot2)创建一个Joyplot.一般的想法是,一个Joyplot可以创建缩放比例合适的堆叠密度图.但是,我似乎无法使用加权密度生成其中之一.在创建Joyplot的密度计算中,是否有某种方法可以将采样权重(用于加权密度)纳入计算?

I am trying to create a joyplot using the ggridges package (based on ggplot2). The general idea is that a joyplot creates nicely scaled stacked density plots. However, I cannot seem to produce one of these using weighted density. Is there some way of incorporating sampling weights (for weighted density) in the calculation of the densities in the creation of a joyplot?

以下是ggridges软件包文档的链接: https://cran.r-project.org/web/packages/ggridges/ggridges.pdf 我知道很多基于ggplot的软件包都可以接受其他美学效果,但是我不知道如何增加权重这种类型的geom对象.

Here's a link to the documentation for the ggridges package: https://cran.r-project.org/web/packages/ggridges/ggridges.pdf I know a lot of packages based on ggplot can accept additional aesthetics, but I don't know how to add weights to this type of geom object.

此外,这是ggplot中未加权的Joyplot的示例.我正在尝试将其转换为加权图,并根据pweight对密度进行加权.

Additionally, here is an example of an unweighted joyplot in ggplot. I am trying to convert this to a weighted plot with the density weighted according to 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.根据您链接到的文档:

It looks like the way to do this is to use stat_density rather than the default stat_density_ridges. Per the docs you linked to:

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

Fortunately, stat_density (unlike stat_density_ridges) understands the aesthetic weight and will pass it to the underlying density call. You end up with something like:

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轴范围的行为略有不同:它将把密度图修整到数据范围,并丢掉漂亮的尾巴.您可以通过手动扩展x轴轻松地纠正此问题,但我认为值得一提.

Note: It appears that when you use stat_density the x-axis range behaves a little differently: it will trim the density plot to the data range and drop the nice-looking tails. You can easily correct this by manually expanding your x-axis, but I thought it was worth mentioning.

这篇关于R:加权Joyplot/Ridgeplot/密度图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:26