4

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?

Dair
  • 15,910
  • 9
  • 62
  • 107
  • Do you have exactly 2 sets of edges? I personally often find a network line graph more informative in such a case. For example, something like [this](https://github.com/paulbrodersen/network_line_graph). – Paul Brodersen Jun 19 '18 at 16:18
  • @Paul Atm, I am under constraints to have a circular graph but otherwise, yes, you are correct. The project sure does look interesting! – Dair Jun 19 '18 at 20:08

1 Answers1

3

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.

Gambit1614
  • 8,547
  • 1
  • 25
  • 51