Source code for spm1d.plot._clusters


'''
Cluster extent plots.
'''

# Copyright (C) 2026  Todd Pataky


import numpy as np
from . import _style


def _as_list(spmi):
    '''List of SPMi objects and their row labels.'''
    if isinstance( spmi, (list, tuple) ):
        spms   = list( spmi )
        labels = getattr( spmi, 'labels', None ) or getattr( spmi, 'effect_labels', None )
        if labels is None:
            labels = [ getattr(s, 'name', None) or str(i)  for i, s in enumerate(spms) ]
        return spms, list( labels )
    return [spmi], None


def _check_inference(spms):
    for s in spms:
        if not getattr( s, 'isinference', False ):
            from .. exceptions import SPM1DTypeError
            raise SPM1DTypeError( 'cluster plots need an inference result (the output of "inference"), not a raw SPM' )
        if getattr( s, 'dim', 1 ) == 0:
            from .. exceptions import SPM1DNotImplementedError
            raise SPM1DNotImplementedError( 'cluster plots are for 1D results. A 0D result has no clusters.' )


def _colors(color, n):
    if color is None:
        return [ _style.ink() ] * n
    if isinstance( color, (list, tuple) ) and not isinstance( color, str ) and len( color ) == n and n > 1:
        return list( color )
    if isinstance( color, (list, tuple) ) and len( color ) in (3, 4) and all( isinstance(v, (int, float)) for v in color ):
        return [ color ] * n                    # one RGB(A) tuple
    return [ color ] * n


def _segments(spmi):
    '''
    One broken_barh segment (start, width) per cluster of one result.
    '''
    clusters = getattr( spmi, 'clusters', None ) or []
    return [ c._bbar  for c in clusters ]


def _all_segments(spmi):
    '''All broken_barh segments of one result.'''
    clusters = getattr( spmi, 'clusters', None ) or []
    return [ seg  for c in clusters  for seg in c._bbars ]


#  Bars and bands are outlined in the axes background color so that clusters
#  less than a pixel apart keep a visible gap.
_SEPARATOR_LW = 1.5


def _separator(ax):
    '''
    Separator color for adjacent clusters.
    '''
    try:
        c = ax.get_facecolor()
    except Exception:
        c = None
    from matplotlib import colors as mcolors
    if c is None or mcolors.to_rgba( c )[3] == 0:
        c = _style.background()
    return c


def _ptext(p):
    return 'p < 0.001' if (p is not None and p < 0.001) else ( 'p = %.3f' % p if p is not None else '' )


def _colored_ticklabels(ax, ys, labels, label_colors, fontsize=None):
    '''
    Color y tick label parts as specified in ``label_colors``.
    '''
    from matplotlib.offsetbox import TextArea, HPacker, AnchoredOffsetbox
    ink = _style.ink()
    for yy, label in zip( ys, labels ):
        parts = []
        for i, tok in enumerate( str(label).split(' ') ):
            if i:
                parts.append( TextArea( ' ', textprops=dict(color=ink, fontsize=fontsize) ) )
            parts.append( TextArea( tok, textprops=dict(color=label_colors.get(tok, ink), fontsize=fontsize) ) )
        box = AnchoredOffsetbox( loc='center right', child=HPacker( children=parts, pad=0, sep=0 ), frameon=False,
                                 bbox_to_anchor=(-0.01, yy), bbox_transform=ax.get_yaxis_transform(), pad=0, borderpad=0 )
        ax.add_artist( box )
    ax.set_yticks( ys )
    ax.set_yticklabels( [''] * len(ys) )


[docs] def plot_cluster_bars(spmi, ax=None, color=None, height=None, labels=None, pvalues=False, fontsize=8, tidy=True, transform=None, y=None, label_colors=None, **kwargs): ''' Plot suprathreshold clusters as horizontal bars (one row per result). :Parameters: - *spmi* --- inference SPM or list of inference SPMs (one row per element) - *ax* --- axes [default: matplotlib.pyplot.gca()] - *color* --- one color for all bars or one color per row - *height* --- bar height [default: 0.35] - *labels* --- y tick labels (one per row) [default: list labels if present] - *pvalues* --- if True, write cluster p values above bars - *fontsize* --- p value font size - *tidy* --- if True (default), hide y ticks and top, left and right spines - *transform*, *y* --- for plotting inside another plot - *label_colors* --- dict mapping row label parts to colors (e.g., ``{'A0': 'C0', 'A1': 'C1'}``) :Returns: - axes :Example: A strip of cluster bars beneath a plot of the data. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.PlantarArchAngle() >>> y, A = dataset.y, dataset.x # (20,101) array and (20,) array >>> y0, y1 = y[ A == 0 ], y[ A == 1 ] >>> spmi = spm1d.stats.ttest_paired( y0, y1 ).inference( 0.05 ) >>> fig, (ax0, ax1) = plt.subplots( 2, 1, sharex=True, gridspec_kw=dict( height_ratios=[9, 1] ) ) >>> h0 = spm1d.plot.plot_mean_sd( y0, ax=ax0 ) >>> h1 = spm1d.plot.plot_mean_sd( y1, ax=ax0, linecolor='r', facecolor='r' ) >>> ax = spm1d.plot.plot_cluster_bars( spmi, ax=ax1 ) >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt ax = plt.gca() if (ax is None) else ax spms, lab0 = _as_list( spmi ) _check_inference( spms ) n = len( spms ) labels = lab0 if (labels is None) else list( labels ) colors = _colors( color, n ) if y is None: ys = [ float(n - i) for i in range(n) ] # first row on top h = 0.35 if (height is None) else float( height ) else: ys = [ float(y) ] * n if np.isscalar( y ) else [ float(v) for v in y ] h = 0.05 if (height is None) else float( height ) tkw = {} if (transform is None) else dict( transform=transform ) sep = _separator( ax ) for s, yy, c in zip( spms, ys, colors ): segs = _all_segments( s ) if segs: ekw = dict( edgecolors=sep, linewidth=_SEPARATOR_LW ) ekw.update( kwargs ) ax.broken_barh( segs, (yy - 0.5 * h, h), facecolors=c, **tkw, **ekw ) if pvalues: for cl, (x0, w) in zip( s.clusters, _segments( s ) ): ax.text( x0 + 0.5 * w, yy + 0.5 * h, _ptext( getattr(cl, 'p', None) ), ha='center', va='bottom', fontsize=fontsize, color=_style.ink(), **tkw ) if transform is None: ax.set_ylim( 0.5, n + 0.5 + (0.45 if pvalues else 0) ) if labels is not None and n > 1 or (labels is not None and lab0 is None): ax.set_yticks( ys ) ax.set_yticklabels( labels ) if label_colors: _colored_ticklabels( ax, ys, labels, dict(label_colors) ) elif tidy: ax.set_yticks( [] ) if tidy: for side in ('top', 'left', 'right'): ax.spines[side].set_visible( False ) ax.tick_params( axis='y', length=0 ) Q = getattr( spms[0], 'Q', None ) if (Q is not None) and (transform is None): ax.set_xlim( 0, Q - 1 ) return ax
def _split_label(label): '''Two group names of a comparison label such as "A0 - A1".''' parts = str( label ).split( ' - ' ) if len( parts ) != 2: from .. exceptions import SPM1DError raise SPM1DError( 'color-split bars need comparison labels of the form "A0 - A1" (the output of "posthoc"). ' 'the given label is "%s".' % label ) return parts[0], parts[1] def _group_colors(colors, groups): ''' Dictionary mapping group names to colors. ''' if isinstance( colors, dict ): missing = [ g for g in groups if g not in colors ] if missing: from .. exceptions import SPM1DError raise SPM1DError( '"colors" has no entry for the group(s) %s.' % ', '.join( '"%s"' % g for g in missing ) ) return dict( colors ) if colors is None: from matplotlib import pyplot as plt colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] colors = list( colors ) return { g : colors[i % len(colors)] for i, g in enumerate( groups ) }
[docs] def plot_cluster_bars_colorsplit(spmi, ax=None, colors=None, height=None, labels=None, color_order_by_effect_sign=True, csign=None, pvalues=False, fontsize=8, tidy=True, **kwargs): ''' Plot post hoc clusters as horizontal bars split into compared group colors. One row per pairwise comparison. :Parameters: - *spmi* --- post hoc list (``posthoc`` output) or list of inference results with labels like ``"A0 - A1"`` - *ax* --- axes [default: matplotlib.pyplot.gca()] - *colors* --- group colors as a dict (group name to color) or a sequence (order of first label appearance) [default: matplotlib's color cycle] - *height* --- bar height in row units (rows are one unit apart) [default: 0.5] - *labels* --- y tick labels (one per row) [default: list labels] - *color_order_by_effect_sign* --- if True (default), the group with the larger mean is on top; otherwise the first-named group is on top - *csign* --- short alias of *color_order_by_effect_sign* - *pvalues* --- if True, write cluster p values above bars - *fontsize* --- p value font size - *tidy* --- if True (default), hide top, left and right spines and y tick marks - *kwargs* --- passed to ``matplotlib.axes.Axes.broken_barh`` :Returns: - Axes :Example: Post hoc bars beneath a plot of the group means. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.SpeedGRFcategoricalRM() >>> y, (A, S) = dataset.y, dataset.x.T >>> Fi = spm1d.stats.anova1rm( y, A, S ).inference( 0.05 ) >>> phi = Fi.posthoc( correction='bonf' ) >>> fig, (ax0, ax1) = plt.subplots( 2, 1, sharex=True, gridspec_kw=dict( height_ratios=[3, 1] ) ) >>> for a, color in zip( (0, 1, 2), ('b', 'k', 'r') ): ... h = spm1d.plot.plot_mean_sd( y[A == a], ax=ax0, linecolor=color, facecolor=color ) >>> ax = phi.plot_cluster_bars_colorsplit( ax=ax1, colors={'A0': 'b', 'A1': 'k', 'A2': 'r'} ) >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt ax = plt.gca() if (ax is None) else ax spms, lab0 = _as_list( spmi ) _check_inference( spms ) if lab0 is None: from .. exceptions import SPM1DError raise SPM1DError( 'color-split bars need a list of comparisons with labels (the output of "posthoc"), not a single result.' ) bysign = bool( color_order_by_effect_sign ) if (csign is None) else bool( csign ) pairs = [ _split_label( lab ) for lab in lab0 ] groups = [] for g0, g1 in pairs: for g in (g0, g1): if g not in groups: groups.append( g ) gcolors = _group_colors( colors, groups ) n = len( spms ) labels = lab0 if (labels is None) else list( labels ) ys = [ float(n - i) for i in range(n) ] # first row on top h = 0.5 if (height is None) else float( height ) sep = _separator( ax ) for s, yy, (g0, g1) in zip( spms, ys, pairs ): for cl in (getattr( s, 'clusters', None ) or []): top, bot = (g1, g0) if (bysign and getattr( cl, 'sign', 1 ) < 0) else (g0, g1) ekw = dict( edgecolors=sep, linewidth=_SEPARATOR_LW ) ekw.update( kwargs ) ax.broken_barh( cl._bbars, (yy, 0.5 * h), facecolors=gcolors[top], **ekw ) ax.broken_barh( cl._bbars, (yy - 0.5 * h, 0.5 * h), facecolors=gcolors[bot], **ekw ) if pvalues: x0, w = cl._bbar ax.text( x0 + 0.5 * w, yy + 0.5 * h, _ptext( getattr(cl, 'p', None) ), ha='center', va='bottom', fontsize=fontsize, color=_style.ink() ) ax.set_ylim( 0.5, n + 0.5 + (0.45 if pvalues else 0) ) ax.set_yticks( ys ) ax.set_yticklabels( labels ) _colored_ticklabels( ax, ys, labels, gcolors ) if tidy: for side in ('top', 'left', 'right'): ax.spines[side].set_visible( False ) ax.tick_params( axis='y', length=0 ) Q = getattr( spms[0], 'Q', None ) if Q is not None: ax.set_xlim( 0, Q - 1 ) return ax
[docs] def plot_cluster_patches(spmi, ax=None, color=None, alpha=0.25, labels=None, zorder=0, **kwargs): ''' Plot suprathreshold clusters as vertical bands. :Parameters: - *spmi* --- inference SPM or list of inference SPMs (one color per element) - *ax* --- axes [default: matplotlib.pyplot.gca()] - *color* --- one color for all bands or one color per result - *alpha* --- band transparency - *labels* --- legend labels (one per result) [default: list labels or None] - *zorder* --- plotting order (default 0: bands behind data) :Returns: - list of patches per result :Example: Suprathreshold clusters as vertical bands behind the data. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.PlantarArchAngle() >>> y, A = dataset.y, dataset.x # (20,101) array and (20,) array >>> y0, y1 = y[ A == 0 ], y[ A == 1 ] >>> spmi = spm1d.stats.ttest_paired( y0, y1 ).inference( 0.05 ) >>> ax = plt.gca() >>> h0 = spm1d.plot.plot_mean_sd( y0, ax=ax ) >>> h1 = spm1d.plot.plot_mean_sd( y1, ax=ax, linecolor='r', facecolor='r' ) >>> patches = spm1d.plot.plot_cluster_patches( spmi, ax=ax ) >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt ax = plt.gca() if (ax is None) else ax spms, lab0 = _as_list( spmi ) _check_inference( spms ) n = len( spms ) labels = lab0 if (labels is None) else list( labels ) if color is None: colors = [ _style.gray(0.75) ] if (n == 1) else [ 'C%d' % i for i in range(n) ] else: colors = _colors( color, n ) from matplotlib import colors as mcolors sep = _separator( ax ) out = [] for i, (s, c) in enumerate( zip(spms, colors) ): patches = [] for k, (x0, w) in enumerate( _all_segments( s ) ): lab = ( labels[i] if (labels is not None and k == 0) else None ) # An opaque background-colored edge keeps adjacent bands apart. pkw = dict( facecolor=mcolors.to_rgba( c, alpha ), edgecolor=sep, linewidth=_SEPARATOR_LW, zorder=zorder, label=lab ) pkw.update( kwargs ) patches.append( ax.axvspan( x0, x0 + w, **pkw ) ) out.append( patches ) return out
[docs] def plot_cluster_barh(spmi, ax=None, loc=None, color=None, pvalues=False): ''' Attach a cluster bar strip to existing axes. :Parameters: - *spmi* --- inference SPM - *ax* --- axes [default: matplotlib.pyplot.gca()] - *loc* --- bar location: None (default), ``'below'`` or ``'above'`` - *color* --- bar color - *pvalues* --- if True, write cluster p values on bars :Returns: - bar axes if *loc* is ``'below'`` or ``'above'``, otherwise *None* :Example: Cluster bars attached below a plot of the data. >>> import spm1d >>> import jikudata as jd >>> from matplotlib import pyplot as plt >>> dataset = jd.PlantarArchAngle() >>> y, A = dataset.y, dataset.x # (20,101) array and (20,) array >>> y0, y1 = y[ A == 0 ], y[ A == 1 ] >>> spmi = spm1d.stats.ttest_paired( y0, y1 ).inference( 0.05 ) >>> ax = plt.gca() >>> h0 = spm1d.plot.plot_mean_sd( y0, ax=ax ) >>> h1 = spm1d.plot.plot_mean_sd( y1, ax=ax, linecolor='r', facecolor='r' ) >>> axb = spm1d.plot.plot_cluster_barh( spmi, ax=ax, loc='below', pvalues=True ) >>> plt.show() The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from matplotlib import pyplot as plt ax = plt.gca() if (ax is None) else ax if loc is None: plot_cluster_bars( spmi, ax=ax, color=color, pvalues=pvalues, transform=ax.get_xaxis_transform(), y=0.04, height=0.025 ) return None if loc not in ('below', 'above'): from .. exceptions import SPM1DError raise SPM1DError( 'loc must be None, "below" or "above"' ) bax = _exploded_axes( ax, loc, size=('12%' if pvalues else '7%') ) plot_cluster_bars( spmi, ax=bax, color=color, pvalues=pvalues ) if loc == 'above': # The strip sits on the main axes' top edge and has no spine or ticks of its own. bax.spines['bottom'].set_visible( False ) bax.tick_params( axis='x', length=0 ) return bax
def _exploded_axes(ax, where, size='7%', pad=0.05): '''Narrow axes above or below ``ax`` sharing its x axis.''' from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable( ax ) side = 'bottom' if (where == 'below') else 'top' bax = divider.append_axes( side, size=size, pad=pad, sharex=ax ) if where == 'below': ax.tick_params( axis='x', labelbottom=False ) else: bax.tick_params( axis='x', labelbottom=False ) return bax