Skip to content

Instantly share code, notes, and snippets.

@kokes
Created March 6, 2016 16:33
Show Gist options
  • Save kokes/58157d1ac5a21d5730c3 to your computer and use it in GitHub Desktop.
Save kokes/58157d1ac5a21d5730c3 to your computer and use it in GitHub Desktop.
Mixplots of normal mixtures in R
library(mclust)
mixplot <- function(ts,plot=TRUE) {
rng=seq(from=min(ts),to=max(ts),by=(max(ts)-min(ts))/1000)
mcp = Mclust(ts)$par
mat=cbind(mcp$mean,mcp$var$sigmasq,mcp$pro)
dens=apply(mat[,-3],1,function(x) dnorm(rng,mean=x[1],sd=sqrt(x[2])))
f=dens%*%mat[,3]
if (plot) {
hist(ts,breaks=100,border="gray",probability=TRUE,main="")
lines(rng,f,lty=2)
}
result = list(mean=as.vector(mcp$mean), sigmasq=as.vector(mcp$var$sigmasq),proportion=as.vector(mcp$pro))
return(result)
}
# you feed it data and out you get a histogram with
# a line plot of a normal mixture estimated using the Mclust
# package
# the function plots by default, but you can supress to chart
# and only get the Mclust output
mixplot(c(rnorm(1000,0,0.5),rnorm(400,1.5,0.1),rnorm(600,2.5,0.5)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment