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

tim*_*ove 33 python networkx python-3.x

我设法正确生成了图形,但是对于以下两个不同的代码行,一些更多的测试结果表明结果不一致:

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()))
Run Code Online (Sandbox Code Playgroud)

第一行产生一致的输出,而第二行产生每个边缘的错误颜色/大小.

但是,它看起来我上面的两行都依赖于函数调用来返回每个边缘顺序的属性.为什么结果不同?

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

或者我错过了什么?

Ari*_*ric 55

传递给绘图函数的边的顺序很重要.如果您未指定(使用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)
Run Code Online (Sandbox Code Playgroud)

这导致输出如下: 在此输入图像描述

  • 获取“ValueError:收到无效参数:边缘” - 运行 python3 (3认同)
  • @SCBuergel 边缘参数可以省略 (2认同)

yat*_*atu 12

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

所以在绘图时,我们可以直接从 返回的结果中设置edge_color和等属性。下面是一个例子:widthget_edge_attributes

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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 是的,请注意,在“nx.draw” @tobias 中绘图时,我确实从中构建了一个列表 (2认同)