Dair
Dair

Reputation: 16240

Coloring, weighting and drawing a MultiGraph in networkx?

This answer demonstrates how to draw a graph with custom colors and edge thickness using the following code:

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)

Suppose however, that I want to graph a multi graph like:

G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='b',weight=6)

Calling something like draw should result in a total of three points. Point 1 and 2 should have both a red and blue line between them, similarly 2 and 3 should have both a red and blue line between them as well.

This fails to work for multigraphs because the multiple edges requires a different storage technique. Is there a relatively easy way around this?

Also, I believe this question and answer does not apply. The questioner uses the MultiGraph object, however, the actual graph is not a multigraph. The solution, is to chose the first (and, in his case, only) edge. In this case, however, both edges are needed in the drawing phase.

Is there a way to graph the multiple edges with different colors and weights in networkx?

Upvotes: 4

Views: 2747

Answers (1)

Gambit1614
Gambit1614

Reputation: 8801

You just need to access the edges of a multigraph in a different way

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=8)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='c',weight=6)

pos = nx.circular_layout(G)

edges = G.edges()

colors = []
weight = []

for (u,v,attrib_dict) in list(G.edges.data()):
    colors.append(attrib_dict['color'])
    weight.append(attrib_dict['weight'])


nx.draw(G, pos, edges=edges, edge_color=colors, width=weight, )
plt.show()

enter image description here

Here is another combination of edges

G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='b',weight=6)

enter image description here

You can read more about accessing multigraph edges here.

Upvotes: 3

Related Questions