如何从networkx到不同颜色的边缘

时间:2010-12-06 13:27:53

标签: python networkx

我已经建立了一张树形图像,请参阅question 现在我有一些主要的团体 一组具有绿色和棕色的节点,并且具有“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')

所以我已经完成了与上面类似的功能,而不是节点,我改为get_edge。 试试这个:

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

其中edge是:

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

也许有办法说出T是否在名字中,然后为边缘着色。 你觉得怎么样?

有谁知道怎么做?

谢谢

1 个答案:

答案 0 :(得分: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

Tree with colours