Reputation: 197
I want to generate a chi squared distribution with 100,000 random numbers with degrees of freedom 3.
This is what I have tried.
df3=data.frame(X=dchisq(1:100000, df=3))
But output is not I have expected. I used below code to visualize it.
ggplot(df3,aes(x=X,y=..density..)) + geom_density(fill='blue')
Then the pdf looks abnormal. Please help
Upvotes: 3
Views: 5594
Reputation: 73272
You may use rchisq
to make random draws from a random X2 distribution as shown in the other answers.
dchisq
is the density distribution function, which you might find useful though, since you want to plot:
curve(dchisq(x, 3), xlim=0:1*15)
Upvotes: 1
Reputation: 10855
Use rchisq()
to create a distribution of 100,000 observations randomly drawn from a chi square distribution with 3 degrees of freedom.
df3=data.frame(X=rchisq(1:100000, df=3))
hist(df3$X)
...and the output:
The ggplot version looks like this:
library(ggplot2)
ggplot(data = df3, aes(X)) + geom_histogram()
Upvotes: 1
Reputation: 132864
Use rchisq
to sample from the distribution:
df3=data.frame(X=rchisq(1:100000, df=3))
ggplot(df3,aes(x=X,y=..density..)) + geom_density(fill='blue')
If your goal is to plot a density function, do this:
ggplot(data.frame(x = seq(0, 25, by = 0.01)), aes(x = x)) +
stat_function(fun = dchisq, args = list(df = 3), fill = "blue", geom = "density")
The latter has the advantage of the plot being fully deterministic.
Upvotes: 3