Skip to content

Instantly share code, notes, and snippets.

@mine-cetinkaya-rundel
Created March 1, 2018 03:36
Show Gist options
  • Save mine-cetinkaya-rundel/27c9c21453f65e2d6f655e4bc3a5a2c7 to your computer and use it in GitHub Desktop.
Save mine-cetinkaya-rundel/27c9c21453f65e2d6f655e4bc3a5a2c7 to your computer and use it in GitHub Desktop.
Plotting parallel regression lines
# Fit model with parallel lines (main effects only)
m_pr <- lm(log(price) ~ Surface + factor(artistliving), data = pp_Surf_lt_5000)
## Option 1
# Save regression coefficients in a tibble
m_pr_coefs <- m_pr %>%
tidy() %>%
select(term, estimate)
# Save regression coefficients separately as numeric values
deceased_int <- m_pr_coefs %>%
filter(term == "(Intercept)") %>%
select(estimate) %>%
pull()
living_int <- m_pr_coefs %>%
filter(term == "factor(artistliving)1" | term == "(Intercept)") %>%
select(estimate) %>%
pull() %>%
sum()
surf_slope <- m_pr_coefs %>%
filter(term == "Surface") %>%
select(estimate) %>%
pull()
# Plot lines with geom_abline
ggplot(data = pp_Surf_lt_5000,
aes(y = log(price), x = Surface, color = factor(artistliving))) +
geom_point(alpha = 0.3) +
geom_abline(intercept = deceased_int, slope = surf_slope, color = "#F57670", lwd = 1) +
geom_abline(intercept = living_int, slope = surf_slope, color = "#1FBEC3", lwd = 1) +
labs(x = "Surface", y = "Log(price)", color = "Living artist")
## Option 2
# Augment the data with model results, including fitted values
m_pr_aug <- augment(m_pr)
# Plot lines with geom_line for predicted values
ggplot(data = m_pr_aug, mapping = aes(y = log.price., x = Surface, color = factor.artistliving.)) +
geom_point(alpha = 0.3) +
geom_line(aes(y = .fitted), lwd = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment