Skip to content

Instantly share code, notes, and snippets.

@expersso
Created January 22, 2019 13:40
Show Gist options
  • Save expersso/ed09a658011f81967414306cb19ceb54 to your computer and use it in GitHub Desktop.
Save expersso/ed09a658011f81967414306cb19ceb54 to your computer and use it in GitHub Desktop.
PMF and likelihood of binomial RV
library(tidyverse)
library(patchwork)
strip_lblr <- function(s) as_labeller(function(x) paste0(s, " = ", x))
p_brks <- seq(0, 1, .25) %>% set_names() %>% set_names(MASS::fractions(.))
x <- 4
df <- crossing(k = 0:x, p = seq(0, 1, .05)) %>%
mutate(PX_k = dbinom(k, x, p))
ml_estimates <- tibble(k = 0:x, p = k / x, L = dbinom(k, 4, p))
pmf_binom <-
ggplot(filter(df, p %in% c(0, .25, .5, .75, 1))) +
geom_col(aes(x = k, y = PX_k), fill = "sienna2", color = "white") +
facet_wrap(~p, labeller = strip_lblr("p"), nrow = 1) +
scale_x_continuous(breaks = unique(df$k)) +
scale_y_continuous(expand = c(0, 0)) +
labs(subtitle = "Probability mass function: P(X = k | p)", y = NULL)
lik_binom <-
ggplot(df) +
geom_line(aes(x = p, y = PX_k), color = "sienna2") +
geom_point(aes(x = p, y = L), ml_estimates, color = "blue", size = rel(0.5)) +
facet_wrap(~k, labeller = strip_lblr("k"), nrow = 1) +
scale_x_continuous(breaks = p_brks) +
scale_y_continuous(expand = expand_scale(c(0.02, 0.04))) +
theme(plot.caption = element_text(size = 8)) +
labs(subtitle = "Likelihood function: L(p | X = k)", y = NULL,
caption = expression(
"Blue dots indicate " ~ L(hat(p) ~ "|" ~ X == k) ~
", where " ~ hat(p) == frac(k,n) ~ " is the maximum likelihood estimator."))
pmf_binom / lik_binom *
theme_classic(base_size = 11, base_line_size = 0.1) *
theme(strip.background = element_blank()) +
plot_annotation("X ~ Binomial(4, p)")
@expersso
Copy link
Author

image

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