2

我已经建立了一个树图像,请参阅问题
现在我有一些主要的群体。
一组具有绿色和棕色的节点,并具有“B”和“A”。第二组只有粉色节点和“T”,最后一组有黄色、橙色和蓝色,以及字母“L”、“X”和“H”。颜色是指节点的颜色,字母属于名称。所以我想为不同组的边缘着色。

#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


labels = dict(get_label_mapping(G, None))
for label in labels.keys():
if str(label) != "Clade":
        num = label.name.split('-')
        if 'T' in num[0]:
            node_colors.append('#CC6699')
        elif 'X' in num[0]:
            node_colors.append('r')
        else:
            node_colors.append('y')

所以我做了与上面类似的功能,而不是node,我改为get_edge。试试这个:

  for edge in edges.keys():
        if str(edge) != "Clade":
            if 'T' in edge:
                edge_colors.append('b')

其中边缘是:

(Clade(branch_length=-0.00193, name='T-7199-8'), Clade(branch_length=0.00494))

也许有一种方法可以说明 T 是否名副其实,然后给边缘上色。你怎么看?

有人知道该怎么做吗?

谢谢

4

1 回答 1

4

我猜(因为我不知道该片段如何适合其余代码)您正在迭代节点,并为每个节点添加一种颜色到列表中。就像错误消息所暗示的那样,您需要计算出每个边缘所需的颜色。那会更棘手。

好的,明白了!代码可以稍微整理一下,但这有效。

#Define your centre node: you need to pull this out of the graph. Call it b.
# The number changes each time: look for a Clade(branch_length=0.03297)
# Its neighbors have branch lengths .00177, .01972, .00774.
b = G.nodes()[112]

# Recursively paint edges below a certain point, ignoring ones we've already seen
def paintedges(graph, startnode, colour):
    for node in graph.neighbors(startnode):
        if node not in alreadyseen: # alreadyseen is in global scope
            graph[startnode][node]["colour"] = colour
            alreadyseen.add(node)
            paintedges(graph, node, colour)

alreadyseen = set([b])
G[b][G.neighbors(b)[0]]["colour"] = "red"
paintedges(G, G.neighbors(b)[0], "red")
G[b][G.neighbors(b)[1]]["colour"] = "blue"
paintedges(G, G.neighbors(b)[1], "blue")
G[b][G.neighbors(b)[2]]["colour"] = "green"
paintedges(G, G.neighbors(b)[2], "green")

# Now make a list of all the colours, in the order networkx keeps the edges
edgecolours = [G[f][t]["colour"] for f,t in G.edges()]
kwargs["edge_color"] = edgecolours

有颜色的树

于 2010-12-06T13:55:22.830 回答