Skip to content

Instantly share code, notes, and snippets.

@expersso
Last active December 8, 2015 11:49
Show Gist options
  • Save expersso/9a9547331350e8fc0cb2 to your computer and use it in GitHub Desktop.
Save expersso/9a9547331350e8fc0cb2 to your computer and use it in GitHub Desktop.
Binomial distributions
library(ggplot2)
library(dplyr)
probs <- seq(0.05, 0.95, each = 0.05)
df <- lapply(probs, rbinom, n = 100, size = 100) %>%
unlist() %>%
data.frame("successes" = .) %>%
mutate(probs = rep(probs, each = 100))
df_annotate <- df %>%
group_by(probs) %>%
summarise(top = max(density(successes)$y),
mid = density(successes)$x[which.max(density(successes)$y)])
ggplot(df, aes(x = successes, group = factor(probs), fill = probs)) +
geom_density(alpha = 0.75, color = "white") +
geom_text(aes(label = probs, x = mid, y = top), data = df_annotate,
vjust = 0, nudge_y = 0.001, size = 3) +
geom_segment(aes(x = mid, xend = mid, yend = top), y = 0, data = df_annotate,
linetype = "dashed", size = 0.25, color = "white") +
theme_bw(10) +
scale_fill_gradient(low = "red", high = "lightgreen") +
scale_y_continuous(expand = c(0, 0), limits = c(0, max(df_annotate$top) * 1.2)) +
labs(x = "\n# of successes", y = "Density\n", fill = "Probability\nof success",
title = "Simulated draws from binomial distributions")
@expersso
Copy link
Author

expersso commented Dec 8, 2015

rplot02

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment