networkx - change color/width according to edge at

2019-01-17 07:50发布

问题:

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

nx.draw_circular(h,edge_color=[h.edge[i][j]['color'] for (i,j) in h.edges_iter()], width=[h.edge[i][j]['width'] for (i,j) in h.edges_iter()])

nx.draw_circular(h,edge_color=list(nx.get_edge_attributes(h,'color').values()), width=list(nx.get_edge_attributes(h,'width').values()))

The first line results consistent output, while the second produce wrong color/size per the orders of edges.

However, it looks to me the above two lines both rely on the function call to return the attributes per the order of edges. Why the different results?

It looks a bit clumsy to me to access attributes with h[][][]; is it possible to access it by dot convention, e.g. edge.color for edge in h.edges().

Or did I miss anything?

回答1:

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: