|
| 1 | +# pyXenium/analysis/plotting.py |
| 2 | + |
| 3 | +import seaborn as sns |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | +def plot_auc_heatmap(summary: pd.DataFrame, figsize=(10,8)): |
| 8 | + mat = summary.pivot(index="cluster", columns="protein", values="test_auc") |
| 9 | + mat = mat.apply(pd.to_numeric, errors="coerce") |
| 10 | + g = sns.clustermap(mat, cmap="viridis", linewidths=.3, figsize=figsize) |
| 11 | + g.ax_heatmap.set_xlabel("Protein"); g.ax_heatmap.set_ylabel("Cluster") |
| 12 | + return g |
| 13 | + |
| 14 | +def plot_topk_per_cluster(summary: pd.DataFrame, k=5, metric="test_auc"): |
| 15 | + topk = (summary.sort_values(["cluster", metric], ascending=[True, False]) |
| 16 | + .groupby("cluster").head(k)) |
| 17 | + fig, ax = plt.subplots(figsize=(max(10, k * 1.2), 6)) |
| 18 | + labels = [] |
| 19 | + vals = [] |
| 20 | + for cl, sub in topk.groupby("cluster"): |
| 21 | + for _, r in sub.iterrows(): |
| 22 | + labels.append(f"{cl}:{r['protein']}") |
| 23 | + vals.append(r[metric]) |
| 24 | + ax.bar(labels, vals) |
| 25 | + ax.set_ylabel(metric) |
| 26 | + ax.set_xticklabels(labels, rotation=90) |
| 27 | + plt.tight_layout() |
| 28 | + return fig |
| 29 | + |
| 30 | +def plot_DE_volcano(de_df: pd.DataFrame, title="DE Volcano", |
| 31 | + logfc_col="mean_diff", pval_col="pval", adj_col="adj_pval", |
| 32 | + fdr_thresh=0.05): |
| 33 | + df = de_df.copy() |
| 34 | + df["-log10p"] = -np.log10(df[pval_col]) |
| 35 | + plt.figure(figsize=(6,5)) |
| 36 | + sns.scatterplot(data=df, x=logfc_col, y="-log10p", |
| 37 | + hue=df[adj_col] < fdr_thresh, |
| 38 | + palette={True: "red", False: "gray"}, legend=False) |
| 39 | + plt.axhline(-np.log10(0.05), ls="--", color="black") |
| 40 | + plt.title(title) |
| 41 | + plt.xlabel("Mean difference (High vs Low)") |
| 42 | + plt.ylabel("-log10(p)") |
| 43 | + plt.tight_layout() |
| 44 | + plt.show() |
| 45 | + |
| 46 | +def plot_model_diagnostics(adata, models, cluster, protein, feature_key="X_rna_pca"): |
| 47 | + from sklearn.metrics import RocCurveDisplay, PrecisionRecallDisplay |
| 48 | + from sklearn.calibration import calibration_curve |
| 49 | + |
| 50 | + res = models[cluster][protein] |
| 51 | + clf, scaler = res.model, res.scaler |
| 52 | + thr = getattr(res, "threshold", None) |
| 53 | + |
| 54 | + mask = (adata.obs["rna_cluster"] == cluster) |
| 55 | + X = scaler.transform(adata.obsm[feature_key][mask, :]) |
| 56 | + # y 真值需要你自己定义:可能 adata.obs[f"protein:{protein}"] ≥ thr |
| 57 | + y = (adata.obs.loc[mask, f"protein:{protein}"] >= thr).astype(int).to_numpy() |
| 58 | + y_prob = clf.predict_proba(X)[:, 1] |
| 59 | + |
| 60 | + RocCurveDisplay.from_predictions(y, y_prob) |
| 61 | + plt.title(f"ROC — {cluster}:{protein}") |
| 62 | + PrecisionRecallDisplay.from_predictions(y, y_prob) |
| 63 | + plt.title(f"PR — {cluster}:{protein}") |
| 64 | + prob_true, prob_pred = calibration_curve(y, y_prob, n_bins=10, strategy="quantile") |
| 65 | + plt.figure() |
| 66 | + plt.plot(prob_pred, prob_true, marker="o") |
| 67 | + plt.plot([0,1],[0,1], "--") |
| 68 | + plt.xlabel("Predicted prob"); plt.ylabel("Empirical freq") |
| 69 | + plt.title(f"Calibration — {cluster}:{protein}") |
| 70 | + plt.tight_layout() |
| 71 | + plt.show() |
0 commit comments