关于python:networkx-根据边缘属性更改颜色/宽度-结果不一致

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

我设法正确生成了图形,但是在进行了更多测试后,发现以下两个不同代码行的结果不一致:

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

这种方法产生一致的输出,而以下按照边缘的顺序产生错误的颜色/大小:

1
2
3
colors = list(nx.get_edge_attributes(h,'color').values())
widths = list(nx.get_edge_attributes(h,'width').values())
nx.draw_circular(h, edge_color=colors, width=widths)

但是,在我看来,以上两行都依赖于函数调用以按边缘顺序返回属性。 为什么结果不同?

使用h[][][]访问属性对我来说似乎有点笨拙; 是否可以通过点号约定访问它,例如 edge.color for edge in h.edges()

还是我错过了什么?


传递给绘图功能的边的顺序很重要。 如果不指定(使用edges关键字),则将获得G.edges()的默认顺序。 显式给出如下参数是最安全的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

结果是这样的:
enter image description here


字典是用于NetworkX图形的基础数据结构,从Python 3.7+开始,它们维护插入顺序。
这意味着我们可以安全地使用nx.get_edge_attributes来检索边缘属性,因为可以保证每次运行Graph.edges()(在内部由get_edge_attributes调用)具有相同的边缘顺序。

因此,在绘制时,我们可以根据get_edge_attributes返回的结果直接设置诸如edge_colorwidth的属性。 这是一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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')

enter image description here