Skip to content

Instantly share code, notes, and snippets.

@grantmcdermott
Created December 27, 2019 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantmcdermott/d86af2b8f21f4082595c0e717eea5a90 to your computer and use it in GitHub Desktop.
Save grantmcdermott/d86af2b8f21f4082595c0e717eea5a90 to your computer and use it in GitHub Desktop.
Examples of how to plot multiple coefficients from multiple models (using ggplot2 and broom::tidy)
## Context: https://twitter.com/grant_mcdermott/status/1210654424600731648
library(tidyverse)
library(broom)
library(hrbrthemes) ## theme(s) I like
df =
mtcars %>%
mutate(vs = factor(vs), am = factor(am))
fit1 = lm(mpg ~ vs * am * wt, data = df)
fit1_coefs = tidy(fit1, conf.int = T)
fit2 = lm(mpg ~ vs / am / wt, data = df)
fit2_coefs = tidy(fit2, conf.int = T)
## Option 1: Facet by model
bind_rows(
fit1_coefs %>% mutate(model = "Partial MEs"),
fit2_coefs %>% mutate(model = "Full MEs")
) %>%
filter(grepl("wt", term)) %>%
## Optional regexp work to make plot look nicier
mutate(
am = ifelse(grepl("am1", term), "Automatic", "Manual"),
vs = ifelse(grepl("vs1", term), "V-shaped", "Straight"),
x_lab = paste(am, vs, sep="\n")
) %>%
ggplot(aes(x=x_lab, y=estimate, ymin=conf.low, ymax=conf.high)) +
geom_pointrange() +
geom_hline(yintercept = 0, col = "orange") +
labs(
x = NULL, y = "Marginal effect (Δ in MPG : Δ in '000 lbs)",
title = " Marginal effect of vehicle weight on MPG",
subtitle = "Conditional on transmission type and engine shape"
) +
facet_wrap(~ model) +
theme_ipsum()
## Option 2: Share plot area, but use position dodge and colouring
bind_rows(
fit1_coefs %>% mutate(model = "Partial MEs"),
fit2_coefs %>% mutate(model = "Full MEs")
) %>%
filter(grepl("wt", term)) %>%
## Optional regexp work to make plot look nicier
mutate(
am = ifelse(grepl("am1", term), "Automatic", "Manual"),
vs = ifelse(grepl("vs1", term), "V-shaped", "Straight"),
x_lab = paste(am, vs, sep="\n")
) %>%
ggplot(aes(x=x_lab, y=estimate, ymin=conf.low, ymax=conf.high)) +
geom_pointrange(aes(col = model), position = position_dodge(width = 0.5)) +
geom_hline(yintercept = 0, col = "black") +
labs(
x = NULL, y = "Marginal effect (Δ in MPG : Δ in '000 lbs)",
title = " Marginal effect of vehicle weight on MPG",
subtitle = "Conditional on transmission type and engine shape"
) +
theme_ipsum()
@samuelsaari
Copy link

This is awesome, thank you!

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