'''
Design matrix and variance component plots.
'''
# Copyright (C) 2026 Todd Pataky
import numpy as np
def _scaled_columns(X):
'''
Design matrix columns scaled to [0, 1].
'''
X = np.asarray( X, dtype=float )
mn = X.min( axis=0 )
mx = X.max( axis=0 )
rng = np.where( mx > mn, mx - mn, 1.0 )
Xs = (X - mn) / rng
Xs[:, mx == mn] = 1.0 # a constant column shows as white
return Xs
[docs]
def plot_design(design, ax=None, term_labels=True, fontsize=9, cmap='gray'):
'''
Plot a design matrix as an image.
:Parameters:
- *design* --- **spm1d** design object (e.g., ``spm.design``)
- *ax* --- matplotlib.axes object [default: matplotlib.pyplot.gca()]
- *term_labels* --- label terms above their columns
- *fontsize* --- label font size
:Returns:
- **matplotlib.image.AxesImage**
:Example:
The design matrix of a two-sample t test on two simulated groups of six
responses.
>>> import spm1d
>>> import jikudata as jd
>>> from matplotlib import pyplot as plt
>>> dataset = jd.SimulatedTwoLocalMax()
>>> y, A = dataset.y, dataset.x # (12,101) array and (12,) array
>>> spm = spm1d.stats.ttest2( y[ A == 0 ], y[ A == 1 ] )
>>> image = spm1d.plot.plot_design( spm.design )
>>> plt.show()
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
import matplotlib.pyplot as plt
from . import _style
ax = plt.gca() if (ax is None) else ax
X = np.asarray( design.X, dtype=float )
J, n = X.shape
im = ax.imshow( _scaled_columns(X), cmap=cmap, interpolation='nearest', vmin=0, vmax=1, aspect='auto' )
ink = _style.ink()
for name, sl in design.terms.items():
if sl.start > 0:
ax.axvline( sl.start - 0.5, color=_style.accent(), lw=1 )
if term_labels:
ax.text( 0.5 * (sl.start + sl.stop - 1), -0.6, name, ha='center', va='bottom', color=ink, fontsize=fontsize )
ax.set_xlim( -0.5, n - 0.5 )
ax.set_ylim( J - 0.5, -0.5 )
ax.set_xlabel( 'column' )
ax.set_ylabel( 'observation' )
ax.set_title( design.name, pad=14 )
return im
[docs]
def plot_spm_design(spm, ax=None, fontsize=10):
'''
Plot the SPM design matrix using ``plot_design(spm.design)``.
:Parameters:
- *spm* --- **spm1d** SPM object before or after inference
- *ax* --- matplotlib.axes object [default: matplotlib.pyplot.gca()]
- *fontsize* --- label font size
:Returns:
- **matplotlib.image.AxesImage**
:Example:
The design matrix of a two-sample t test on two simulated groups of six
responses.
>>> import spm1d
>>> import jikudata as jd
>>> from matplotlib import pyplot as plt
>>> dataset = jd.SimulatedTwoLocalMax()
>>> y, A = dataset.y, dataset.x # (12,101) array and (12,) array
>>> spm = spm1d.stats.ttest2( y[ A == 0 ], y[ A == 1 ] )
>>> image = spm1d.plot.plot_spm_design( spm ) # equivalent to image = spm.plot_design()
>>> plt.show()
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
return plot_design( spm.design, ax=ax, fontsize=fontsize )
[docs]
def plot_variance_components(QQ, ax=None, ncols=None, fontsize=9, cmap='gray'):
'''
Plot each design variance component as a small labeled J-by-J image.
:Parameters:
- *QQ* --- **VarianceComponents** object (``design.get_variance_model()``)
- *ax* --- matplotlib.axes object whose figure receives the grid (the axes
is removed) [default: new figure]
- *ncols* --- panels per row [default: approximately sqrt(count)]
- *fontsize* --- label font size (default 9)
- *cmap* --- matplotlib colormap name (default ``'gray'``)
:Returns:
- list of axes
:Example:
The two variance components (one variance per group) of a two-sample t
test on two simulated groups of six responses.
>>> import spm1d
>>> import jikudata as jd
>>> from matplotlib import pyplot as plt
>>> dataset = jd.SimulatedTwoLocalMax()
>>> y, A = dataset.y, dataset.x # (12,101) array and (12,) array
>>> spm = spm1d.stats.ttest2( y[ A == 0 ], y[ A == 1 ] )
>>> QQ = spm.design.get_variance_model()
>>> axs = spm1d.plot.plot_variance_components( QQ )
>>> plt.show()
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
import matplotlib.pyplot as plt
from math import ceil
from . import _style
n = len( QQ )
labels = getattr( QQ, 'labels', [f'Q{i}' for i in range(n)] )
if ncols is None:
ncols = int( ceil( n ** 0.5 ) )
nrows = int( ceil( n / ncols ) )
if ax is None:
fig = plt.figure( figsize=(2.2 * ncols, 2.2 * nrows) )
else:
fig = ax.figure
ax.remove()
AX = []
for i, (Q, label) in enumerate( zip(QQ, labels) ):
a = fig.add_subplot( nrows, ncols, i + 1 )
a.imshow( np.asarray(Q, dtype=float), cmap=cmap, interpolation='nearest', vmin=0, vmax=max(1.0, float(np.max(Q))) )
a.set_title( label, fontsize=fontsize, color=_style.ink() )
a.set_xticks( [] )
a.set_yticks( [] )
AX.append( a )
return AX