基于R中拟合的GMM在直方图顶部绘制密度

Draw density on top of histogram based on fitted GMM in R

我想简单地在直方图的顶部绘制密度,使用 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)

这里有一些假设,但我会试一试。首先,我认为您不能使用标准 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))