6.5 Coefficient plots: Coloring
- Figure 6.3 below provides a coefficient plot and colors estimations for subsets.

Figure 6.3: Coefficient plot: Coloring
6.5.1 Lab: Data & code
The logic of estimating the models is the same as in the section [Coefficient plots: Facetting]. The only difference is that we use another variable namely Infant.Mortality_cat
.
swiss <- swiss %>%
mutate(Infant.Mortality_cat = cut(Infant.Mortality,
breaks = quantile(Infant.Mortality, probs = seq(0, 1, 0.5)),
labels = c("low", "high")))
#table(swiss$Infant.Mortality, swiss$Infant.Mortality_cat)
results <- swiss %>%
filter(!is.na(Infant.Mortality_cat)) %>%
select(Infant.Mortality_cat, Fertility, Agriculture, Education, Catholic) %>%
nest(data = c(Fertility, Agriculture, Education, Catholic)) %>%
mutate(fit = map(data, ~ lm(Fertility ~ Catholic + Agriculture + Education, data = .)),
results = map(fit, tidy),
results_90 = map(fit, conf.level = 0.90, confint_tidy),
results_95 = map(fit, conf.level = 0.95, confint_tidy)) %>%
mutate(results_90 = map(results_90, ~ rename_all(., function(x){paste(x, "_90", sep="")})),
results_95 = map(results_95, ~ rename_all(., function(x){paste(x, "_95", sep="")}))) %>%
unnest(c(results, results_90, results_95)) %>%
rename(Variable = term,
Coefficient = estimate,
SE = std.error) %>%
filter(Variable != "(Intercept)")
Plotting the data is straightforward again. We use the same code as above but now instead of facetting we simply specify colour = Infant.Mortality_cat
within aes()
.
# GGPLOT
ggplot(results, aes(x = Variable, y = Coefficient, colour = Infant.Mortality_cat)) +
geom_hline(yintercept = 0, colour = gray(1/2), lty = 2) +
geom_point(aes(x = Variable,
y = Coefficient), position=position_dodge(width=0.3)) +
geom_linerange(aes(x = Variable,
ymin = conf.low_90,
ymax = conf.high_90),
lwd = 1, position=position_dodge(width=0.3)) +
geom_linerange(aes(x = Variable,
ymin = conf.low_95,
ymax = conf.high_95),
lwd = 1/2, position=position_dodge(width=0.3)) +
ggtitle("Outcome: Fertility (Subsets: Infant.Mortality)") +
coord_flip()