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

时间:2019-07-11 07:59:09

标签: r histogram density-plot gmm

我想使用均值简单地在直方图上绘制密度,并使用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)

1 个答案:

答案 0 :(得分: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))

enter image description here