我是R的新手。
我试图绘制正常概率密度函数,用于1000个样本值的平均值,这些样本值来自每个大小为40的指数分布。样本均值的分布应近似正常。
我遇到的问题是如何渲染绘图,见下文:
这是我的“R”代码:
#allocate list size to store means
meanOfSampleMeansVector <- numeric(1000)
#for 1000 iterations create 40 exponential random variable with variance of 0.2 units
for (i in 1:1000 ){
sample <- rexp(n=40,0.2)
#get mean of sample
meanOfSample <- mean(sample)
#set the mean in list
meanOfSampleMeansVector[i] <- meanOfSample
}
propDensity=dnorm(meanOfSampleMeansVector,mean(meanOfSampleMeansVector),sd(meanOfSampleMeansVector))
方法#1用于绘图:
plot(meanOfSampleMeansVector,propDensity, xlab="x value", type="l",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
结果:
方法#2用于绘图:
plot(meanOfSampleMeansVector,propDensity, xlab="x value",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
结果:
但我想要的是与此图类似的内容:
答案 0 :(得分:1)
require(ggplot2)
qplot(meanOfSampleMeansVector,propDensity,geom="line")+
xlab("x value")+ylab("Density")+
ggtitle("Sample Means of Exponential Distribution")
我使用ggplot2
答案 1 :(得分:0)
基础图形也可以这样做:
xval <- seq(min(meanOfSampleMeansVector), max(meanOfSampleMeansVector), length=200)
propDensity=dnorm(xval, mean(meanOfSampleMeansVector), sd(meanOfSampleMeansVector))
plot(xval,propDensity, xlab="x value", type="l",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
答案 2 :(得分:0)
方法#1中的问题仅仅是样本没有排序:
S<-sort(meanOfSampleMeansVector)
propDensity=dnorm(S,mean(S),sd(S))
plot(S,propDensity, xlab="x value", type="l",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
但我强烈建议,如果你想绘制估计的pdf(这里添加到同一个图中),你可以看看density()
:
lines(density(meanOfSampleMeansVector),col=1)
或者如果你想验证CLT,可能只使用正常的分位数图:
qqnorm(S)
qqline(S)