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

如何用Python基于Excel中的距离矩阵构建系统发育树?

使用Python基于距离矩阵绘制系统发育树的解决方案

需求可行性

完全可以实现。Python拥有多个成熟的生物信息学库,支持从距离矩阵构建并绘制系统发育树,常见的包括scikit-bio、Biopython、ete3等。

问题分析

你之前的代码未成功生成预期树形,核心问题包括:

  • 读取CSV时未将物种名称列设为索引,导致树构建工具无法识别样本标识
  • 距离矩阵为下三角形式,缺失上三角数据,不符合树构建工具对对称矩阵的要求
  • 仅完成树对象构建,缺少可视化步骤

完整实现方案

1. 安装依赖库

执行以下命令安装所需工具包:

pip install pandas scikit-bio matplotlib

2. 完整代码(scikit-bio版本)

import pandas as pd
import skbio
import matplotlib.pyplot as plt

# 读取CSV文件,将第一列设为物种索引
df = pd.read_csv('Book1.csv', index_col=0)
# 补全对称矩阵:将上三角缺失值填充为下三角对应值
df = df.fillna(df.T)

# 转换为scikit-bio要求的DistanceMatrix对象
dm = skbio.DistanceMatrix(df.values, ids=df.index.tolist())

# 构建UPGMA树并绘制
upgma_tree = skbio.tree.upgma(dm)
fig, ax = plt.subplots(figsize=(10, 6))
skbio.draw.tree(upgma_tree, ax=ax, label_func=lambda x: x.name)
plt.title('UPGMA系统发育树')
plt.show()

# 构建NJ树并绘制
nj_tree = skbio.tree.nj(dm)
fig, ax = plt.subplots(figsize=(10, 6))
skbio.draw.tree(nj_tree, ax=ax, label_func=lambda x: x.name)
plt.title('NJ系统发育树')
plt.show()

3. 适配你原有代码的Biopython版本

如果你更倾向于使用DistanceTreeConstructor,可以用以下代码:

import pandas as pd
from Bio.Phylo.TreeConstruction import DistanceMatrix, DistanceTreeConstructor
from Bio.Phylo import draw
import matplotlib.pyplot as plt

# 读取并补全矩阵
df = pd.read_csv('Book1.csv', index_col=0)
df = df.fillna(df.T)

# 转换为Biopython的DistanceMatrix对象
ids = df.index.tolist()
matrix = df.values.tolist()
dm = DistanceMatrix(ids=ids, matrix=matrix)

# 构建并绘制UPGMA树
constructor = DistanceTreeConstructor()
upgma_tree = constructor.upgma(dm)
draw(upgma_tree)
plt.title('UPGMA系统发育树')
plt.show()

# 构建并绘制NJ树
nj_tree = constructor.nj(dm)
draw(nj_tree)
plt.title('NJ系统发育树')
plt.show()

关键注意事项

  • 矩阵补全:距离矩阵必须是对称矩阵,df.fillna(df.T)可快速补全下三角矩阵的缺失部分
  • 数据格式转换:树构建工具无法直接识别Pandas DataFrame,必须转为对应库的DistanceMatrix对象
  • 可视化调整:可通过修改figsize参数调整树形图大小,label_func可自定义物种标签显示方式

内容的提问来源于stack exchange,提问作者Riaz Hussain Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:53:32