在前面的文章中,我们已经讲述了CellPhoneDB算法的基本原理。接下来,我们以CellPhoneDB研发团队提供的示例数据为基础,走一遍模式二的全程。该示例数据包括约3300个细胞、3万余个基因。
创建独立Python环境 打开Anaconda Prompt并输入:
1 2 3 4 5 conda create -n cpdb python=3.10 -y conda activate cpdb python -m pip install cellphonedb==5.0 .1 python -m pip install notebook ipykernel jupyter notebook
此时会自动打开浏览器并进入jupyter主页。
新建Notebook,创建项目目录 在打开的Jupyter Notebook主页中,点击File-New-Notebook,新建一个Notebook。随后,在第一个代码单元格输入以下代码,以检查Python和CellPhoneDB是否可用:
1 2 3 4 5 6 import sysfrom importlib.metadata import versionprint ("Python路径:" , sys.executable)print ("Python版本:" , sys.version)print ("CellPhoneDB版本:" , version("cellphonedb" ))
按Shift+Enter执行,输出示例如下:
1 2 3 Python路径: D:\Software\miniconda3\envs\cpdb\python.exe Python版本: 3.10.22 | packaged by Anaconda, Inc. | (main, Oct 29 2026, 20:28:38) [MSC v.1942 64 bit (AMD64)] CellPhoneDB版本: 5.0.1
同时,我们创建好项目目录:
1 2 3 4 5 6 7 8 9 from pathlib import Pathroot = Path(r"D:\Projects\Python\CellPhoneDB" ) (root / "database" ).mkdir(parents=True , exist_ok=True ) (root / "input" ).mkdir(parents=True , exist_ok=True ) (root / "results" ).mkdir(parents=True , exist_ok=True ) print ("项目目录:" , root)
输出示例如下:
1 项目目录: D:\Projects\Python\CellPhoneDB
此时,我们已经在所需要的文件夹中创建一个新的CellPhoneDB文件夹,后者下属三个文件夹,即database、input和results。
下载官方示例数据及CellPhoneDB数据库 在Github仓库下载CellPhoneDB官方示例数据data_tutorial.zip ,下载后并解压至...\CellPhoneDB\input文件夹。
解压后,运行以下代码以检验能否查找到输入文件:
1 2 3 4 5 6 7 8 9 10 11 12 meta_files = list (root.rglob("metadata.tsv" )) counts_files = list (root.rglob("normalised_log_counts.h5ad" )) print ("细胞注释文件:" , meta_files)print ("表达矩阵文件:" , counts_files)assert meta_files, "找不到 metadata.tsv" assert counts_files, "找不到 normalised_log_counts.h5ad" meta_path = meta_files[0 ] counts_path = counts_files[0 ]
如果显示如下代码,则表示下载成功:
1 2 细胞注释文件: [WindowsPath('D:/Projects/Python/CellPhoneDB/input/data_tutorial/data/metadata.tsv')] 表达矩阵文件: [WindowsPath('D:/Projects/Python/CellPhoneDB/input/data_tutorial/data/normalised_log_counts.h5ad')]
同时在Jupyter Notebook中运行以下代码以下载CellPhoneDB v5.0.0数据库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from cellphonedb.utils import db_utilsdb_utils.download_database( str (root / "database" ), "v5.0.0" ) db_files = list ((root / "database" ).rglob("cellphonedb.zip" )) print (db_files)assert db_files, "未找到 CellPhoneDB 数据库" cpdb_path = db_files[0 ]
示例输出:
1 2 3 4 5 6 7 8 9 Downloaded cellphonedb.zip into D:\Projects\Python\CellPhoneDB\database Downloaded complex_input.csv into D:\Projects\Python\CellPhoneDB\database Downloaded gene_input.csv into D:\Projects\Python\CellPhoneDB\database Downloaded interaction_input.csv into D:\Projects\Python\CellPhoneDB\database Downloaded protein_input.csv into D:\Projects\Python\CellPhoneDB\database Downloaded uniprot_synonyms.tsv into D:\Projects\Python\CellPhoneDB\database\sources Downloaded transcription_factor_input.csv into D:\Projects\Python\CellPhoneDB\database\sources [WindowsPath('D:/Projects/Python/CellPhoneDB/database/cellphonedb.zip')]
检查单细胞数据 我们之前所下载的官方示例数据包含约3300个细胞及3万余个基因。在进行分析之前,我们需要对单细胞数据进行检验,检验内容包括细胞、基因数量是否一致,以及细胞注释和表达矩阵是否对应。我们能运行以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 import pandas as pdimport anndata as admeta = pd.read_csv(meta_path, sep="\t" ) adata = ad.read_h5ad(counts_path) print ("细胞注释:" )display(meta.head()) print ("表达矩阵维度:" , adata.shape)print ("基因名称:" )print (adata.var_names[:10 ])
如果出现以下示例输出,则说明细胞和基因数量的确是没有问题的:
1 2 3 4 5 6 7 8 9 10 11 12 细胞注释: barcode_sample cell_type 0 AGCGATTAGTCTAACC-1_Pla_HDBR10917733 B_cells 1 ATCCGTGAGGCTAGAA-1_Pla_Camb10714918 B_cells 2 AGTAACCCATTAAAGG-1_Pla_HDBR10917733 B_cells 3 GTTCACCTCAATGAGG-1_Pla_HDBR10142864 B_cells 4 GCCAACGTCCACGTAA-1_Pla_HDBR10917733 B_cells 表达矩阵维度: (3312, 30800) 基因名称: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2ML1-AS1', 'A3GALT2', 'A4GALT', 'A4GNT'], dtype='object')
我们继续检查细胞注释和表达矩阵是否一致:
1 2 3 4 5 6 meta_cells = set (meta.iloc[:, 0 ].astype(str )) count_cells = set (adata.obs_names.astype(str )) print ("细胞名称一致:" , meta_cells == count_cells)print ("细胞类型数量:" , meta.iloc[:, 1 ].nunique())
如果输出以下结果,则单细胞数据检查通过,可以进行正式的分析啦~
运行CellPhoneDB模式二 此部分代码已在前文具体阐述,这里就不再展开:
1 2 3 4 5 6 7 8 9 10 11 12 13 from cellphonedb.src.core.methods import cpdb_statistical_analysis_methodcpdb_results = cpdb_statistical_analysis_method.call( cpdb_file_path = str (cpdb_path), meta_file_path = str (meta_path), counts_file_path = str (counts_path), counts_data = "hgnc_symbol" , output_path = str (root / "results" ), iterations = 1000 , threshold = 0.1 , pvalue = 0.05 , threads = 4 )
以下是示例输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Reading user files... The following user files were loaded successfully: D:\Projects\Python\CellPhoneDB\input\data_tutorial\data\normalised_log_counts.h5ad D:\Projects\Python\CellPhoneDB\input\data_tutorial\data\metadata.tsv [ ][CORE][02/11/26-20:15:20][INFO] [Cluster Statistical Analysis] Threshold:0.1 Iterations:1000 Debug-seed:-1 Threads:4 Precision:3 [ ][CORE][02/11/26-20:15:21][INFO] Running Real Analysis [ ][CORE][02/11/26-20:15:21][INFO] Running Statistical Analysis 100%|██████████| 1000/1000 [01:06<00:00, 15.10it/s] [ ][CORE][02/11/26-20:16:27][INFO] Building Pvalues result [ ][CORE][02/11/26-20:16:32][INFO] Building results Saved deconvoluted to D:\Projects\Python\CellPhoneDB\results\statistical_analysis_deconvoluted_11_02_2026_201632.txt Saved deconvoluted_percents to D:\Projects\Python\CellPhoneDB\results\statistical_analysis_deconvoluted_percents_11_02_2026_201632.txt Saved means to D:\Projects\Python\CellPhoneDB\results\statistical_analysis_means_11_02_2026_201632.txt Saved pvalues to D:\Projects\Python\CellPhoneDB\results\statistical_analysis_pvalues_11_02_2026_201632.txt Saved significant_means to D:\Projects\Python\CellPhoneDB\results\statistical_analysis_significant_means_11_02_2026_201632.txt
查看分析结果 通过print(cpdb_results.keys()),我们可以查看输出文件的类型。
1 dict_keys(['deconvoluted', 'deconvoluted_percents', 'means', 'pvalues', 'significant_means', 'CellSign_active_interactions', 'CellSign_active_interactions_deconvoluted'])
其中,我们重点关注means、pvalues和significant_means这三类结果,分别记录各配体–受体对在不同细胞类型组合中的平均表达量、置换检验得到的经验$p$值,以及经过显著性筛选后的平均表达量。我们接下来查看前几个配体-受体对及其经验$p$值:
1 display(cpdb_results["pvalues" ].head())
示例输出结果:
index
id_cp_interaction
interacting_pair
partner_a
partner_b
gene_a
gene_b
secreted
receptor_a
receptor_b
annotation_strategy
…
uSMC|dS1
uSMC|dS2
uSMC|dS3
uSMC|dT_cells
uSMC|dT_regs
uSMC|eEVT
uSMC|fF1
uSMC|fF2
uSMC|iEVT
uSMC|uSMC
0
CPI-SC0A2DB962D
CDH1_integrin_a2b1_complex
simple:P12830
complex:integrin_a2b1_complex
CDH1
NaN
False
False
False
curated
…
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1
CPI-SC0B5CEA47D
COL10A1_integrin_a2b1_complex
simple:Q03692
complex:integrin_a2b1_complex
COL10A1
NaN
True
False
False
curated
…
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
2
CPI-SC0C8B7BCBB
COL11A1_integrin_a2b1_complex
simple:P12107
complex:integrin_a2b1_complex
COL11A1
NaN
True
False
False
curated
…
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
3
CPI-SC0D3C12C3F
COL11A2_integrin_a2b1_complex
simple:P13942
complex:integrin_a2b1_complex
COL11A2
NaN
True
False
False
curated
…
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
4
CPI-SC0B86B7CED
COL12A1_integrin_a2b1_complex
simple:Q99715
complex:integrin_a2b1_complex
COL12A1
NaN
True
False
False
curated
…
1.0
1.0
1.0
1.0
1.0
0.0
1.0
1.0
1.0
1.0
5 rows × 1777 columns
该表格中列名的含义如下:
列名
含义
id_cp_interaction
配体–受体相互作用的唯一编号
interacting_pair
配体–受体组合的名称
partner_a / partner_b
参与相互作用的两个分子或蛋白复合物
gene_a / gene_b
相应分子的基因名称;如果是蛋白复合物,可能显示为空值(NaN)
secreted
是否涉及分泌型分子
receptor_a / receptor_b
标记相互作用中的哪一方属于受体
annotation_strategy
配体–受体相互作用的注释来源或策略
A|B
A与B细胞群之间,该配体–受体组合的经验P值
A|A
A细胞群内部,该配体–受体组合的经验P值
我们也可以找出一个细胞类型组合,并查看该细胞类型组合中显著的配体-受体对:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 pvalues = cpdb_results["pvalues" ] pair_cols = [c for c in pvalues.columns if "|" in c] print (pair_cols[:10 ])pair = pair_cols[0 ] sig = pvalues.loc[ pd.to_numeric(pvalues[pair], errors="coerce" ) < 0.05 , ["interacting_pair" , pair] ] display(sig.sort_values(pair).head(10 ))
示例输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 ['B_cells|B_cells', 'B_cells|DC', 'B_cells|EVT_1', 'B_cells|EVT_2', 'B_cells|Endo_F', 'B_cells|Endo_L', 'B_cells|Endo_M', 'B_cells|GC', 'B_cells|Granulocytes', 'B_cells|HOFB'] interacting_pair B_cells|B_cells 931 FCER2_CR2 0.000 483 APP_CD74 0.000 2898 PTPRC_CD22 0.000 1848 LTB_LTBR 0.000 765 CXCL14_CXCR4 0.001 2344 LTA_TNFRSF1B 0.001 1703 HLA-F_LILRB1 0.003 2156 SEMA4D_CD72 0.003 2158 SEMA4D_PTPRC 0.007 267 PLAUR_integrin_a4b1_complex 0.011
可视化 气泡图 如果我们需要展示特定的细胞类型组合中,配体-受体对的平均表达量和统计学显著性,气泡图是非常合适的选择。
我们运行以下代码:
1 2 3 4 5 6 7 import pandas as pd import numpy as np import matplotlib.pyplot as plt pvalues = cpdb_results["pvalues" ].copy() means = cpdb_results["means" ].copy()
接下来,我们取以下细胞类型配对及配体-受体对进行演示。
1 2 3 4 5 6 7 8 9 10 11 selected_pairs = [ "uSMC|dS1" ,"uSMC|dS2" ,"uSMC|dS3" ,"uSMC|dT_cells" ,"uSMC|dT_regs" , "uSMC|eEVT" ,"uSMC|fF1" ,"uSMC|fF2" ,"uSMC|iEVT" ,"uSMC|uSMC" ] selected_lr = [ "APP_CD74" ,"CD44_TYROBP" ,"VEGFA_FLT1" ,"PGF_FLT1" ,"VEGFB_FLT1" , "FN1_integrin_a5b1_complex" ,"COL1A1_integrin_a1b1_complex" ,"COL4A1_ADGRG6" ,"LAMA2_ADGRG6" ,"IL1RAP_PTPRF" ]
选择以上细胞类型配对及配体-受体对仅作为演示。在实际科研实践中,我们可根据我们的实验目的进行筛选,或由CellPhoneDB算法自动进行筛选(详见下述)。
接下来,我们继续从pvalues及means表格中提取细胞互作ID、配体-受体对名称及所有uSMC细胞相关的细胞类型配对。同时,我们把宽表转换为长表,便于查看、合并和绘图。
举例,这是“宽表”:
interacting_pair
uSMC|dS1
uSMC|dS2
uSMC|dS3
L1-R1
0.01
0.20
0.03
L2-R2
1.00
0.04
0.50
我们要把它变成这样的“长表”:
interacting_pair
cell_pair
pvalue
L1-R1
uSMC|dS1
0.01
L1-R1
uSMC|dS2
0.20
L1-R1
uSMC|dS3
0.03
L2-R2
uSMC|dS1
1.00
L2-R2
uSMC|dS2
0.04
L2-R2
uSMC|dS3
0.50
1 2 3 4 5 6 7 8 9 10 11 12 13 p_long = pvalues[["id_cp_interaction" , "interacting_pair" ] + selected_pairs].melt( id_vars=["id_cp_interaction" , "interacting_pair" ], value_vars=selected_pairs, var_name="cell_pair" , value_name="pvalue" ) m_long = means[["id_cp_interaction" , "interacting_pair" ] + selected_pairs].melt( id_vars=["id_cp_interaction" , "interacting_pair" ], value_vars=selected_pairs, var_name="cell_pair" , value_name="mean" )
然后,我们合并两个表格,并只保留我们关注的10个配体-受体对,便于绘图。同时,我们将pvalue值和mean值都转位数值型(如果存在异常字符即设置为NaN),并删除$p$值或平均表达量缺失的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 plot_df = pd.merge( p_long, m_long, on=["id_cp_interaction" , "interacting_pair" , "cell_pair" ], how="inner" ) plot_df = plot_df[ plot_df["interacting_pair" ].isin(selected_lr) ].copy() plot_df["pvalue" ] = pd.to_numeric( plot_df["pvalue" ], errors="coerce" ) plot_df["mean" ] = pd.to_numeric( plot_df["mean" ], errors="coerce" ) plot_df = plot_df.dropna(subset=["pvalue" , "mean" ]) display(plot_df.head())
以下是输出示例:
id_cp_interaction
interacting_pair
cell_pair
pvalue
mean
85
CPI-SC08DBCCFF0
COL1A1_integrin_a1b1_complex
uSMC
dS1
0.0
203
CPI-SS015BF69EE
COL4A1_ADGRG6
uSMC
dS1
1.0
209
CPI-SS0335C4DDE
LAMA2_ADGRG6
uSMC
dS1
1.0
262
CPI-SC06C3BA86F
FN1_integrin_a5b1_complex
uSMC
dS1
0.0
417
CPI-SS080C81D37
APP_CD74
uSMC
dS1
1.0
在气泡图中,我们以气泡大小表示置换检验的统计学显著性,并通过 (-\log_{10}(p)) 转换,使$p$值越小时气泡越大。但置换检验可能出现以下情况:在有限次数的置换中,没有获得比真实统计量更加极端的结果,此时经验$p$值为0。但我们知道,对数函数的底数不能为0。那为之奈何?我们需要给$p$值设置一个足够低的下限。在这里,我们进行置换检验共1000次,若出现更极端的结果的次数只有1次,此时$p=\frac{1}{1000}$,这是$p$值除0外的最小值。因此,我们可以将$p$值的下限设置为$\frac{1}{1000+1}$,代表比1次更少。
1 2 3 4 5 6 7 8 9 n_permutations = 1000 plot_df["plot_p" ] = plot_df["pvalue" ].clip( lower=1 / (n_permutations + 1 ) ) plot_df["neglog10_p" ] = -np.log10(plot_df["plot_p" ])
接下来,我们用matplotlib来绘制气泡图——
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 x_order = selected_pairs y_order = selected_lr[::-1 ] x_map = {name: i for i, name in enumerate (x_order)} y_map = {name: i for i, name in enumerate (y_order)} plot_df = plot_df.copy() plot_df["x" ] = plot_df["cell_pair" ].map (x_map) plot_df["y" ] = plot_df["interacting_pair" ].map (y_map) size_min = 20 size_max = 260 max_score = -np.log10(1 / (n_permutations + 1 ) ) plot_df["point_size" ] = ( size_min + plot_df["neglog10_p" ] / max_score *(size_max - size_min) ) fig = plt.figure(figsize=(12 , 8 )) ax = fig.add_axes([0.08 , 0.12 , 0.60 , 0.78 ]) sc = ax.scatter( plot_df["x" ], plot_df["y" ], s=plot_df["point_size" ], c=plot_df["mean" ], cmap="viridis" , vmin=0 , vmax=plot_df["mean" ].max (), alpha=0.9 , edgecolors="none" ) ax.set_xticks(range (len (x_order))) ax.set_xticklabels(x_order, rotation=45 , ha="right" ) ax.set_yticks(range (len (y_order))) ax.set_yticklabels(y_order) ax.set_xlabel("Cell pair" ) ax.set_ylabel("Ligand-receptor interaction" ) ax.set_title("CellPhoneDB: uSMC interactions" ) cax = fig.add_axes([0.76 , 0.57 , 0.025 , 0.30 ]) cbar = fig.colorbar(sc, cax=cax) cbar.set_label("Mean expression" ) legend_pvalues = [0.05 , 0.01 , 0.001 ] def p_to_size (p ): score = -np.log10(max (p, 1 / (n_permutations + 1 ))) return size_min + (score / max_score) * (size_max - size_min) handles = [] for p in legend_pvalues: handle = ax.scatter( [], [], s=p_to_size(p), color="gray" ) handles.append(handle) ax.legend( handles, [f"P = {p:g} " for p in legend_pvalues], title="P value" , loc="upper left" , bbox_to_anchor=(0.75 , 0.48 ), bbox_transform=fig.transFigure, frameon=False , labelspacing=2.0 , handletextpad=1.5 , scatterpoints=1 ) fig.savefig( root / "results" / "CellPhoneDB_uSMC_bubble_plot_final.png" , dpi=300 , bbox_inches="tight" ) plt.show()
以下是示例输出图片:
热图 当我们需要展示不同细胞类型之间的整体通讯情况,我们可以选择绘制显著配体-受体互作数量热图,如下图所示。本部分主要还是用样例数据做吧
我们在绘制此图时,需要的信息主要有二,其一是我们所关注的细胞类型,其二是不同细胞类型之间、不同配体-受体对的统计学显著性,也就是$p$值。现在,我们从细胞注释文件中提取前者,从我们产出的cpdb_results文件中提取后者,用于后续分析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import pandas as pd import numpy as np import matplotlib.pyplot as plt pvalues = cpdb_results["pvalues" ].copy() cell_types = meta["cell_type" ].dropna().unique().tolist() cell_types = sorted (cell_types) print ("细胞类型数量:" , len (cell_types))print (cell_types)
输出示例如下:
细胞类型数量: 42 [‘B_cells’, ‘DC’, ‘EVT_1’, ‘EVT_2’, ‘Endo_F’, ‘Endo_L’, ‘Endo_M’, ‘GC’, ‘Granulocytes’, ‘HOFB’, ‘ILC3’, ‘M3’, ‘MO’, ‘NK’, ‘PV MMP11’, ‘PV MYH11’, ‘PV STEAP4’, ‘Plasma’, ‘SCT’, ‘T_cells’, ‘VCT’, ‘VCT_CCC’, ‘VCT_fusing’, ‘VCT_p’, ‘dDC’, ‘dEpi_lumenal’, ‘dEpi_secretory’, ‘dM1’, ‘dM2’, ‘dNK1’, ‘dNK2’, ‘dNK3’, ‘dS1’, ‘dS2’, ‘dS3’, ‘dT_cells’, ‘dT_regs’, ‘eEVT’, ‘fF1’, ‘fF2’, ‘iEVT’, ‘uSMC’]
接下来,我们需要对每一个细胞类型组合的所有配体-受体对进行筛选,筛选并统计每个细胞类型组合、具有统计学显著性的配体-受体对数量。如前所述,这是热图的色块颜色深浅的决定因素。
1 2 3 4 5 6 7 8 9 10 interaction_counts = pd.DataFrame( 0 , index=cell_types, columns=cell_types, dtype=int ) display(interaction_counts.iloc[:5 , :5 ])
输出示例如下:
B_cells
DC
EVT_1
EVT_2
Endo_F
B_cells
0
0
0
0
0
DC
0
0
0
0
0
EVT_1
0
0
0
0
0
EVT_2
0
0
0
0
0
Endo_F
0
0
0
0
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 alpha = 0.05 for cell_a in cell_types: for cell_b in cell_types: pair_name = f"{cell_a} |{cell_b} " if pair_name not in pvalues.columns: raise ValueError(f"未找到细胞类型配对:{pair_name} " ) pair_pvalues = pd.to_numeric( pvalues[pair_name], errors="coerce" ) n_sig = (pair_pvalues < alpha).sum () interaction_counts.loc[cell_a, cell_b] = n_sig print ("矩阵维度:" , interaction_counts.shape)print ("最大显著互作数量:" , interaction_counts.values.max ())print ("最小显著互作数量:" , interaction_counts.values.min ())display(interaction_counts.iloc[:5 , :5 ])
示例输出如下:
矩阵维度: (42, 42) 最大显著互作数量: 153 最小显著互作数量: 1
B_cells
DC
EVT_1
EVT_2
Endo_F
B_cells
16
37
15
26
39
DC
17
50
20
29
27
EVT_1
13
29
30
39
78
EVT_2
16
29
35
41
88
Endo_F
21
54
54
69
105
数据到手,接下来我们使用Matplotlib的imshow()函数作图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 fig, ax = plt.subplots(figsize=(16 , 14 )) im = ax.imshow( interaction_counts.values, cmap="Reds" , vmin=0 , aspect="equal" , interpolation="nearest" ) ax.set_xticks(range (len (cell_types))) ax.set_yticks(range (len (cell_types))) ax.set_xlabel("Cell type B" ) ax.set_ylabel("Cell type A" ) ax.set_xticklabels( cell_types, rotation=90 , fontsize=7 ) ax.set_yticklabels( cell_types, fontsize=7 ) ax.set_title("CellPhoneDB: Significant ligand-receptor interaction counts" ) cbar = fig.colorbar( im, ax=ax, fraction=0.035 , pad=0.02 ) cbar.set_label("Number of significant interactions" ) fig.tight_layout() fig.savefig( root / "results" / "CellPhoneDB_interaction_heatmap.png" , dpi=300 , bbox_inches="tight" ) plt.show()
当然,通过指定cell_types(或cella_types、cellb_types)中的细胞类型,可以查看特定细胞类型组合之间的配体-受体对显著关系。因较简单,只需更改参数即可,在此不再展开。
弦图 弦图也是体现细胞通讯关系的一种重要可视化手段。如下图所示,圆形中的每一个扇区代表细胞类型,不同扇区之间可以“弦”带连接,表示这两种细胞之间存在互作关系。同时,当细胞类型组合中,具有统计学显著性的配体-受体对数量越多,则相应的弦带越粗。
但与前面所介绍的热力图不同,如果我们把所有的细胞类型都放进同一张弦图中,则会显得臃肿,且不便于阅读。因此,弦图主要用于观察特定细胞类型之间的细胞通讯关系。在这里,我们将会以子宫平滑肌细胞(uSMC)为中心,筛选出与其通讯关系最为密切的若干细胞类型,再为这些细胞类型绘制弦图。
与热图一致,我们需要提取细胞类型名称,及每个细胞类型组合的所有配体-受体对的经验$p$值,并进行筛选和统计。下面的代码与热图部分一致。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import pandas as pd import numpy as np import matplotlib.pyplot as plt pvalues = cpdb_results["pvalues" ].copy() cell_types = meta["cell_type" ].dropna().unique().tolist() cell_types = sorted (cell_types) interaction_counts = pd.DataFrame( 0 , index=cell_types, columns=cell_types, dtype=int ) alpha = 0.05 for cell_a in cell_types: for cell_b in cell_types: pair_name = f"{cell_a} |{cell_b} " if pair_name not in pvalues.columns: raise ValueError(f"未找到细胞类型配对:{pair_name} " ) pair_pvalues = pd.to_numeric( pvalues[pair_name], errors="coerce" ) n_sig = (pair_pvalues < alpha).sum () interaction_counts.loc[cell_a, cell_b] = n_sig
我们指定uSMC为关注的细胞类型,并计数uSMC与其他细胞类型之间显著的配体-受体对数量。
1 2 3 4 5 6 7 8 9 10 11 12 focus_cell = "uSMC" partner_scores = ( interaction_counts.loc[focus_cell] + interaction_counts[focus_cell] ) partner_scores = partner_scores.drop(focus_cell) partner_scores = partner_scores.sort_values(ascending=False ) display(partner_scores.head(10 ))
示例输出:
Endo_M 263 Endo_L 252 fF2 251 fF1 249 Endo_F 234 dS2 226 dS3 224 eEVT 214 dS1 186 PV STEAP4 179 Name: uSMC, dtype: int64
接下来,我们选取uSMC与和uSMC细胞通讯关系最明显的8个细胞类型绘制弦图。当然,首先还是得构建仅包含这些细胞类型的矩阵。我们可以从interaction_counts这个大矩阵中提取出相应的子矩阵,再将两种方向的细胞互作数量相加得到对称矩阵。
1 2 3 4 5 6 7 8 9 10 top_n = 8 top_partners = partner_scores.head(top_n).index.tolist() selected_cells = [focus_cell] + top_partners sub_counts = interaction_counts.loc[selected_cells, selected_cells].copy() chord_counts = sub_counts + sub_counts.T np.fill_diagonal(chord_counts.values, 0 ) display(chord_counts)
示例输出如下:
uSMC
Endo_M
Endo_L
fF2
fF1
Endo_F
dS2
dS3
eEVT
uSMC
0
263
252
251
249
234
226
224
214
Endo_M
263
0
225
243
239
203
212
202
226
Endo_L
252
225
0
230
242
201
201
189
204
fF2
251
243
230
0
218
228
203
198
204
fF1
249
239
242
218
0
190
219
209
201
Endo_F
234
203
201
228
190
0
202
180
198
dS2
226
212
201
203
219
202
0
178
187
dS3
224
202
189
198
209
180
178
0
183
eEVT
214
226
204
204
201
198
187
183
0
此外,为了让图片更加直观,我们可以设置一阈值;当细胞类型组合之间的显著互作关系数量低于此阈值时,则不显示二者之间的弦(也就是将相应的显著互作数量设置为0)。
1 2 3 4 5 6 min_interactions = 20 chord_counts = chord_counts.where( chord_counts >= min_interactions, 0 )
我们终于可以来绘制弦图了!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from pycirclize import Circoscircos = Circos.initialize_from_matrix( chord_counts, space=5 , cmap="tab20" , label_kws=dict (size=10 ), link_kws=dict ( alpha=0.7 , ec="white" , lw=0.5 ) ) fig = circos.plotfig() fig.savefig( root / "results" / "CellPhoneDB_uSMC_chord_diagram.png" , dpi=300 , bbox_inches="tight" ) fig.show()
示例输出: