在NetworkX中访问Multigraph的属性 [英] Access attributes of a Multigraph in NetworkX
问题描述
我正在使用此问题中的代码: networkx -根据边缘属性更改颜色/宽度-结果不一致,因为它几乎可以回答我的问题,但是我正在使用Multigraph,这就是为什么该问题的答案对我没有帮助的原因.
I am using code from this question: networkx - change color/width according to edge attributes - inconsistent result because it almost answers my question, but I am working with a Multigraph, which is why the answer to that question is not helping me.
我需要根据权重绘制线条粗细的图形,但该图形绘制不正确.我确定问题是由于边缘的顺序造成的.这是我的代码:
I need to draw a graph with line thicknesses based on the weights but the graph is being drawn incorrectly. I am sure the problem is because of the order of the edges. Here is my code:
我有一个多重图形,它是由看起来像这样的边组成的:
I have a multigraph which is made up of edges that look like this:
edgies = [(1,2, {'color': 'r'}),(2,3,{'color': 'b'}),(3,4,{'color':'g'})]
G = nx.MultiGraph()
G.add_edges_from(edgies, color = 'color')
pos = nx.circular_layout(G)
edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
nx.draw(G, pos, edges=edges, edge_color=colors)
plt.show()
我得到的错误如下:
colors = [G[u][v]['color'] for u,v in edges]
KeyError: 'color'
如果我仅使用图形,则此代码有效,但在使用多图形时会出现错误.如果您需要任何进一步的说明,请告诉我.谢谢.
This code works if I am only using a graph but gives the error when working with a multigraph. Please let me know if you need any further clarification. Thanks.
推荐答案
更改导致错误的行
colors = [print(G[u][v]) for u,v in edges]
我们可以看到您真正在看的是:
We can see what you are actually looking at is:
{0: {'color': 'r'}}
{0: {'color': 'b'}}
{0: {'color': 'g'}}
我假设networkx会将其存储在哪个图上作为键,因此您只需要首先访问键[0],就像这样:
I assume networkx is storing which graph it is on as the key, so you just need to access key [0] first, like this:
colors = [G[u][v][0]["color"] for u,v in edges]
此访问模式在 https:/上有所记录/networkx.github.io/documentation/networkx-1.9.1/reference/classes.multigraph.html 在边缘部分.
This access pattern is somewhat documented on https://networkx.github.io/documentation/networkx-1.9.1/reference/classes.multigraph.html in the edges section.
这篇关于在NetworkX中访问Multigraph的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!