0
votes

I would like to use R to randomly construct chi-square distribution with the degree of freedom of 5 with 100 observations. After doing so, I want to calculate the mean of those observations and use ggplot2 to plot the chi-square distribution with a bar chart. The following is my code:

rm(list = ls())
library(ggplot2)
set.seed(9487)

###Step_1###
x_100 <-data.frame(rchisq(100, 5, ncp = FALSE))

###Step_2###
mean_x <- mean(x_100[,1])
class(x_100)

###Step_3###
plot_x_100 <- ggplot(data = x_100, aes(x = x_100)) +
  geom_bar()
plot_x_100

Firstly, I construct a data frame of a random chi-square distribution with df = 5, obs = 100.

Secondly, I calculate the mean value of this chi-square distribution.

At last, I plot the graph with the ggplot2 package.

However, I get the result like the follows:

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error in is.finite(x) : default method not implemented for type 'list'

I got stuck in this problem for several hours and cannot find any list in my global environment. It would be appreciated if anyone can help me and give me some suggestions.

1
The error is because you're passing the whole data.frame to the x aesthetic instead of the column of data. I would first label the column in x_100 (x_100 = data.frame(x_col = rchisq(100, 5, ncp = FALSE))). Then change the aes to aes(x=x_col). And if you just want a histogram, you might want to try geom_histogram instead of geom_bar - cookesd

1 Answers

2
votes

The problem is that inside the ggplot function you are calling the same dataframe (x_100) as both the data and the x variable inside aes. Remember that in ggplot, inside aes you should indicate the name of the column you wish to map. Additionally, if you want to plot the chi-square distribution I think it might be a better idea to use the geom_histogram instead of geom_bar, as the first one groups the observations into bins.

library(ggplot2)
# Rename the only column of your data frame as "value"
colnames(x_100) <- "value"
plot_x_100 <- ggplot(data = x_100, aes(x = value)) +
  geom_histogram(bins = 20) 

Histogram plot