| """ |
| plot_util.py — Plotting utilities for Squidiff reproducibility notebooks. |
| |
| The original authors used a local private script that was not included |
| in the public repository. This file reimplements the required functions |
| based on their call signatures in the reproducibility notebooks. |
| |
| Functions: |
| plot_pca -- PCA scatter plot of embeddings colored by group label. |
| display_reconst -- Scatter + kernel density comparison of original |
| vs. reconstructed gene expressions. |
| """ |
|
|
| import numpy as np |
| import matplotlib.pyplot as plt |
| import matplotlib.patches as mpatches |
| from sklearn.decomposition import PCA |
| import torch |
|
|
|
|
| def plot_pca( |
| data, |
| label=None, |
| size=3, |
| alpha=0.8, |
| colorlist=None, |
| color_label=None, |
| title=None, |
| figsize=(3, 3), |
| dpi=300, |
| ): |
| """ |
| Project data to 2D via PCA and render a scatter plot colored by label. |
| |
| Parameters |
| ---------- |
| data : torch.Tensor or numpy.ndarray |
| Input matrix of shape (n_cells, n_features). |
| label : array-like, optional |
| Group labels for each cell (e.g., obs['Group']). Used for coloring. |
| size : float, optional |
| Marker size for scatter points. Default is 3. |
| alpha : float, optional |
| Marker opacity. Default is 0.8. |
| colorlist : list of str, optional |
| List of hex color strings, one per unique label value. |
| Default cycles through a built-in palette. |
| color_label : list, optional |
| Subset of label values to include in the legend. If None, all |
| unique label values are shown. |
| title : str, optional |
| Plot title. If None, no title is shown. |
| figsize : tuple, optional |
| Figure size in inches. Default is (3, 3). |
| dpi : int, optional |
| Figure DPI. Default is 300. |
| """ |
| |
| if isinstance(data, torch.Tensor): |
| data = data.detach().cpu().numpy() |
| else: |
| data = np.array(data) |
|
|
| |
| if data.shape[1] > 2: |
| pca = PCA(n_components=2) |
| coords = pca.fit_transform(data) |
| else: |
| coords = data |
|
|
| |
| if label is not None: |
| labels = np.array(label) |
| unique_labels = np.unique(labels) |
| else: |
| labels = np.zeros(len(coords), dtype=int) |
| unique_labels = np.array([0]) |
|
|
| |
| default_palette = [ |
| '#3145a8', '#fa2616', '#40a8f7', '#f5bf36', |
| '#2ca02c', '#9467bd', '#8c564b', '#e377c2', |
| ] |
| if colorlist is None: |
| colorlist = default_palette |
|
|
| |
| if color_label is not None: |
| legend_labels = [str(v) for v in color_label] |
| else: |
| legend_labels = [str(v) for v in unique_labels] |
|
|
| |
| fig, ax = plt.subplots(figsize=figsize, dpi=dpi) |
| handles = [] |
| for idx, ul in enumerate(unique_labels): |
| mask = labels == ul |
| color = colorlist[idx % len(colorlist)] |
| ax.scatter( |
| coords[mask, 0], |
| coords[mask, 1], |
| c=color, |
| s=size, |
| alpha=alpha, |
| rasterized=True, |
| ) |
| if str(ul) in legend_labels: |
| handles.append( |
| mpatches.Patch(color=color, label=str(ul)) |
| ) |
|
|
| ax.set_xlabel('PC1') |
| ax.set_ylabel('PC2') |
| if title: |
| ax.set_title(title) |
| if handles: |
| ax.legend(handles=handles, markerscale=2, frameon=False, |
| bbox_to_anchor=(1.01, 1), loc='upper left') |
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| def display_reconst( |
| original_df, |
| reconstructed_df, |
| density=False, |
| size=(2.5, 2.5), |
| dpi=300, |
| alpha=0.3, |
| color_orig='#3145a8', |
| color_reconst='#fa2616', |
| xlabel='Original gene expression', |
| ylabel='Reconstructed gene expression', |
| ): |
| """ |
| Display a scatter plot comparing original and reconstructed gene expression, |
| with optional kernel-density overlays. |
| |
| Parameters |
| ---------- |
| original_df : pandas.DataFrame or array-like |
| Flattened original gene expression values. |
| reconstructed_df : pandas.DataFrame or array-like |
| Flattened reconstructed gene expression values. |
| density : bool, optional |
| If True, overlay a KDE (kernel density estimate) on 1-D marginals. |
| Default is False. |
| size : tuple, optional |
| Figure size (width, height) in inches. Default is (2.5, 2.5). |
| dpi : int, optional |
| Figure DPI. Default is 300. |
| alpha : float, optional |
| Scatter point opacity. Default is 0.3. |
| color_orig : str, optional |
| Color for original values in density plot. Default is '#3145a8'. |
| color_reconst : str, optional |
| Color for reconstructed values in density plot. Default is '#fa2616'. |
| xlabel : str, optional |
| X-axis label. Default is 'Original gene expression'. |
| ylabel : str, optional |
| Y-axis label. Default is 'Reconstructed gene expression'. |
| """ |
| import pandas as pd |
| from scipy.stats import gaussian_kde |
|
|
| |
| orig = np.array(original_df).flatten() |
| reconst = np.array(reconstructed_df).flatten() |
|
|
| if density: |
| |
| fig, axes = plt.subplots(1, 2, figsize=(size[0] * 2, size[1]), dpi=dpi) |
|
|
| |
| axes[0].scatter(reconst, orig, s=2, alpha=alpha, color=color_orig, |
| rasterized=True) |
| axes[0].set_xlabel('Reconstructed') |
| axes[0].set_ylabel('Original') |
| |
| lims = [min(orig.min(), reconst.min()), |
| max(orig.max(), reconst.max())] |
| axes[0].plot(lims, lims, 'k--', linewidth=0.8, alpha=0.5) |
|
|
| |
| for vals, color, lbl in [ |
| (orig, color_orig, 'Original'), |
| (reconst, color_reconst, 'Reconstructed'), |
| ]: |
| kde = gaussian_kde(vals, bw_method=0.3) |
| x_range = np.linspace(vals.min(), vals.max(), 300) |
| axes[1].plot(x_range, kde(x_range), color=color, label=lbl) |
| axes[1].fill_between(x_range, kde(x_range), alpha=0.2, color=color) |
|
|
| axes[1].set_xlabel('Gene expression') |
| axes[1].set_ylabel('Density') |
| axes[1].legend(frameon=False, fontsize=8) |
| else: |
| |
| fig, ax = plt.subplots(figsize=size, dpi=dpi) |
| ax.scatter(reconst, orig, s=2, alpha=alpha, color=color_orig, |
| rasterized=True) |
| lims = [min(orig.min(), reconst.min()), |
| max(orig.max(), reconst.max())] |
| ax.plot(lims, lims, 'k--', linewidth=0.8, alpha=0.5) |
| ax.set_xlabel(xlabel) |
| ax.set_ylabel(ylabel) |
|
|
| plt.tight_layout() |
| plt.show() |
|
|