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)