【问题标题】:R Creating Normal Distribution Plot using datasetR使用数据集创建正态分布图
【发布时间】:2014-11-12 10:43:42
【问题描述】:

我是 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")

结果:

但是我想要的是类似于这张图的东西:

【问题讨论】:

    标签: r plot statistics


    【解决方案1】:

    方法#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")
    

    但我强烈建议您查看density(),而不是如果您想绘制估计的 pdf(此处添加到同一图中):

    lines(density(meanOfSampleMeansVector),col=1)
    

    如果您想验证 CLT,也可以只使用正常的分位数图:

    qqnorm(S)
    qqline(S) 
    

    【讨论】:

      【解决方案2】:

      基础图形也可以做到这一点:

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

      【讨论】:

        【解决方案3】:
        require(ggplot2)
        qplot(meanOfSampleMeansVector,propDensity,geom="line")+
          xlab("x value")+ylab("Density")+
          ggtitle("Sample Means of Exponential Distribution")
        

        我用ggplot2 来做

        【讨论】:

          猜你喜欢
          • 2021-10-31
          • 1970-01-01
          • 1970-01-01
          • 2017-11-02
          • 1970-01-01
          • 2014-02-03
          • 1970-01-01
          • 2021-04-16
          • 1970-01-01
          相关资源
          最近更新 更多