Two-way ANOVA#
A two-way ANOVA assesses the main effects of two factors (A and B) and their
interaction effect (AB). Two- and three-way ANOVA procedures return
a list of results spms which contains one SPM object for each effect:
spms.effect_labelslists all effect namesspms['Main A']accesses a single effect by namespms[0]accesses a single effect by indexspms.plot()plots all effects in separate panels
The example below uses the simulated dataset SPM1D_ANOVA2_2x3. It has two
levels of factor A and three levels of factor B. Interpreting these results
may require cell means (i.e., one mean for each combination of factor
levels) as shown at the end of this example.
import numpy as np
from matplotlib import pyplot as plt
import spm1d
import jikudata as jd
plt.rc( 'font', size=18 ) # minimum font size for all figure text
dataset = jd.SPM1D_ANOVA2_2x3() # 1D dataset: 2 x 3 design
y = dataset.y # (60,101) array of observations
A, B = dataset.x.T # factor A and factor B labels
spms = spm1d.stats.anova2( y, A, B ).inference( 0.05 )
print( spms.effect_labels )
('Main A', 'Main B', 'Interaction A:B')
The figure below depicts the F statistic (solid line) and critical threshold (dashed line) for each effect (the main effects of A and B and their interaction AB). In this dataset only the main effect of B is significant.
plt.figure( figsize=(8, 5.6) )
spms.plot( plot_threshold_label=False, plot_p_values=False )
for ax, label in zip( plt.gcf().axes, spms.effect_labels ):
ax.set_title( label.split()[-1], fontsize=26 ) # short effect names: A, B, AB, ...
ax.set_ylabel( '' )
ax.set_xticks( [] ); ax.set_yticks( [] ) # tick labels omitted: the panels are small
plt.tight_layout()


The figure below depicts all six cell means.
plt.figure( figsize=(11, 4.5), tight_layout=True )
ax = plt.gca()
for a in (0, 1):
for b, ls in zip( (0, 1, 2), ('-', '--', ':') ):
ax.plot( y[(A == a) & (B == b)].mean( axis=0 ), lw=3, color=['C0', 'C3'][a], ls=ls, label=f'A{a}, B{b}' )
ax.legend( fontsize=18, loc='upper left', bbox_to_anchor=(1.01, 1) ) # outside the axes, on the right


The figure below depicts cell means at the domain point where the main effect of B is largest.
q = int( np.argmax( spms['Main B'].z ) ) # domain point with the largest F value for the main effect of B
plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
for a, marker in zip( (0, 1), 'os' ):
m = [ y[(A == a) & (B == b)][:, q].mean() for b in (0, 1, 2) ]
ax.plot( [0, 1, 2], m, marker + '-', color=['C0', 'C3'][a], lw=2, label=f'A{a}' )
ax.set_xticks( [0, 1, 2] )
ax.set_xticklabels( ['B0', 'B1', 'B2'] )
ax.set_ylabel( f'Cell mean at q = {q}', fontsize=20 )
ax.legend( fontsize=20, loc='upper center' )

