R中概率分布的直方图

Histogram for probability distribution in R

我想弄清楚如何绘制掷五个骰子时出现 6 的概率分布的直方图。我在 R 中的代码如下所示:

library(polynom)
library(ggplot2)
library(gridExtra)

pd <- function(n){
  s = 6
  p<-polynomial(c(0,rep(1/s,s)))
  k <- data.frame(as.vector(p^n)[-(1:n)])
  k$no <- n:(s*n)
  names(k)[1] <- "p"
  ggplot(data.frame(k)) +
    geom_bar(stat = "identity",aes(no, p), size = 1, fill = "orange", col = "black") +
    labs(title = paste(n, ifelse(n == 1,"die roll", "dice rolls"), sep = " "),
         x = "Outcome", y = "Probability")
}

grid.arrange(pd(5), ncol =2)

你可以试试

library(stats)
pd <- function(n){
  df <- data.frame(
    prob = dbinom(0:n, n, 1/6),
    m = 0:n
  )
  ggplot(df, aes(m, prob)) +
    geom_col(fill = "steelblue") +
    geom_line(color = "red", lwd = 1)
}
pd(5)