我正在尝试使用 BioPython、Phylo 模块构建一棵树。
到目前为止我所做的是这张图片:
每个名称都有一个四位数字,后跟 - 和一个数字:这个数字指的是该序列出现的次数。这意味着 1578 - 22,该节点应表示 22 个序列。
所以现在我知道如何更改节点的每个大小。每个节点都有不同的大小,这很容易做一个不同值的数组:
fh = open(MEDIA_ROOT + "groupsnp.txt")
list_size = {}
for line in fh:
if '>' in line:
labels = line.split('>')
label = labels[-1]
label = label.split()
num = line.split('-')
size = num[-1]
size = size.split()
for lab in label:
for number in size:
list_size[lab] = int(number)
a = array(list_size.values())
但数组是任意的,我想将正确的节点大小放入正确的节点中,我试过这个:
for elem in list_size.keys():
if labels == elem:
Phylo.draw_graphviz(tree_xml, prog="neato", node_size=a)
但是当我使用 if 语句时什么也没有出现。
无论如何都要这样做?
非常感谢!
谢谢大家
最佳答案
我终于搞定了。基本前提是您将使用 labels/nodelist
构建您的 node_sizes
。这样它们就可以正确关联。我确定我遗漏了一些使树看起来 100% 的重要选项,但节点大小显示正确。
#basically a stripped down rewrite of Phylo.draw_graphviz
import networkx, pylab
from Bio import Phylo
#taken from draw_graphviz
def get_label_mapping(G, selection):
for node in G.nodes():
if (selection is None) or (node in selection):
try:
label = str(node)
if label not in (None, node.__class__.__name__):
yield (node, label)
except (LookupError, AttributeError, ValueError):
pass
kwargs={}
tree = Phylo.read('tree.dnd', 'newick')
G = Phylo.to_networkx(tree)
Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False)
node_sizes = []
labels = dict(get_label_mapping(G, None))
kwargs['nodelist'] = labels.keys()
#create our node sizes based on our labels because the labels are used for the node_list
#this way they should be correct
for label in labels.keys():
if str(label) != "Clade":
num = label.name.split('-')
#the times 50 is just a guess on what would look best
size = int(num[-1]) * 50
node_sizes.append(size)
kwargs['node_size'] = node_sizes
posi = networkx.pygraphviz_layout(Gi, 'neato', args='')
posn = dict((n, posi[Gi.node_labels[n]]) for n in G)
networkx.draw(G, posn, labels=labels, node_color='#c0deff', **kwargs)
pylab.show()
结果树
关于python - Phylo BioPython 构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051414/