Andrew Earl - 8 months ago 115

Python Question

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

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.

Answer

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:

```
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.