网络错误?颜色放错了位置



i人,我正在尝试使用NetworkX模块绘制网络图,但是我的结果我没想到,我开始问自己是否是任何模块问题!

我在类中有此代码:

def plotGraph(self):
    conn = []
    nodeLabel = {}
    for node_idx in self.operatorNodes:
        print("i = ", node_idx)
        print(self.node[node_idx].childs)
        for child in self.node[node_idx].childs:
            conn.append((child.idx, node_idx))
    for i in range(self.nn):
        nodeLabel[i] = str(i) + ": " + self.node[i].opString
    node_color = ['blue'] * self.nn
    #for i in range(self.nOutputs):
    #    node_color[i] = 'red'
    node_color[0] = 'red'
    print('Graph Conn = ', conn)
    print('Graph Color = ', node_color)
    # you may name your edge labels
    labels = map(chr, range(65, 65 + len(conn)))
    print('nodeLabel = ', nodeLabel)
    draw_graph(conn, nodeLabel, node_color=node_color, labels=labels)

从图片中,我可以看到draw_graph内部传递的内容是(draw_graph代码基于https://www.udacity.com/wiki/wiki/creating-network-graphs-withs-with-python):

Graph Conn =  [(2, 0), (3, 0), (4, 1), (5, 1), (6, 2), (7, 2), (8, 5), (9, 5)]
Graph Color =  ['red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue']
nodeLabel =  {0: '0: mul', 1: '1: mul', 2: '2: mul', 3: '3: cte', 4: '4: cte', 5: '5: sum', 6: '6: cte', 7: '7: cte', 8: '8: cte', 9: '9: cte'}

但图是以下

draw_graph代码是:

def draw_graph(graph, nodeLabel, node_color, labels=None, graph_layout='shell',
               node_size=1600, node_alpha=0.3,
               node_text_size=12,
               edge_color='blue', edge_alpha=0.3, edge_tickness=1,
               edge_text_pos=0.3,
               text_font='sans-serif'):
    # create networkx graph
    G=nx.DiGraph()
    # add edges
    for edge in graph:
        G.add_edge(edge[0], edge[1])
    # these are different layouts for the network you may try
    # shell seems to work best
    if graph_layout == 'spring':
        graph_pos = nx.spring_layout(G)
    elif graph_layout == 'spectral':
        graph_pos = nx.spectral_layout(G)
    elif graph_layout == 'random':
        graph_pos = nx.random_layout(G)
    else:
        graph_pos = nx.shell_layout(G)
    # draw graph
    nx.draw_networkx_edges(G, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color)
    nx.draw_networkx_labels(G, graph_pos, labels=nodeLabel, font_size=node_text_size, font_family=text_font)
    if labels is None:
        labels = range(len(graph))
    edge_labels = dict(zip(graph, labels))
    nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos)
    nx.draw(G, graph_pos, node_size=node_size, alpha=node_alpha, node_color=node_color)

可以看出,0位置的图形颜色为红色,剩余的图应为蓝色,但图将其放在第三个节点中!我没有办法访问节点1的良好,显然是放错了节点!节点颜色位于以下位置[2、0、3、4、5,....]。

使用nx.draw并将其传递给(可选)颜色列表时,它将这些颜色分配给节点,以与(可选)nodelist相同的顺序。但是您没有定义nodelist。因此,它将默认为G.nodes()的任何顺序。

由于网络图的基础数据结构是字典,因此您必须处理以下事实:您不能依靠节点具有任何指定的顺序。

尝试按照您想要的顺序将nodelist传递到nx.draw命令中。

最新更新