AAPredPlot.group_cluster
- static AAPredPlot.group_cluster(X, *, kind='clustermap', layout='rectangular', labels=None, dict_color=None, legend_title='Class', labels_row=None, dict_color_row=None, legend_title_row=None, names=None, cmap='GnBu', figsize=None, cbar_label='Pearson correlation (r)', title=None)[source]
Cluster the sample group by how its members relate, dispatched by
kind.The sample-relation counterpart of
AAPredPlot.predict_group()(which plots the prediction scores):group_clustertakes the sample x feature matrixX(feature values fromSequenceFeature.feature_matrix(), or SHAP values from a fittedShapModel) and lays the samples out by their similarity, annotating each sample with up to two per-sample class strips (a top and a left sidebar), each with a titled legend.'clustermap'— hierarchically clustered sample x sample correlation heatmap of the feature/SHAP vectors.labelscolors the top (column) sidebar andlabels_rowthe left (row) sidebar; a lonelabelsis mirrored onto both.'dendrogram'— the sample relation tree alone, drawn with thelayoutof choice ('rectangular'or a radial'circular'tree). It is built from exactly the same linkage as the clustermap, so its topology and leaf order equal the clustermap’s row dendrogram.labelsandlabels_rowcolor the leaves as one strip (rectangular) or ring (circular) each,labelsinnermost, each with its titled legend.
Added in version 1.1.0.
Changed in version 1.2.0: Added
kind='dendrogram'and thelayoutparameter.- Parameters:
X (pd.DataFrame or array-like) – Finite numeric per-sample feature or importance matrix, shape
(n_samples, n_features)with at least two samples and one feature. Its rows determine the sample relations; use CPP feature values fromSequenceFeature.feature_matrix()or SHAP values fromShapModel.kind ({'clustermap', 'dendrogram'}, default='clustermap') –
Which relation figure to draw.
'clustermap': draw the clustered sample x sample Pearson-correlation heatmap.'dendrogram': draw only the corresponding sample-relation tree.
Changed in version 1.2.0: Added the
'dendrogram'option.layout ({'rectangular', 'circular'}, default='rectangular') –
Tree layout when
kind='dendrogram'. It has no visual effect for the default clustermap layout; a non-default value withkind='clustermap'raises aValueError.'rectangular': draw the root on the left and leaves in rows on the right.'circular': draw a radial tree with the root at the center and leaves around it.
Added in version 1.2.0.
labels (array-like, optional, default=None) – Per-sample class labels (length
n_samples) coloring the top (column) sidebar. Whenlabels_rowisNone, the same annotation is mirrored onto the left sidebar. Forkind='dendrogram', they color the innermost leaf strip or ring. IfNone, no top or innermost annotation is drawn. Labels must be hashable and cannot beNone.dict_color (dict, optional, default=None) – A
label -> colormapping forlabels; the mapping order also sets the legend order. It must contain a valid matplotlib color for every label. IfNone, colors are assigned from the house palette in first-occurrence order.legend_title (str or None, default='Class') – Title for the
labelsannotation legend. IfNone, the legend title is'Class'; an empty string also uses'Class'.labels_row (array-like, optional, default=None) – Per-sample class labels for a distinct left (row) sidebar (length
n_samples), e.g. a prediction-confidence band alongside a class annotation on top. Forkind='dendrogram'they color a second, outer leaf strip or ring. IfNone, the clustermap mirrorslabelson its left sidebar and the dendrogram draws no outer annotation. Labels must be hashable and cannot beNone.dict_color_row (dict, optional, default=None) – A
label -> colormapping forlabels_row. It must contain a valid matplotlib color for every row label. IfNone, colors are assigned from the house palette in first-occurrence order.legend_title_row (str or None, default=None) – Title for the
labels_rowannotation legend. IfNone, the legend title is'Class'; an empty string also uses'Class'.names (array-like, optional, default=None) – Per-sample tick labels (leaf names for
kind='dendrogram'). IfNone, positional indices are used; otherwise items must be strings or string-convertible. Dense sample sets show only every k-th name.cmap (str, default='GnBu') – (
kind='clustermap') Colormap for the correlation heatmap; validated but ignored by the dendrogram.figsize (tuple of float, optional, default=None) – Figure width and height in inches, each at least one. If
None, uses(11, 11)forkind='clustermap',(7, 9)for a rectangular dendrogram, or(9, 10)for a circular dendrogram. Both kinds own their figure, so noaxis accepted.cbar_label (str or None, default='Pearson correlation (r)') – (
kind='clustermap') Label of the colorbar. Defaults to'Pearson correlation (r)';Noneleaves the colorbar unlabeled. It is validated but ignored by the dendrogram.title (str, optional, default=None) – Figure title. If
None, no figure title is added.
- Returns:
fig (matplotlib.figure.Figure) – The figure.
ax (matplotlib.axes.Axes) – The clustermap heatmap axes, or the tree axes (a polar axes for
layout='circular').
- Raises:
ValueError – If
kindis not one of'clustermap'or'dendrogram', iflayoutis not one of'rectangular'or'circular', or if a non-defaultlayoutis combined withkind='clustermap'.ValueError – If
Xis not a finite numeric 2D matrix with at least two samples and one feature.ValueError – If
labels,labels_row, ornamesare not list-like of lengthn_samples, if a label isNoneor not hashable, ifnamescontains an item that is not string-convertible, ifdict_color/dict_color_roware not dictionaries of valid colors or miss a color for a label, iflegend_title,legend_title_row,cbar_label, ortitleare not strings, ifcmapis not a valid matplotlib colormap name, or iffigsizeis not a tuple of two numbers each at least one.
See also
AAPredPlot.predict_group()for across-samples views of the prediction scores.ShapModelandSequenceFeature.feature_matrix()for the input matrix.
Notes
Samples are related by the Pearson correlation between their feature/importance vectors. A sample whose vector has zero variance (e.g. an all-zero SHAP row) is treated as uncorrelated (0) with other samples and has self-correlation 1, so the clustering stays well-defined without numerical warnings.
Both kinds share one hierarchical linkage, computed with
scipy(average linkage on the Euclidean distances between the rows of that correlation matrix) and handed toseaborn.clustermapviarow_linkage/col_linkage. The dendrogram therefore shows the same topology and leaf order as the clustermap’s row dendrogram.seabornuses thefastclusterpackage for its own linkage when it is installed. Since the linkage is now always computed withscipy, a clustermap drawn on a machine withfastclusterinstalled may break exact ties between equidistant merges differently than before (the cluster contents are the same; only the arrangement of tied branches can differ).
Examples
AAPredPlot().group_cluster(X, kind=...)is the sample-relation counterpart ofpredict_group: it takes the sample x feature matrixX(feature values fromSequenceFeature.feature_matrix, or SHAP values from a fittedShapModel) and clusters the samples by how they relate. Two kinds are available:kind='clustermap': a hierarchically clustered sample x sample correlation heatmap.kind='dendrogram': the relation tree alone, as alayout='rectangular'or a radiallayout='circular'tree. It uses the same linkage as the clustermap, so both show the same tree.
Each sample can carry two class annotations:
labelsandlabels_row, each with its owndict_colormap and titled legend. In the clustermap they color the top (column) and left (row) sidebars (a lonelabelsis mirrored onto both sides); in the dendrogram they color the leaves as one strip or ring each.import numpy as np import matplotlib.pyplot as plt import aaanalysis as aa aa.options["verbose"] = False aa.plot_settings(font_scale=0.8, weight_bold=False) aap_plot = aa.AAPredPlot() # Synthetic per-sample importance matrix: three blocks of samples with distinct signals. rng = np.random.RandomState(1) X = np.vstack([rng.normal(0.7, 0.25, size=(12, 30)), rng.normal(-0.2, 0.25, size=(8, 30)), rng.normal(-0.7, 0.25, size=(10, 30))]) names = [f"P{i:02d}" for i in range(30)] # Two per-sample annotations: a prediction group (top) and a confidence band (left). group = ["Substrate"] * 12 + ["Non-substrate (known)"] * 8 + ["Non-substrate (dPULearn)"] * 10 score = np.clip(np.concatenate([rng.normal(85, 12, 12), rng.normal(30, 18, 8), rng.normal(15, 12, 10)]), 0, 100) confidence = ["HC Substrate" if s >= 80 else "LC Substrate" if s >= 50 else "LC Non-substrate" if s >= 20 else "HC Non-substrate" for s in score]
Two annotations.
labels(prediction group) colors the top sidebar andlabels_row(confidence band) the left sidebar;dict_color/dict_color_rowfix eachlabel -> colormap (and the legend order), andlegend_title/legend_title_rowtitle the two legends.namessets the per-sample tick labels:C_SUB, C_KNOWN, C_DPU = "tab:green", "tab:purple", "tab:olive" dict_group = {"Substrate": C_SUB, "Non-substrate (known)": C_KNOWN, "Non-substrate (dPULearn)": C_DPU} dict_conf = {"HC Substrate": "#FF0D57", "LC Substrate": "#F9779E", "LC Non-substrate": "#83BBEC", "HC Non-substrate": "#1E88E5"} aap_plot.group_cluster(X, kind="clustermap", labels=group, dict_color=dict_group, legend_title="Prediction group", labels_row=confidence, dict_color_row=dict_conf, legend_title_row="Confidence", names=names) plt.tight_layout() plt.show()
Single annotation and further parameters. With only
labelsthe annotation is mirrored onto both sidebars. Here we also adjust the heatmapcmap, the colorbar label (cbar_label), thefigsizeand atitle:aap_plot.group_cluster(X, kind="clustermap", labels=group, dict_color=dict_group, legend_title="Prediction group", names=names, cmap="RdBu_r", cbar_label="Pearson correlation (r)", figsize=(9, 9), title="Explanation-similarity clustering") plt.tight_layout() plt.show()
Rectangular dendrogram.
kind='dendrogram'draws only the tree of the clustermap above (same linkage, same leaf order), with the root on the left and the leaves on the right. The same annotation parameters color the leaves:labelsthe inner strip andlabels_rowthe outer strip, each with its legend;nameslabel the leaves:aap_plot.group_cluster(X, kind="dendrogram", layout="rectangular", labels=group, dict_color=dict_group, legend_title="Prediction group", labels_row=confidence, dict_color_row=dict_conf, legend_title_row="Confidence", names=names) plt.tight_layout() plt.show()
Circular dendrogram.
layout='circular'draws the same tree radially, with the root at the center and the annotations as rings around the leaves. Here we also set thefigsizeand atitle. The heatmap-onlycmapandcbar_labelare not used by the dendrogram, and a non-defaultlayoutis only accepted forkind='dendrogram':aap_plot.group_cluster(X, kind="dendrogram", layout="circular", labels=group, dict_color=dict_group, legend_title="Prediction group", labels_row=confidence, dict_color_row=dict_conf, legend_title_row="Confidence", names=names, figsize=(8, 9), title="Explanation-similarity tree") plt.tight_layout() plt.show()