7.1 Conditional and unconditional effects
You might reproduce Hayes’s Table 7.1 data like this.
library(tidyverse) d <- tibble(x = rep(-1:2, each = 3), w = rep(0:2, times = 4)) %>% mutate(A = 4 + 1*x + 2*w, B = 4 + 1*x + 2*w + 1.5*x*w)
In previous chapters, we alteried our plot themes using either built-in settings from ggplot2 or extra themes from the ggthemes package. When we wanted to change them further, we did so with extra
theme() arguments. One, it’s nice to be know how to make one’s own custom theme and, two, it’d be handy to condense our code a bit. Here we’ll take a few cues from the Building a New Theme and from Peng, Kross, and Anderson’s Mastering Software Development in R. We’ll make our own theme,
theme_07 by saving a handful of augmentations from the default
library(dutchmasters) theme_07 <- theme_gray() + theme(plot.background = element_rect(fill = dutchmasters$little_street), panel.background = element_rect(fill = dutchmasters$little_street), strip.background = element_rect(fill = alpha(dutchmasters$little_street, 2/3), color = "transparent"), legend.background = element_rect(fill = "transparent"), legend.key = element_rect(fill = "transparent", color = "transparent"), panel.grid = element_blank(), text = element_text(family = "Courier", color = dutchmasters$little_street, size = 14), axis.text = element_text(color = dutchmasters$little_street))
This chapter’s color palette comes from the dutchmasters package, which was itself based of Vermeer’s The Little Street. To get a quick glance at the full palette, we’ll also use
viz_palette(), a convenience function from the ochRe package.
With our new
theme_07 in hand, we’re ready for our version of Figure 7.2.
library(directlabels) d %>% gather(key, value, -x, -w) %>% rename(y = value) %>% mutate(label = str_c("W = ", w)) %>% ggplot(aes(x = x, y = y, group = w, size = w %>% as.factor(), label = label)) + geom_line(color = dutchmasters$little_street) + geom_dl(method = list(dl.trans(x = x + 0.2), "last.points", cex = 1, color = dutchmasters$little_street, fontfamily = "Courier")) + scale_size_manual(values = c(.5, .75, 1)) + coord_cartesian(xlim = c(-1, 2.6), ylim = 0:16) + labs(x = expression(italic("X")), y = expression(italic("Y"))) + facet_wrap(~key) + theme_07 + # because we didn't alter the `legend.position` argument in our `theme_07`, we need to use `theme()` to remove it theme(legend.position = "none")
geom_dl() form the directlabels package, which made it easy to insert the “W = \(i\)” labels to the right of the lines.
I played around with the annotation in Figure 7.4 for a while and it was just way more trouble than it was worth. If you’re ever inspired to work it out, please share your code.