【问题标题】:ggplot mixture model Rggplot混合模型R
【发布时间】:2017-02-01 11:58:18
【问题描述】:

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

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

如果我根据分类变量将 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做到这一点?还是计算一下?

感谢您的想法。

【问题讨论】:

    标签: r ggplot2 density-plot mixture-model


    【解决方案1】:

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

    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))
    

    【讨论】:

    • 嗨,是的,看起来很有希望。如果我用 iris 数据集的条目数来缩放它,即 nrow(iris) = 150,它看起来相当不错。所以不是 ..count.. 它是 ..count../150。任何人都可以验证这是正确的方法吗?就我而言,每个类别中的数量并不相同,但有一个类别约占数据的 60%。
    • 您好,我考虑过并讨论过,这是正确的答案。感谢@Kota Mori 的快速回复。要么采用 y = ..count../Number_of_rows_of_entire_dataset 要么采用 y = ..density../number_of_categories
    猜你喜欢
    • 2015-09-13
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2020-09-12
    • 2020-02-12
    • 1970-01-01
    相关资源
    最近更新 更多