单细胞堆叠小提琴图(Python)

作者

[编辑] 王诗翔

[贡献] Claude Code —— AI 生成,独立 AI 复核;

修改于

2026-10-19

🤖 AI Skill — Download the Bizard unified skill for your AI assistant ⬇️ Download Skill ZIP
🔌 MCP Server — Let AI agents (Claude Code, Cursor, …) query Bizard live: claude mcp add bizard -- npx @openbiox/bizard-mcp — or the free hosted instance (no install, faster from mainland China): claude mcp add --transport http bizard http://biotree.top:38123/bizard-mcp/mcp 📖 MCP Docs
📖 Cite Bizard — if Bizard helps your research, please cite: Li, K., Zheng, H., Huang, K., et al. (2026). Bizard: A Community-Driven Platform for Accelerating and Enhancing Biomedical Data Visualization. iMetaMed, e70038. 🔗 DOI / BibTeX

堆叠小提琴图把「基因 × cluster」的小提琴排成对齐网格,在点图只给汇总量的地方展示完整的标志基因表达分布——当审稿人要求提供分布时,它是点图的标准配套图。scanpy.pl.stacked_violin 负责网格排布与跨面板统一样式。

示例

环境配置

  • 系统要求:跨平台(Linux/MacOS/Windows)
  • 编程语言:Python
  • 依赖包:scanpy、anndata、pandas、numpy、matplotlib
import matplotlib.pyplot as plt
import scanpy as sc
import pandas as pd
import numpy as np

sc.settings.verbosity = 0
sc.settings.set_figure_params(dpi=90, facecolor='white')

数据准备

我们复用模拟的三群体 PBMC 数据集(log 标准化后),配一组六基因精选标志集。

np.random.seed(241)

n_per = 400
genes = [f'Gene{i:02d}' for i in range(1, 31)]
blocks = {'T cells': (0, 10), 'B cells': (10, 20), 'Monocytes': (20, 30)}
counts = np.zeros((n_per * 3, 30))
labels = []
for i, (cell_type, (lo, hi)) in enumerate(blocks.items()):
    sl = slice(i * n_per, (i + 1) * n_per)
    counts[sl] = np.random.negative_binomial(4, 0.3, (n_per, 30))
    counts[sl, lo:hi] += np.random.negative_binomial(8, 0.2, (n_per, hi - lo))
    labels += [cell_type] * n_per

adata = sc.AnnData(counts.astype(np.float32))
adata.var_names = genes
adata.obs['CellType'] = pd.Categorical(labels, categories=blocks)

sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
marker_genes = ['Gene01', 'Gene07', 'Gene12',
                'Gene16', 'Gene22', 'Gene28']

可视化

统一样式的堆叠小提琴

网格中的小提琴共享样式;旋转基因标签并收紧布局让六个面板保持紧凑。

fig, ax = plt.subplots(figsize=(7.4, 4.6))
sc.pl.stacked_violin(adata, var_names=marker_genes, groupby='CellType',
                     ax=ax, show=False, cmap='Reds',
                     dendrogram=False)
plt.tight_layout()
plt.show()
图 1: 各群体的标志基因表达分布

交换方向

交换 groupby 与基因顺序(按基因画小提琴、跨 cluster 排列)在基因名较长时可读性更好——同一数据,一次转置即可。

fig, ax = plt.subplots(figsize=(6.2, 4.2))
sc.pl.stacked_violin(adata, var_names=marker_genes, groupby='CellType',
                     ax=ax, show=False, cmap='Blues', swap_axes=True,
                     dendrogram=False)
plt.tight_layout()
plt.show()
图 2: 转置布局:按基因跨群体的小提琴

参考文献

  1. Wolf, F. A., Angerer, P., & Theis, F. J. (2018). SCANPY: large-scale single-cell gene expression data analysis. Genome Biology, 19, 15.
  2. Trapnell, C. (2015). Defining cell types and states with single-cell genomics. Genome Research, 25(10), 1491-1498.