The interaction.plot() function eases the plotting of summary statistics for a numeric response variable for combinations of factors. As a demonstration, we’ll consider miles-per-gallon as a function of the number of cylinders (4, 6 or 8) and transmission type (automatic, manual) for the vehicles included in the Motor Trend “mtcars” dataset; itself included as part of the base installation “datasets” package.
We’ll load the dataset, coerce the transmission type variable - “am” - to factor to make for a clearer legend, then create the interaction plot, via interaction.plot().
# load Motor Trends' cars dataset
data(mtcars)
# coerce "am" variable to factor with appropriate labels/levels. For the purposes of the plot,
# this is necessary only to ease labeling of the 'traces' for the legend.
mtcars$am <- factor(x = mtcars$am, labels = c("auto", "manual"))
interaction.plot(x.factor = mtcars$cyl, # variable to plot on x-axis
trace.factor = mtcars$am, # variable to specify "traces"; here, lines
response = mtcars$mpg, # variable to plot on y-axis
fun = median, # summary statistic to be plotted for response variable
type = "l", # type of plot, here "l" for lines
ylab = "Miles per gallon (mpg)",
xlab = "Cylinders (cyl)",
col = c("blue4", "red4"),
lty = 1, # line type
lwd = 2, # line width
trace.label = "Transmission", # label for legend
xpd = FALSE) #, # 'clip' legend at border