Search code examples
rhistogramprobability-distribution

Histogram for probability distribution in R


I am trying to figure out how to draw a histogram for the probability distribution over the number of 6s when rolling five dice. My code in R looks like this:

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)

probability distribution


Solution

  • You may try

    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)
    

    enter image description here