简体   繁体   English

在NetworkX中访问Multigraph的属性

[英]Access attributes of a Multigraph in NetworkX

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. 我正在使用来自以下问题的代码: networkx-根据边缘属性更改颜色/宽度-结果不一致,因为它几乎可以回答我的问题,但是我正在使用Multigraph,这就是为什么该问题的答案对我没有帮助的原因。

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()

The error I get is as follows: 我得到的错误如下:

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. 谢谢。

Changing the line causing the error to 将导致错误的行更改为

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'}}

I assume networkx is storing which graph it is on as the key, so you just need to access key [0] first, like this: 我假设networkx会将它存储在哪个图上作为键,所以您只需要首先访问键[0],如下所示:

colors = [G[u][v][0]["color"] for u,v in edges]

This access pattern is somewhat documented on https://networkx.github.io/documentation/networkx-1.9.1/reference/classes.multigraph.html in the edges section. https://networkx.github.io/documentation/networkx-1.9.1/reference/classes.multigraph.html的“边缘”部分中对此文档进行了一些记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM