1

I'm sure this is very basic, but is it possible to specify an arbitrary number of edges between nodes when constructing a graph? I've been searching under terms: 'directed graph', 'multiple directed graph', 'parallel edges', 'add_edges', etc.

Say, I have four nodes: A, B, C, D and I want to show: A to B, has 600 edges A to C, has 100 edges A to D, has 400 edges

I'm thinking something like:

import networkx as nx
G = nx.MultiDiGraph()
G.add_node('a', {'b': 600, 'c':100, 'd':400})
G.add_node('b')
G.add_node('c')
G.add_node('d')

(Except, obviously this isn't correct.)

Serenity
  • 35,289
  • 20
  • 120
  • 115
Colman McMahon
  • 175
  • 1
  • 17

1 Answers1

2

According to documentation: https://networkx.github.io/documentation/development/tutorial/tutorial.html you have to add edges from a list of tuples:

import networkx as nx

a = {'b': 600, 'c':100, 'd':400}
MG=nx.MultiGraph()
MG.add_weighted_edges_from([('a', k, v) for k, v in a.iteritems()], weight='weight')
print MG.edges(data='weight')

Output:

[('a', 'c', 100), ('a', 'b', 600), ('a', 'd', 400)]
Serenity
  • 35,289
  • 20
  • 120
  • 115
  • 1
    You've added single edges and assigned a weight to them (possibly what the OP needs, but not what he asked for). To add multiple edges, you can do something like `MG.add_edges_from([('a','b')]*600)` – Joel Jul 03 '16 at 12:58
  • Thanks! Both methods give me multiple edges which is great. When I plot them, though, I only see a single edge line from node 'a' to the targets. I expected (hoped?) to see multiple separate edges lines. I'm trying to plot the amount of interactions from a source to its targets (something like those flight-path plots). – Colman McMahon Jul 03 '16 at 20:44
  • 1
    By default you can not plot multi-edged graph by networkx. Look at this question: http://stackoverflow.com/questions/10379448/plotting-directed-graphs-in-python-in-a-way-that-show-all-edges-separately – Serenity Jul 03 '16 at 22:39
  • 1
    Can anyone tell me how to plot "Multi-edges graph" with NetworkX or is there any work around solution to do this ? – Pearapon Joe Jul 11 '19 at 11:35