networkx - change color/width according to edge attributes - inconsistent result

后端 未结 2 636
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 03:31

I managed to produce the graph correctly, but with some more testing noted inconsistent result for the following two different line of codes:

colors = [h.edg         


        
2条回答
  •  渐次进展
    2020-11-29 03:58

    The order of the edges passed to the drawing functions are important. If you don't specify (using the edges keyword) you'll get the default order of G.edges(). It is safest to explicitly give the parameter like this:

    import networkx as nx
    
    G = nx.Graph()
    G.add_edge(1,2,color='r',weight=2)
    G.add_edge(2,3,color='b',weight=4)
    G.add_edge(3,4,color='g',weight=6)
    
    pos = nx.circular_layout(G)
    
    edges = G.edges()
    colors = [G[u][v]['color'] for u,v in edges]
    weights = [G[u][v]['weight'] for u,v in edges]
    
    nx.draw(G, pos, edges=edges, edge_color=colors, width=weights)
    

    This results in an output like this: enter image description here

提交回复
热议问题