两种正态分布的混合物的图密度曲线 [英] Plot density curve of mixture of two normal distribution

查看:64
本文介绍了两种正态分布的混合物的图密度曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R相当陌生,可以使用一些基本帮助.我想生成两个正常随机变量的总和(每个变量的方差= 1),因为它们的均值会分开并绘制结果.基本思想:如果均值相距足够远,则分布将是双峰的.这是我正在尝试的代码:

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))
}

几个问题:

  1. 有没有更好的方法来做到这一点?
  2. 我的地块上只有一张PDF.如何在同一图上放置多个PDF?

提前谢谢!

推荐答案

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

It is not difficult to do this using basic R features. We first define a function f to compute the density of mixture normal:

## `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 以获得相应的密度:

Then we use sapply to loop through various dev to get corresponding density:

## `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 进行绘图:

Finally we use matplot for plotting:

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

更多说明

sapply 期间, x 不变,而我们每次迭代都选择并尝试 dev 的一个元素.就像

During sapply, x is not changed, while we pick up and try one element of dev each iteration. It is like

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 的列.

matplot(x, X) will plot columns of X one by one, against x.

这篇关于两种正态分布的混合物的图密度曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆