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_cluster takes the sample x feature matrix X (feature values from SequenceFeature.feature_matrix(), or SHAP values from a fitted ShapModel) 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. labels colors the top (column) sidebar and labels_row the left (row) sidebar; a lone labels is mirrored onto both.

  • 'dendrogram' — the sample relation tree alone, drawn with the layout of 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. labels and labels_row color the leaves as one strip (rectangular) or ring (circular) each, labels innermost, each with its titled legend.

Added in version 1.1.0.

Changed in version 1.2.0: Added kind='dendrogram' and the layout parameter.

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 from SequenceFeature.feature_matrix() or SHAP values from ShapModel.

  • 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 with kind='clustermap' raises a ValueError.

    • '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. When labels_row is None, the same annotation is mirrored onto the left sidebar. For kind='dendrogram', they color the innermost leaf strip or ring. If None, no top or innermost annotation is drawn. Labels must be hashable and cannot be None.

  • dict_color (dict, optional, default=None) – A label -> color mapping for labels; the mapping order also sets the legend order. It must contain a valid matplotlib color for every label. If None, colors are assigned from the house palette in first-occurrence order.

  • legend_title (str or None, default='Class') – Title for the labels annotation legend. If None, 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. For kind='dendrogram' they color a second, outer leaf strip or ring. If None, the clustermap mirrors labels on its left sidebar and the dendrogram draws no outer annotation. Labels must be hashable and cannot be None.

  • dict_color_row (dict, optional, default=None) – A label -> color mapping for labels_row. It must contain a valid matplotlib color for every row label. If None, colors are assigned from the house palette in first-occurrence order.

  • legend_title_row (str or None, default=None) – Title for the labels_row annotation legend. If None, 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'). If None, 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) for kind='clustermap', (7, 9) for a rectangular dendrogram, or (9, 10) for a circular dendrogram. Both kinds own their figure, so no ax is accepted.

  • cbar_label (str or None, default='Pearson correlation (r)') – (kind='clustermap') Label of the colorbar. Defaults to 'Pearson correlation (r)'; None leaves 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 kind is not one of 'clustermap' or 'dendrogram', if layout is not one of 'rectangular' or 'circular', or if a non-default layout is combined with kind='clustermap'.

  • ValueError – If X is not a finite numeric 2D matrix with at least two samples and one feature.

  • ValueError – If labels, labels_row, or names are not list-like of length n_samples, if a label is None or not hashable, if names contains an item that is not string-convertible, if dict_color / dict_color_row are not dictionaries of valid colors or miss a color for a label, if legend_title, legend_title_row, cbar_label, or title are not strings, if cmap is not a valid matplotlib colormap name, or if figsize is not a tuple of two numbers each at least one.

See also

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 to seaborn.clustermap via row_linkage / col_linkage. The dendrogram therefore shows the same topology and leaf order as the clustermap’s row dendrogram.

  • seaborn uses the fastcluster package for its own linkage when it is installed. Since the linkage is now always computed with scipy, a clustermap drawn on a machine with fastcluster installed 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 of predict_group: it takes the sample x feature matrix X (feature values from SequenceFeature.feature_matrix, or SHAP values from a fitted ShapModel) 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 a layout='rectangular' or a radial layout='circular' tree. It uses the same linkage as the clustermap, so both show the same tree.

Each sample can carry two class annotations: labels and labels_row, each with its own dict_color map and titled legend. In the clustermap they color the top (column) and left (row) sidebars (a lone labels is 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 and labels_row (confidence band) the left sidebar; dict_color / dict_color_row fix each label -> color map (and the legend order), and legend_title / legend_title_row title the two legends. names sets 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()
../_images/aap_plot_group_cluster_1_output_3_0.png

Single annotation and further parameters. With only labels the annotation is mirrored onto both sidebars. Here we also adjust the heatmap cmap, the colorbar label (cbar_label), the figsize and a title:

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()
../_images/aap_plot_group_cluster_2_output_5_0.png

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: labels the inner strip and labels_row the outer strip, each with its legend; names label 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()
../_images/aap_plot_group_cluster_3_output_7_0.png

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 the figsize and a title. The heatmap-only cmap and cbar_label are not used by the dendrogram, and a non-default layout is only accepted for kind='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()
../_images/aap_plot_group_cluster_4_output_9_0.png