ggplot混合模型R

ggplot mixture model R

我有一个包含数值和分类变量的数据集。每个类别的数值变量分布不同。我想为每个分类变量绘制 "density plots",以便它们在视觉上位于整个密度图下方。

这类似于不计算混合模型的混合模型的组件(因为我已经知道拆分数据的分类变量)。

如果我拿ggplot按分类变量分组,四个密度每一个都是真实密度,积分为一个。

library(ggplot2)
ggplot(iris, aes(x = Sepal.Width)) + geom_density() + geom_density(aes(x = Sepal.Width, group = Species, colour = 'Species'))

我想要的是将每个类别的密度作为子密度(不积分为1)。类似于下面的代码(我只实现了三种鸢尾花中的两种)

myIris <- as.data.table(iris)
# calculate density for entire dataset
dens_entire <- density(myIris[, Sepal.Width], cut = 0)
dens_e <- data.table(x = dens_entire[[1]], y = dens_entire[[2]])

# calculate density for dataset with setosa
dens_setosa <- density(myIris[Species == 'setosa', Sepal.Width], cut = 0)
dens_sa <- data.table(x = dens_setosa[[1]], y = dens_setosa[[2]])

# calculate density for dataset with versicolor
dens_versicolor <- density(myIris[Species == 'versicolor', Sepal.Width], cut = 0)
dens_v <- data.table(x = dens_versicolor[[1]], y = dens_versicolor[[2]])

# plot densities as mixture model
ggplot(dens_e, aes(x=x, y=y)) + geom_line() + geom_line(data = dens_sa, aes(x = x, y = y/2.5, colour = 'setosa')) + 
  geom_line(data = dens_v, aes(x = x, y = y/1.65, colour = 'versicolor'))

导致

上面我硬编码了数字以减少 y 值。有什么办法可以用ggplot来做吗?还是计算一下?

感谢您的想法。

你的意思是这样的吗?不过你需要改变比例。

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_density(aes(y = ..count..)) + 
  geom_density(aes(x = Sepal.Width, y = ..count.., 
               group = Species, colour = Species))

另一个选项可能是

ggplot(iris, aes(x = Sepal.Width)) + 
   geom_density(aes(y = ..density..)) + 
   geom_density(aes(x = Sepal.Width, y = ..density../3, 
                    group = Species, colour = Species))