Plot density curve of mixture of two normal distribution

时间:2016-10-09 15:49:30

标签: r loops plot

I am rather new to R and could use some basic help. I'd like to generate sums of two normal random variables (variance = 1 for each) as their means move apart and plot the results. The basic idea: if the means are sufficiently far apart, the distribution will be bimodal. Here's the code I'm trying:

x <- seq(-3, 3, length=500)
for(i in seq(0, 3, 0.25)) {
y <- dnorm(x, mean=0-i, sd=1)
z <- dnorm(x, mean=0+i, sd=1)
plot(x,y+z, type="l", xlim=c(-3,3))
}

Several questions:

  1. Are there better ways to do this?
  2. I'm only getting one PDF on my plot. How can I put multiple PDFs on the same plot?

Thank you in advance!

1 个答案:

答案 0 :(得分:1)

使用基本R功能进行此操作并不困难。我们首先定义一个函数f来计算混合物法线的密度:

## `x` is an evaluation grid
## `dev` is deviation of mean from 0
f <- function (x, dev) {
  (dnorm(x, -dev) + dnorm(x, dev)) / 2
  }

然后我们使用sapply循环遍历各种dev以获得相应的密度:

## `dev` sequence to test
dev <- seq(0, 3, 0.25)
## evaluation grid; extending `c(-1, 1) * max(dev)` by 4 standard deviation
x <- seq(-max(dev) -4, max(dev) + 4, by = 0.1)
## density matrix
X <- sapply (dev, f, x = x)

最后我们使用matplot进行绘图:

matplot(x, X, type = "l", lty = 1)

enter image description here

更多解释

sapply期间,x未更改,而我们每次迭代时都会尝试dev的一个元素。就像

X <- matrix(0, nrow = length(x), ncol = length(dev))
for (i in 1:length(dev)) X[, i] <- f(x, dev[i])

matplot(x, X)会针对X逐一绘制x列。