Python networkx - 根据边缘属性更改颜色/宽度 - 结果不一致
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25639169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
networkx - change color/width according to edge attributes - inconsistent result
提问by timeislove
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().
使用h[][][];访问属性对我来说看起来有点笨拙 ;是否可以通过点约定访问它,例如edge.color for edge in h.edges().
Or did I miss anything?
还是我错过了什么?
回答by Aric
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:
传递给绘图函数的边的顺序很重要。如果您不指定(使用edges 关键字),您将获得G.edges() 的默认顺序。像这样显式给出参数是最安全的:
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:

这会产生如下输出:


