Reputation: 2994
Im new to R.
Im trying to plot normal probability density function for the mean of 1000 sample values that are from exponential distributions of size 40 each. The distribution of sample means should be approximately normal.
Problem that Im having is with how the plot is rendered, see below:
Here is my "R" code:
#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))
Approach #1 for plotting:
plot(meanOfSampleMeansVector,propDensity, xlab="x value", type="l",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
Result:
Approach #2 for plotting:
plot(meanOfSampleMeansVector,propDensity, xlab="x value",
ylab="Density", main="Sample Means of Exponential Distribution",col="red")
Result:
However what I want is something similar to this graph:
Upvotes: 0
Views: 2132
Reputation: 3888
The problem in approach #1 is simply that the sample isn't sorted:
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")
But I strongly recommend, that you take a look at density()
instead if you want to plot the estimated pdf (here added to the same plot):
lines(density(meanOfSampleMeansVector),col=1)
or maybe just use a normal quantile plot if you want to verify the CLT:
qqnorm(S)
qqline(S)
Upvotes: 0
Reputation: 1538
Base graphics can do this just as well:
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")
Upvotes: 0
Reputation: 326
require(ggplot2)
qplot(meanOfSampleMeansVector,propDensity,geom="line")+
xlab("x value")+ylab("Density")+
ggtitle("Sample Means of Exponential Distribution")
I do it with ggplot2
Upvotes: 1