
// Simulate data
clear
set seed 1
set obs 500
generate e = 0 + (500 - 0) * runiform() // To generate random variates over the
generate x1 = 0 + (800 - 0) * runiform() // interval [a,b), a+(b-a)*runiform()
generate x2 = round(0 + (1 - 0) * runiform()) // Binary variable
generate y = (x1 + x2 + (x1*x2) + e) / 1000
// Calculations for Aiken & West (1991) style plot
regress y c.x1##x2
qui sum x1
local x1_minsd = r(mean) - (2*r(sd))
local x1_mean = r(mean)
local x1_plusd = r(mean) + (2*r(sd))
// Calculate predicted values for plot
margins, at(c.x1 = (`x1_minsd' `x1_mean' `x1_plusd') ///
c.x2 = (0 1)) vsquish
// Plot
qui marginsplot, recastci(rarea) ciopts(color(gs10)) ///
title("Interaction plot with overlaid data points") ///
ytitle("y") ///
ylabel(, format(%6.1f)) ///
xtitle("") ///
plotopts(msymbol(none)) /// // Turn off markers
plot1opts(lpattern(longdash)) /// // Define line types here
plot2opts(lpattern(solid)) ///
addplot(scatter y x1 ///
, symbol(o) ///
xlabel(`x1_minsd' "-2 SD" /// // The addplot seems to override
`x1_mean' "Average x1" /// // the regular axis label
`x1_plusd' "+2 SD") /// // command
legend(subtitle(x2) /// // And the legend command
order(3 "x2 = 0" 4 "x2 = 1" 2 "95 % CI"))) ///
legend(pos(5) ring(0)) /// // But not completely
name(plot, replace)