scanpy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scanpy: Single-Cell Analysis

Scanpy:单细胞分析

Overview

概述

Scanpy is a scalable Python toolkit for analyzing single-cell RNA-seq data, built on AnnData. Apply this skill for complete single-cell workflows including quality control, normalization, dimensionality reduction, clustering, marker gene identification, visualization, and trajectory analysis.
Scanpy 是一个基于 AnnData 构建的、可扩展的 Python 单细胞 RNA-seq 数据分析工具包。应用此 Skill 可完成完整的单细胞工作流,包括质量控制、归一化、降维、聚类、marker gene 识别、可视化和轨迹分析。

When to Use This Skill

何时使用此 Skill

This skill should be used when:
  • Analyzing single-cell RNA-seq data (.h5ad, 10X, CSV formats)
  • Performing quality control on scRNA-seq datasets
  • Creating UMAP, t-SNE, or PCA visualizations
  • Identifying cell clusters and finding marker genes
  • Annotating cell types based on gene expression
  • Conducting trajectory inference or pseudotime analysis
  • Generating publication-quality single-cell plots
此 Skill 适用于:
  • 分析单细胞 RNA-seq 数据(.h5ad、10X、CSV 格式)
  • 对 scRNA-seq 数据集执行质量控制
  • 创建 UMAP、t-SNE 或 PCA 可视化结果
  • 识别细胞簇并查找 marker gene
  • 根据基因表达情况注释细胞类型
  • 执行轨迹推断或伪时间分析
  • 生成出版级的单细胞图表

Quick Start

快速开始

Basic Import and Setup

基础导入与设置

python
import scanpy as sc
import pandas as pd
import numpy as np
python
import scanpy as sc
import pandas as pd
import numpy as np

Configure settings

Configure settings

sc.settings.verbosity = 3 sc.settings.set_figure_params(dpi=80, facecolor='white') sc.settings.figdir = './figures/'
undefined
sc.settings.verbosity = 3 sc.settings.set_figure_params(dpi=80, facecolor='white') sc.settings.figdir = './figures/'
undefined

Loading Data

加载数据

python
undefined
python
undefined

From 10X Genomics

From 10X Genomics

adata = sc.read_10x_mtx('path/to/data/') adata = sc.read_10x_h5('path/to/data.h5')
adata = sc.read_10x_mtx('path/to/data/') adata = sc.read_10x_h5('path/to/data.h5')

From h5ad (AnnData format)

From h5ad (AnnData format)

adata = sc.read_h5ad('path/to/data.h5ad')
adata = sc.read_h5ad('path/to/data.h5ad')

From CSV

From CSV

adata = sc.read_csv('path/to/data.csv')
undefined
adata = sc.read_csv('path/to/data.csv')
undefined

Understanding AnnData Structure

了解 AnnData 结构

The AnnData object is the core data structure in scanpy:
python
adata.X          # Expression matrix (cells × genes)
adata.obs        # Cell metadata (DataFrame)
adata.var        # Gene metadata (DataFrame)
adata.uns        # Unstructured annotations (dict)
adata.obsm       # Multi-dimensional cell data (PCA, UMAP)
adata.raw        # Raw data backup
AnnData 对象是 scanpy 中的核心数据结构:
python
adata.X          # Expression matrix (cells × genes)
adata.obs        # Cell metadata (DataFrame)
adata.var        # Gene metadata (DataFrame)
adata.uns        # Unstructured annotations (dict)
adata.obsm       # Multi-dimensional cell data (PCA, UMAP)
adata.raw        # Raw data backup

Access cell and gene names

Access cell and gene names

adata.obs_names # Cell barcodes adata.var_names # Gene names
undefined
adata.obs_names # Cell barcodes adata.var_names # Gene names
undefined

Standard Analysis Workflow

标准分析工作流

1. Quality Control

1. 质量控制

Identify and filter low-quality cells and genes:
python
undefined
识别并过滤低质量细胞和基因:
python
undefined

Identify mitochondrial genes

Identify mitochondrial genes

adata.var['mt'] = adata.var_names.str.startswith('MT-')
adata.var['mt'] = adata.var_names.str.startswith('MT-')

Calculate QC metrics

Calculate QC metrics

sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)

Visualize QC metrics

Visualize QC metrics

sc.pl.violin(adata, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'], jitter=0.4, multi_panel=True)
sc.pl.violin(adata, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'], jitter=0.4, multi_panel=True)

Filter cells and genes

Filter cells and genes

sc.pp.filter_cells(adata, min_genes=200) sc.pp.filter_genes(adata, min_cells=3) adata = adata[adata.obs.pct_counts_mt < 5, :] # Remove high MT% cells

**Use the QC script for automated analysis:**
```bash
python scripts/qc_analysis.py input_file.h5ad --output filtered.h5ad
sc.pp.filter_cells(adata, min_genes=200) sc.pp.filter_genes(adata, min_cells=3) adata = adata[adata.obs.pct_counts_mt < 5, :] # Remove high MT% cells

**使用 QC 脚本执行自动化分析:**
```bash
python scripts/qc_analysis.py input_file.h5ad --output filtered.h5ad

2. Normalization and Preprocessing

2. 归一化与预处理

python
undefined
python
undefined

Normalize to 10,000 counts per cell

Normalize to 10,000 counts per cell

sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.normalize_total(adata, target_sum=1e4)

Log-transform

Log-transform

sc.pp.log1p(adata)
sc.pp.log1p(adata)

Save raw counts for later

Save raw counts for later

adata.raw = adata
adata.raw = adata

Identify highly variable genes

Identify highly variable genes

sc.pp.highly_variable_genes(adata, n_top_genes=2000) sc.pl.highly_variable_genes(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000) sc.pl.highly_variable_genes(adata)

Subset to highly variable genes

Subset to highly variable genes

adata = adata[:, adata.var.highly_variable]
adata = adata[:, adata.var.highly_variable]

Regress out unwanted variation

Regress out unwanted variation

sc.pp.regress_out(adata, ['total_counts', 'pct_counts_mt'])
sc.pp.regress_out(adata, ['total_counts', 'pct_counts_mt'])

Scale data

Scale data

sc.pp.scale(adata, max_value=10)
undefined
sc.pp.scale(adata, max_value=10)
undefined

3. Dimensionality Reduction

3. 降维

python
undefined
python
undefined

PCA

PCA

sc.tl.pca(adata, svd_solver='arpack') sc.pl.pca_variance_ratio(adata, log=True) # Check elbow plot
sc.tl.pca(adata, svd_solver='arpack') sc.pl.pca_variance_ratio(adata, log=True) # Check elbow plot

Compute neighborhood graph

Compute neighborhood graph

sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40)
sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40)

UMAP for visualization

UMAP for visualization

sc.tl.umap(adata) sc.pl.umap(adata, color='leiden')
sc.tl.umap(adata) sc.pl.umap(adata, color='leiden')

Alternative: t-SNE

Alternative: t-SNE

sc.tl.tsne(adata)
undefined
sc.tl.tsne(adata)
undefined

4. Clustering

4. 聚类

python
undefined
python
undefined

Leiden clustering (recommended)

Leiden clustering (recommended)

sc.tl.leiden(adata, resolution=0.5) sc.pl.umap(adata, color='leiden', legend_loc='on data')
sc.tl.leiden(adata, resolution=0.5) sc.pl.umap(adata, color='leiden', legend_loc='on data')

Try multiple resolutions to find optimal granularity

Try multiple resolutions to find optimal granularity

for res in [0.3, 0.5, 0.8, 1.0]: sc.tl.leiden(adata, resolution=res, key_added=f'leiden_{res}')
undefined
for res in [0.3, 0.5, 0.8, 1.0]: sc.tl.leiden(adata, resolution=res, key_added=f'leiden_{res}')
undefined

5. Marker Gene Identification

5. Marker Gene 识别

python
undefined
python
undefined

Find marker genes for each cluster

Find marker genes for each cluster

sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')
sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')

Visualize results

Visualize results

sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False) sc.pl.rank_genes_groups_heatmap(adata, n_genes=10) sc.pl.rank_genes_groups_dotplot(adata, n_genes=5)
sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False) sc.pl.rank_genes_groups_heatmap(adata, n_genes=10) sc.pl.rank_genes_groups_dotplot(adata, n_genes=5)

Get results as DataFrame

Get results as DataFrame

markers = sc.get.rank_genes_groups_df(adata, group='0')
undefined
markers = sc.get.rank_genes_groups_df(adata, group='0')
undefined

6. Cell Type Annotation

6. 细胞类型注释

python
undefined
python
undefined

Define marker genes for known cell types

Define marker genes for known cell types

marker_genes = ['CD3D', 'CD14', 'MS4A1', 'NKG7', 'FCGR3A']
marker_genes = ['CD3D', 'CD14', 'MS4A1', 'NKG7', 'FCGR3A']

Visualize markers

Visualize markers

sc.pl.umap(adata, color=marker_genes, use_raw=True) sc.pl.dotplot(adata, var_names=marker_genes, groupby='leiden')
sc.pl.umap(adata, color=marker_genes, use_raw=True) sc.pl.dotplot(adata, var_names=marker_genes, groupby='leiden')

Manual annotation

Manual annotation

cluster_to_celltype = { '0': 'CD4 T cells', '1': 'CD14+ Monocytes', '2': 'B cells', '3': 'CD8 T cells', } adata.obs['cell_type'] = adata.obs['leiden'].map(cluster_to_celltype)
cluster_to_celltype = { '0': 'CD4 T cells', '1': 'CD14+ Monocytes', '2': 'B cells', '3': 'CD8 T cells', } adata.obs['cell_type'] = adata.obs['leiden'].map(cluster_to_celltype)

Visualize annotated types

Visualize annotated types

sc.pl.umap(adata, color='cell_type', legend_loc='on data')
undefined
sc.pl.umap(adata, color='cell_type', legend_loc='on data')
undefined

7. Save Results

7. 保存结果

python
undefined
python
undefined

Save processed data

Save processed data

adata.write('results/processed_data.h5ad')
adata.write('results/processed_data.h5ad')

Export metadata

Export metadata

adata.obs.to_csv('results/cell_metadata.csv') adata.var.to_csv('results/gene_metadata.csv')
undefined
adata.obs.to_csv('results/cell_metadata.csv') adata.var.to_csv('results/gene_metadata.csv')
undefined

Common Tasks

常见任务

Creating Publication-Quality Plots

创建出版级图表

python
undefined
python
undefined

Set high-quality defaults

Set high-quality defaults

sc.settings.set_figure_params(dpi=300, frameon=False, figsize=(5, 5)) sc.settings.file_format_figs = 'pdf'
sc.settings.set_figure_params(dpi=300, frameon=False, figsize=(5, 5)) sc.settings.file_format_figs = 'pdf'

UMAP with custom styling

UMAP with custom styling

sc.pl.umap(adata, color='cell_type', palette='Set2', legend_loc='on data', legend_fontsize=12, legend_fontoutline=2, frameon=False, save='_publication.pdf')
sc.pl.umap(adata, color='cell_type', palette='Set2', legend_loc='on data', legend_fontsize=12, legend_fontoutline=2, frameon=False, save='_publication.pdf')

Heatmap of marker genes

Heatmap of marker genes

sc.pl.heatmap(adata, var_names=genes, groupby='cell_type', swap_axes=True, show_gene_labels=True, save='_markers.pdf')
sc.pl.heatmap(adata, var_names=genes, groupby='cell_type', swap_axes=True, show_gene_labels=True, save='_markers.pdf')

Dot plot

Dot plot

sc.pl.dotplot(adata, var_names=genes, groupby='cell_type', save='_dotplot.pdf')

Refer to `references/plotting_guide.md` for comprehensive visualization examples.
sc.pl.dotplot(adata, var_names=genes, groupby='cell_type', save='_dotplot.pdf')

有关全面的可视化示例,请参阅 `references/plotting_guide.md`。

Trajectory Inference

轨迹推断

python
undefined
python
undefined

PAGA (Partition-based graph abstraction)

PAGA (Partition-based graph abstraction)

sc.tl.paga(adata, groups='leiden') sc.pl.paga(adata, color='leiden')
sc.tl.paga(adata, groups='leiden') sc.pl.paga(adata, color='leiden')

Diffusion pseudotime

Diffusion pseudotime

adata.uns['iroot'] = np.flatnonzero(adata.obs['leiden'] == '0')[0] sc.tl.dpt(adata) sc.pl.umap(adata, color='dpt_pseudotime')
undefined
adata.uns['iroot'] = np.flatnonzero(adata.obs['leiden'] == '0')[0] sc.tl.dpt(adata) sc.pl.umap(adata, color='dpt_pseudotime')
undefined

Differential Expression Between Conditions

不同条件间的差异表达

python
undefined
python
undefined

Compare treated vs control within cell types

Compare treated vs control within cell types

adata_subset = adata[adata.obs['cell_type'] == 'T cells'] sc.tl.rank_genes_groups(adata_subset, groupby='condition', groups=['treated'], reference='control') sc.pl.rank_genes_groups(adata_subset, groups=['treated'])
undefined
adata_subset = adata[adata.obs['cell_type'] == 'T cells'] sc.tl.rank_genes_groups(adata_subset, groupby='condition', groups=['treated'], reference='control') sc.pl.rank_genes_groups(adata_subset, groups=['treated'])
undefined

Gene Set Scoring

基因集评分

python
undefined
python
undefined

Score cells for gene set expression

Score cells for gene set expression

gene_set = ['CD3D', 'CD3E', 'CD3G'] sc.tl.score_genes(adata, gene_set, score_name='T_cell_score') sc.pl.umap(adata, color='T_cell_score')
undefined
gene_set = ['CD3D', 'CD3E', 'CD3G'] sc.tl.score_genes(adata, gene_set, score_name='T_cell_score') sc.pl.umap(adata, color='T_cell_score')
undefined

Batch Correction

批次校正

python
undefined
python
undefined

ComBat batch correction

ComBat batch correction

sc.pp.combat(adata, key='batch')
sc.pp.combat(adata, key='batch')

Alternative: use Harmony or scVI (separate packages)

Alternative: use Harmony or scVI (separate packages)

undefined
undefined

Key Parameters to Adjust

需要调整的关键参数

Quality Control

质量控制

  • min_genes
    : Minimum genes per cell (typically 200-500)
  • min_cells
    : Minimum cells per gene (typically 3-10)
  • pct_counts_mt
    : Mitochondrial threshold (typically 5-20%)
  • min_genes
    :每个细胞的最少基因数(通常为 200-500)
  • min_cells
    :每个基因的最少细胞数(通常为 3-10)
  • pct_counts_mt
    :线粒体阈值(通常为 5%-20%)

Normalization

归一化

  • target_sum
    : Target counts per cell (default 1e4)
  • target_sum
    :每个细胞的目标计数(默认值为 1e4)

Feature Selection

特征选择

  • n_top_genes
    : Number of HVGs (typically 2000-3000)
  • min_mean
    ,
    max_mean
    ,
    min_disp
    : HVG selection parameters
  • n_top_genes
    :HVG 的数量(通常为 2000-3000)
  • min_mean
    、
    max_mean
    、
    min_disp
    :HVG 选择参数

Dimensionality Reduction

降维

  • n_pcs
    : Number of principal components (check variance ratio plot)
  • n_neighbors
    : Number of neighbors (typically 10-30)
  • n_pcs
    :主成分数量(通过方差比率图确定)
  • n_neighbors
    :邻居数量(通常为 10-30)

Clustering

聚类

  • resolution
    : Clustering granularity (0.4-1.2, higher = more clusters)
  • resolution
    :聚类粒度(0.4-1.2,数值越高,聚类越多)

Common Pitfalls and Best Practices

常见问题与最佳实践

  1. Always save raw counts:
    adata.raw = adata
    before filtering genes
  2. Check QC plots carefully: Adjust thresholds based on dataset quality
  3. Use Leiden over Louvain: More efficient and better results
  4. Try multiple clustering resolutions: Find optimal granularity
  5. Validate cell type annotations: Use multiple marker genes
  6. Use
    use_raw=True
    for gene expression plots
    : Shows original counts
  7. Check PCA variance ratio: Determine optimal number of PCs
  8. Save intermediate results: Long workflows can fail partway through
  1. 始终保存原始计数:在过滤基因之前设置
    adata.raw = adata
  2. 仔细检查 QC 图:根据数据集质量调整阈值
  3. 使用 Leiden 而非 Louvain:效率更高,结果更好
  4. 尝试多种聚类分辨率:确定最佳粒度
  5. 验证细胞类型注释:使用多个 marker gene
  6. 在基因表达图中使用
    use_raw=True
    :显示原始计数
  7. 检查 PCA 方差比率:确定最佳主成分数量
  8. 保存中间结果:较长的工作流可能中途失败

Bundled Resources

随附资源

scripts/qc_analysis.py

scripts/qc_analysis.py

Automated quality control script that calculates metrics, generates plots, and filters data:
bash
python scripts/qc_analysis.py input.h5ad --output filtered.h5ad \
    --mt-threshold 5 --min-genes 200 --min-cells 3
用于计算指标、生成图表并过滤数据的自动化质量控制脚本:
bash
python scripts/qc_analysis.py input.h5ad --output filtered.h5ad \
    --mt-threshold 5 --min-genes 200 --min-cells 3

references/standard_workflow.md

references/standard_workflow.md

Complete step-by-step workflow with detailed explanations and code examples for:
  • Data loading and setup
  • Quality control with visualization
  • Normalization and scaling
  • Feature selection
  • Dimensionality reduction (PCA, UMAP, t-SNE)
  • Clustering (Leiden, Louvain)
  • Marker gene identification
  • Cell type annotation
  • Trajectory inference
  • Differential expression
Read this reference when performing a complete analysis from scratch.
完整的分步工作流,包含详细说明和代码示例,涵盖:
  • 数据加载与设置
  • 带可视化的质量控制
  • 归一化与缩放
  • 特征选择
  • 降维(PCA、UMAP、t-SNE)
  • 聚类(Leiden、Louvain)
  • Marker gene 识别
  • 细胞类型注释
  • 轨迹推断
  • 差异表达
从头执行完整分析时,请阅读此参考文档。

references/api_reference.md

references/api_reference.md

Quick reference guide for scanpy functions organized by module:
  • Reading/writing data (
    sc.read_*
    ,
    adata.write_*
    )
  • Preprocessing (
    sc.pp.*
    )
  • Tools (
    sc.tl.*
    )
  • Plotting (
    sc.pl.*
    )
  • AnnData structure and manipulation
  • Settings and utilities
Use this for quick lookup of function signatures and common parameters.
按模块组织的 Scanpy 函数快速参考指南:
  • 数据读写(
    sc.read_*
    、
    adata.write_*
    )
  • 预处理(
    sc.pp.*
    )
  • 工具(
    sc.tl.*
    )
  • 绘图(
    sc.pl.*
    )
  • AnnData 结构与操作
  • 设置与实用工具
使用此文档快速查询函数签名和常用参数。

references/plotting_guide.md

references/plotting_guide.md

Comprehensive visualization guide including:
  • Quality control plots
  • Dimensionality reduction visualizations
  • Clustering visualizations
  • Marker gene plots (heatmaps, dot plots, violin plots)
  • Trajectory and pseudotime plots
  • Publication-quality customization
  • Multi-panel figures
  • Color palettes and styling
Consult this when creating publication-ready figures.
全面的可视化指南,包括:
  • 质量控制图
  • 降维可视化
  • 聚类可视化
  • Marker gene 图(热图、点图、小提琴图)
  • 轨迹与伪时间图
  • 出版级定制
  • 多面板图
  • 调色板和样式
创建可直接用于发表的图时,请查阅此指南。

assets/analysis_template.py

assets/analysis_template.py

Complete analysis template providing a full workflow from data loading through cell type annotation. Copy and customize this template for new analyses:
bash
cp assets/analysis_template.py my_analysis.py
完整的分析模板,涵盖从数据加载到细胞类型注释的全流程。复制并自定义此模板以用于新的分析:
bash
cp assets/analysis_template.py my_analysis.py

Edit parameters and run

Edit parameters and run

python my_analysis.py

The template includes all standard steps with configurable parameters and helpful comments.
python my_analysis.py

该模板包含所有标准步骤,并提供可配置参数和有用的注释。

Additional Resources

其他资源

Tips for Effective Analysis

高效分析提示

  1. Start with the template: Use
    assets/analysis_template.py
    as a starting point
  2. Run QC script first: Use
    scripts/qc_analysis.py
    for initial filtering
  3. Consult references as needed: Load workflow and API references into context
  4. Iterate on clustering: Try multiple resolutions and visualization methods
  5. Validate biologically: Check marker genes match expected cell types
  6. Document parameters: Record QC thresholds and analysis settings
  7. Save checkpoints: Write intermediate results at key steps
  1. 从模板开始:使用
    assets/analysis_template.py
    作为起点
  2. 首先运行 QC 脚本:使用
    scripts/qc_analysis.py
    执行初始过滤
  3. 按需查阅参考资料:将工作流和 API 参考资料加载到上下文中
  4. 迭代聚类分析:尝试多种分辨率和可视化方法
  5. 进行生物学验证:检查 marker gene 是否与预期细胞类型匹配
  6. 记录参数:记录 QC 阈值和分析设置
  7. 保存检查点:在关键步骤保存中间结果