A
A
Andrey Goroshko2019-10-03 19:41:12
R
Andrey Goroshko, 2019-10-03 19:41:12

How to plot a binomial distribution in R?

I need to draw a binomial distribution plot with 100000 tries. The chart should consist of the line chart itself and the histogram. I do like this:

library(tidyverse)
summarize.binomial.observations <- function(trials, theta, observations) {
  sample.space <- c(1,0)
  results <- 1:observations %>%
  map_int(function(x)
    as.integer(
      sum(
        sample(sample.space, size = trials, replace = TRUE, prob = c(theta, 1 - theta))
      )
    )
  )
  return(results)
}
summary <- summarize.binomial.observations(80, 0.6, 5000)
resulting.df <- data.frame(flips <- summary) # ggplot only works with data frames
names(resulting.df) <- c("flips")
#binPDF <- data.frame(x<-1:80, y<-dbinom(1:80, size=80, prob = 0.6))
#names(binPDF) <- c("flips", "prob")
ggplot(resulting.df) + 
  geom_histogram(breaks=seq(1, 80, 2), aes(x=flips, y=..density..), position="identity",,colour = 'blue', fill = 'white') + 
  geom_density(aes(x=flips, y = ..density..), colour="red")

and I get this:
5d9624294d8cc255430971.jpeg
as you can see from the graph, everything is fine, but it’s not :( I need the histogram to have sooo many histogram bars, but it doesn’t turn out very much and I can’t figure out how to increase the number of attempts in the histogram either. Maybe I'm doing something wrong or I have a fundamentally wrong approach?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zexer, 2019-10-07
@Drew20

To increase the number of columns in a distribution histogram (for ggplot), use the bins parameter inside geom_histogram.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question