R: forループ中でカイ二乗分布を描く

forループ中でカイ二乗分布を描いて重ねる練習。

k = c(1, 3, 5, 10, 20)
color = c("red", "green", "blue", "brown", "purple")

for (i in 1:length(k)){
 curve(dchisq(x, k[i]), 0, 30, col = color[i], add = TRUE)
}

画像1

# ggplot 参考にさせていただいたサイト https://abcxyzonetwothree.hatenablog.com/entry/2018/09/23/164148
k = c(1,3,5,10,20)
color = c("red", "green", "blue", "brown", "purple")
n <- 100000
chi.x <- matrix(nrow=n, ncol = length(k))
for(i in 1:length(k)){
 chi.x[,i] <- rchisq(n = n, df = k[i]) #自由度iのカイ二乗分布からn個の乱数発生させる
}

library(ggplot2)
g <- ggplot()
for(i in 1:length(k)){
 data <- data.frame(chi.x)
 x2 <- data[,i]
 g <- g +
   geom_histogram(mapping = aes_string(x = x2), binwidth = 0.1, fill = color[i], alpha = 0.5)
}
g <- g +
 xlim(0,40)+ylim(0,4000) +
 labs(x="chi.square")
plot(g)

画像2