【问题标题】:Draw density on top of histogram based on fitted GMM in R基于 R 中的拟合 GMM 在直方图顶部绘制密度
【发布时间】:2019-07-11 07:59:09
【问题描述】:

我想简单地在我的直方图顶部绘制密度,使用均值和使用 GMM 估计的方差。我一直在尝试这样做,但我无法绘制密度。 y 轴总是不同的。

这将是一个玩具示例:

来自两个正态分布的数据x

setseed(0)    
x1 <- rnorm(100,5,1)
x2 <- rnorm(100,10,1)
x <- c(x1,x2)
hist(x)

然后我使用 mclust 包安装 GMM:

require(mclust)
gmm <- Mclust(x)
summary(gmm)

两个高斯的两个均值和(相等的)方差是:

gmm$parameters$mean ## 5.001579 and 9.931690 
gmm$parameters$variance$sigmasq ## 0.8516606

我可以根据 gmm 输出的classification 值为两条法线绘制不同颜色的直方图。但是我怎样才能在这个图的顶部为每个高斯简单地添加两个密度呢?

hist(x,breaks = seq(1,15,by=1),col="grey")
hist(x[gmm$classification==1],breaks = seq(1,15,by=1),col="red",add=T)
hist(x[gmm$classification==2],breaks = seq(1,15,by=1),col="blue",add=T)

【问题讨论】:

  • 目前您的直方图使用计数/频率。如果您以相同的比例绘制密度,它将在绘图底部附近显示为一个非常小的图形。您想要第二个 y 轴来缩放密度,还是想要在直方图中显示密度而不是频率?
  • @Sven 我想在两个直方图上显示两个密度图的直方图
  • 我明白了。但在什么规模?你的频率目前上升到 35,你的密度将是

标签: r histogram density-plot gmm


【解决方案1】:

这里有一些假设,但我会试一试。首先,我不认为你可以用标准的hist 轻松做到这一点,它可能需要ggplot2

#libraries
library(ggplot2)
library(mclust)

#Creating your sample data
setseed(0)    
x1 <- rnorm(100,5,1)
x2 <- rnorm(100,10,1)
x <- c(x1,x2)
#Putting it in a dataframe for ggplot
df <- as.data.frame(x)

gmm <- Mclust(x)

gmm$parameters$mean ## 5.001579 and 9.931690 
gmm$parameters$variance$sigmasq ## 0.8516606

#Calculating the breaks hist() would use
brx <- pretty(range(df$x), 
              n = nclass.Sturges(df$x),min.n = 1)

#Adding the classification to the dataframe for the colors.
df$classification <- as.factor(x[gmm$classification])

#Plotting the histograms, adding the density (scaled * 80) and adding a 2nd y-axis to show that scale
ggplot(df, aes(x, fill= classification)) + 
  geom_histogram(col="grey", breaks=brx, alpha = 0.5) +
  geom_density(aes(y = 80 * ..density.. , col=classification, fill = NULL), size = 1) +
  scale_y_continuous(sec.axis = sec_axis(~./80))

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2017-06-08
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2014-04-10
    相关资源
    最近更新 更多