Source code for spm1d.plot._effects


# Copyright (C) 2026  Todd Pataky

'''
Effect panels for ANOVA results.
'''

import numpy as np
from . import _style


_LS = ['-', '--', ':', '-.']


def _factor(spm, name):
    from .. exceptions import SPM1DError
    for f in spm.design.factors:
        if f.name_s == name:
            return f
    raise SPM1DError( f'The design has no factor "{name}". Its factors are {[f.name_s for f in spm.design.factors]}.' )


def _effect_factors(spm):
    '''
    Factors involved in an effect (e.g., ``A:B``).
    '''
    from .. exceptions import SPM1DError
    design = getattr( spm, 'design', None )
    if (design is None) or not getattr( design, 'factors', None ):
        raise SPM1DError( 'Effect plots need an ANOVA result. This SPM has no design factors.' )
    name = spm._name_short
    if (name is None) or (name == 'UnnamedContrast'):
        raise SPM1DError( f'Cannot read the factors of effect "{spm.name}".' )
    return [ _factor( spm, part )  for part in str(name).split(':') ]


def _level_colors(spm):
    '''
    One color per factor level.
    '''
    from matplotlib import pyplot as plt
    cmap   = plt.get_cmap( 'Dark2' )
    out, i = {}, 0
    for f in spm.design.factors:
        if f.name_s == 'SUBJ':
            continue
        out[f.name_s] = [ cmap( (i + k) % cmap.N )  for k in range(len(f.u)) ]
        i += len( f.u )
    return out


def _cellmean(y, factors, levels):
    i = np.ones( y.shape[0], dtype=bool )
    for f, u in zip( factors, levels ):
        i &= (f.A == u)
    return y[i].mean( axis=0 )


def _panel_means(ax, y, factors, colors):
    '''
    Cell means averaged over the other factors.
    '''
    f0     = factors[0]
    rest   = factors[1:]
    import itertools
    for i, u0 in enumerate( f0.u ):
        for combo in itertools.product( *[f.u for f in rest] ):
            m      = _cellmean( y, factors, (u0,) + combo )
            lab    = ' '.join( [f0.unames[i]] + [f.unames[list(f.u).index(u)]  for f, u in zip(rest, combo)] )
            ls     = _LS[ list(rest[0].u).index(combo[0]) % len(_LS) ] if rest else '-'
            lw     = (2.5 - 1.0 * list(rest[1].u).index(combo[1]))  if len(rest) > 1 else 1.5
            ax.plot( m, color=colors[i % len(colors)], ls=ls, lw=max(lw, 0.8), label=lab )


def _panel_differences(ax, y, factors, colors):
    '''
    Differences from the first level of the first factor.
    '''
    f0     = factors[0]
    rest   = factors[1:]
    if not rest:
        _panel_means( ax, y, factors, colors )
        return
    import itertools
    #  Color shows the second factor's level. Linestyle shows which level of
    #  the first factor is compared. For a three-way effect linestyle also
    #  shows the third factor's level.
    for combo in itertools.product( *[f.u for f in rest] ):
        m0  = _cellmean( y, factors, (f0.u[0],) + combo )
        at  = ' '.join( f.unames[list(f.u).index(u)]  for f, u in zip(rest, combo) )
        j   = list( rest[0].u ).index( combo[0] )
        for k, uk in enumerate( f0.u[1:] ):
            d   = _cellmean( y, factors, (uk,) + combo ) - m0
            i   = k if (len(rest) == 1) else ( list(rest[1].u).index(combo[1]) + k * len(rest[1].u) )
            ax.plot( d, color=colors[j % len(colors)], ls=_LS[i % len(_LS)],
                     label=f'{f0.unames[k + 1]} - {f0.unames[0]}  at {at}' )


def _datum(ax):
    '''
    Dotted line at zero (plotted only if zero lies within the y limits).
    '''
    ax.autoscale_view()
    y0, y1 = ax.get_ylim()
    if y0 <= 0 <= y1:
        ax.axhline( 0, color=_style.ink(), ls=':', lw=0.8 )


def _bar_axes(ax, size='12%', pad=0.06):
    '''Narrow axes beneath ``ax`` sharing its x axis.'''
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    axb = make_axes_locatable( ax ).append_axes( 'bottom', size=size, pad=pad, sharex=ax )
    ax.tick_params( axis='x', labelbottom=False )
    return axb


[docs] def plot_effect(spm, ax=None, style='means', color=None, bars=True, pvalues=True, legend=True, title=True, **kwargs): ''' Plot ANOVA effect data and clusters. :Parameters: - *spm* --- one ANOVA effect - *ax* --- axes [default: matplotlib.pyplot.gca()] - *style* --- ``'means'`` (default) or ``'differences'`` - *color* --- cluster band, bar and title color - *bars* --- if True (default), add a cluster bar strip beneath the panel (inference results only) - *pvalues* --- write cluster p values above the bars - *legend* --- plot the legend - *title* --- panel title (True, a string or False) - *kwargs* --- passed to line plots :Returns: - ``(ax, axb)`` --- panel axes and bar axes (None if no bars) :Example: The interaction panel of a simulated 2 x 3 ANOVA in the ``differences`` style. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.SPM1D_ANOVA2_2x3() >>> y = dataset.y # (60,101) array >>> A, B = dataset.x.T # (60,) arrays >>> spmi = spm1d.stats.anova2( y, A, B ).inference( 0.05 ) >>> ax, axb = spm1d.plot.plot_effect( spmi[2], style='differences' ) # equivalent to spmi[2].plot_effect( style='differences' ) >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt if spm.dim != 1: from .. exceptions import SPM1DNotImplementedError raise SPM1DNotImplementedError( 'Effect plots are for 1D results. This result is 0D.' ) ax = plt.gca() if (ax is None) else ax factors = _effect_factors( spm ) y = np.asarray( spm.fit.y ) if style not in ('means', 'differences'): from .. exceptions import SPM1DError raise SPM1DError( f'"style" must be "means" or "differences", not {style!r}.' ) ind = getattr( spm._teststat, 'ind', None ) color = ( 'C%d' % (ind or 0) ) if (color is None) else color levels = _level_colors( spm ) # Cell means are colored by the first factor's levels and differences by # the second's because they are taken within the first. A main effect uses # its own factor. lead = factors[0] if (style == 'means' or len(factors) == 1) else factors[1] lines = levels[ lead.name_s ] n = len( lead.u ) if (style == 'means' or len(factors) == 1) else int( np.prod([len(f.u) for f in factors[1:]]) ) if style == 'means': _panel_means( ax, y, factors, lines ) else: _panel_differences( ax, y, factors, lines ) _datum( ax ) axb = None if spm.isinference: from . _clusters import plot_cluster_patches, plot_cluster_bars plot_cluster_patches( spm, ax=ax, color=color ) if bars: axb = _bar_axes( ax ) plot_cluster_bars( spm, ax=axb, color=color, pvalues=pvalues ) if legend: ax.legend( fontsize=7, ncol=1 if n <= 4 else 2 ) if title is True: ax.set_title( 'Effect: ' + spm.name, color=color ) elif title: ax.set_title( str(title), color=color ) ax.set_xlim( 0, spm.Q - 1 ) return ax, axb
def _layout(n): ''' Panel positions: main effects on the first row and interactions on the next. ''' if n <= 3: return 1, n, [ (0, i) for i in range(n) ] if n == 7: return 2, 4, [ (0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (1, 3) ] ncol = int( np.ceil( np.sqrt(n) ) ) return int( np.ceil(n / ncol) ), ncol, [ (i // ncol, i % ncol) for i in range(n) ]
[docs] def plot_effects(FF, style='means', colors=None, fig=None, figsize=None, bars=True, pvalues=True, legend=True, **kwargs): ''' One panel per ANOVA effect. :Parameters: - *FF* --- ANOVA result list - *style* --- ``'means'`` (default) or ``'differences'`` (see plot_effect) - *colors* --- one color per effect [default: ``'C0'``, ``'C1'``, ...] - *fig* --- figure [default: new figure] - *figsize* --- new figure size - *bars*, *pvalues*, *legend* --- see plot_effect :Returns: - ``(axs, axbs)`` --- panel axes and bar axes :Example: One panel per effect of a simulated 2 x 3 ANOVA. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.SPM1D_ANOVA2_2x3() >>> y = dataset.y # (60,101) array >>> A, B = dataset.x.T # (60,) arrays >>> spmi = spm1d.stats.anova2( y, A, B ).inference( 0.05 ) >>> axs, axbs = spm1d.plot.plot_effects( spmi ) # equivalent to spmi.plot_effects() >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt n = len( FF ) if n == 0: from .. exceptions import SPM1DError raise SPM1DError( 'The list holds no results.' ) if FF[0].dim != 1: from .. exceptions import SPM1DNotImplementedError raise SPM1DNotImplementedError( 'Effect plots are for 1D results. This result is 0D.' ) colors = [ 'C%d' % i for i in range(n) ] if (colors is None) else list( colors ) nrow, ncol, pos = _layout( n ) if fig is None: fig = plt.figure( figsize=(3.6 * ncol + 1, 3.4 * nrow + 0.5) if (figsize is None) else figsize ) gs = fig.add_gridspec( nrow, ncol, hspace=0.45, wspace=0.3 ) axs, axbs = [], [] for F, c, (i, j) in zip( FF, colors, pos ): ax = fig.add_subplot( gs[i, j] ) ax, axb = plot_effect( F, ax=ax, style=style, color=c, bars=bars, pvalues=pvalues, legend=legend, **kwargs ) axs.append( ax ) axbs.append( axb ) return axs, axbs