You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Scanpy绘制各细胞簇的细胞占比分布图?

解决Scanpy细胞簇数量统计与占比绘图问题

1. 统计每个细胞簇的细胞数量

直接对adata.obs中的Leiden聚类列(根据你的实际聚类结果列名调整,比如leiden或leiden_0.6)做计数:

import pandas as pd

# 替换为你的聚类列名,比如'leiden'或'leiden_0.6'
cluster_counts = adata.obs['leiden'].value_counts().sort_index()
print(cluster_counts)

执行后会按簇编号排序,输出每个簇对应的细胞总数。

2. 计算各簇占比并绘制比例图

无需使用pd.crosstab,直接基于计数结果计算占比并生成柱状图:

import matplotlib.pyplot as plt

# 计算各簇占总细胞数的百分比
cluster_proportions = cluster_counts / adata.n_obs * 100

# 绘制柱状图
ax = cluster_proportions.plot(kind='bar', figsize=(10, 6), title='各细胞簇占总细胞数的比例')
ax.set_xlabel('细胞簇编号')
ax.set_ylabel('占比 (%)')

# 为每个柱子标注具体百分比数值
for p in ax.patches:
    height = p.get_height()
    ax.annotate(f'{height:.1f}%',
                xy=(p.get_x() + p.get_width() / 2., height),
                xytext=(0, 3),
                textcoords="offset points",
                ha='center', va='bottom')

plt.show()

注意事项

  • 代码中的聚类列名需与你adata.obs中实际的Leiden聚类列名一致,比如如果聚类时设置了分辨率为0.6,列名可能是leiden_0.6,直接替换即可。
  • 可根据需求调整figsize、title及坐标轴标签的内容和样式。

内容的提问来源于stack exchange,提问作者pythonbeginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:13:14