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

后端 未结 2 664
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 03:49

    Dictionaries are the underlying data structure used for NetworkX graphs, and as of Python 3.7+ they maintain insertion order. This means that we can safely use nx.get_edge_attributes to retrieve edge attributes since we are guaranteed to have the same edge order in every run of Graph.edges() (which is internally called by get_edge_attributes).

    So when plotting, we can directly set attributes such as edge_color and width from the result returned by get_edge_attributes. Here's an example:

    G = nx.Graph()
    G.add_edge(0,1,color='r',weight=2)
    G.add_edge(1,2,color='g',weight=4)
    G.add_edge(2,3,color='b',weight=6)
    G.add_edge(3,4,color='y',weight=3)
    G.add_edge(4,0,color='m',weight=1)
    
    colors = nx.get_edge_attributes(G,'color').values()
    weights = nx.get_edge_attributes(G,'weight').values()
    
    pos = nx.circular_layout(G)
    nx.draw(G, pos, 
            edge_color=colors, 
            width=list(weights),
            with_labels=True,
            node_color='lightgreen')
    

提交回复
热议问题