R add tweaks to interaction plot with ggplot

Viewed 312

I would like to modify this graph:

  • Shorten the lines to only display from -1 SD to + 1SD for the weight variable
  • Cap each line with a square or triangle symbol
  • Change the x-axis to display Low weight and High weight instead of the digits and tick marks.
library(tidyverse)
dat=mtcars
mod <- lm(mpg ~ gear * wt, data=dat)

apatheme=theme_bw()+
  theme(panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        panel.border=element_blank(),
        axis.line=element_line(),
        text=element_text(family='Times'),
        legend.title=element_blank())

p=ggplot(dat, aes(x = wt, y = mpg, size = gear))+
  geom_blank()+
  labs(x = 'Vehicle Weight', y = 'Vehicle MPG')+
  scale_size_continuous(guide = FALSE)+
  geom_abline(aes(intercept=33.965, slope=-4.3985, linetype='-1SD Gear'))+
  geom_abline(aes(intercept=42.2767, slope=-7.3095, linetype='+1SD Gear'))+
  scale_linetype_manual(values=c('dotted','dashed','solid'),
                        breaks=c('-1SD Gear','Mean Gear','+1SD Gear'),name='Simple\nSlope')+
  apatheme
p

Here is what it currently produces

enter image description here

I am trying to get it closer to this APA style version

enter image description here

1 Answers

Since you want to plot based on SD difference from the mean, would start with calculating mean and SD on your variables on interest. You can then construct a data frame containing the points you want to include for specific values of gear and wt.

Instead of using numbers for slope/intercept, would predict values of mpg based on gear and wt using your model mod.

I added some factors/labels based on your desired figure.

library(tidyverse)
library(ggplot2)

dat=mtcars
mod <- lm(mpg ~ gear * wt, data=dat)

dat_sum <- do.call(data.frame, aggregate(. ~ 1, dat, function(x) c(mean = mean(x), sd = sd(x))))

df <- data.frame(
  gear = with(dat_sum, c(gear.mean - gear.sd, gear.mean + gear.sd, gear.mean - gear.sd, gear.mean + gear.sd)),
  gear_lab = factor(c("Low Gears", "High Gears", "Low Gears", "High Gears"), levels = c("Low Gears", "High Gears")),
  wt = with(dat_sum, c(wt.mean - wt.sd, wt.mean - wt.sd, wt.mean + wt_sd, wt.mean + wt.sd)),
  wt_lab = factor(c("Low Weight", "Low Weight", "High Weight", "High Weight"), levels = c("Low Weight", "High Weight")))

df$mpg <- predict(mod, df)

apatheme=theme_bw()+
  theme(panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        panel.border=element_blank(),
        axis.line=element_line(),
        text=element_text(family='Times'),
        legend.title=element_blank())

ggplot(df, aes(x = wt_lab, y = mpg, group = gear_lab))+
  geom_point(aes(shape = gear_lab))+
  geom_line(aes(linetype = gear_lab))+
  ylim(0,30)+
  labs(x = 'Vehicle Weight', y = 'Vehicle MPG')+
  scale_shape_manual(values = c(15, 17))+
  scale_linetype_manual(values = c('dotted', 'dashed'))+
  apatheme

Plot

APA style plot

Related