Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created October 4, 2020 02:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/1aaffa49ba0fd85ef0150b33a92efe0b to your computer and use it in GitHub Desktop.
Save andrewheiss/1aaffa49ba0fd85ef0150b33a92efe0b to your computer and use it in GitHub Desktop.
library(tidyverse)
library(broom)
library(latex2exp)
library(patchwork)
set.seed(1234)

logit_df <- tibble(x = seq(-5, 5, length.out = 100)) %>% 
    mutate(p = 1/(1 + exp(-x))) %>% 
    mutate(y = rbinom(n(), size = 1, prob = p))

example_logit <- glm(y ~ x, data = logit_df, family = binomial(link = "logit"))

logit_df_odds <- augment_columns(example_logit, logit_df,
                                    type.predict = c("link")) %>% 
    rename(log_odds = .fitted) %>% 
    mutate(odds_ratio = exp(log_odds))

logit_df_probs <- augment_columns(example_logit, logit_df,
                                    type.predict = c("response")) %>% 
    rename(pred_prob = .fitted)

plot_log_odds <- ggplot(logit_df_odds, aes(x = x, y = log_odds)) +
    geom_path(color = "#771C6D", size = 2) +
    labs(title = "Log odds (β)", 
        subtitle = "This is linear!",
        x = NULL,
        y = TeX("$log \\frac{p}{1 - p}$")) +
    theme_minimal() +
    theme(plot.title = element_text(face = "bold"))

plot_odds <- ggplot(logit_df_odds, aes(x = x, y = odds_ratio)) +
    geom_path(color = "#FB9E07", size = 2) +
    labs(title = "Odds (exp(β))", 
        subtitle = "This is curvy, but it's a mathy transformation of a linear value",
        x = NULL,
        y = TeX("$\\frac{p}{1 - p}$")) +
    theme_minimal() +
    theme(plot.title = element_text(face = "bold"))

plot_probs <- ggplot(logit_df_probs, aes(x = x, y = pred_prob)) +
    geom_path(color = "#CF4446", size = 2) +
    labs(title = "Predicted probabilities", 
        sutitle = "Plug values of X into ",
        x = "X (value of explanatory variable)",
        y = TeX("\\hat{P(Y)} = \\frac{odds}{1 + odds}")) +
    theme_minimal() +
    theme(plot.title = element_text(face = "bold"))

plot_log_odds / plot_odds / plot_probs

Created on 2020-10-03 by the reprex package (v0.3.0)

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