Created
December 27, 2019 20:26
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome, thank you!