0

I have a multidigraph that I'd like to plot in networkx, but I can't get it to work. The reason it needs to be a multidigraph is because the transactions can go both ways. Here's the code I have:

import pandas as pd
import numpy as np
import networkx as nx
from itertools import combinations,permutations

names = ['Mike','Bob','Phil']
permutations = list(permutations(names, 2))

col1 = [val[0] for val in permutations]
col2 = [val[1] for val in permutations]
transactions = [1,3,5,3,9,2]

df = pd.DataFrame({'Sender':col1,'Recipient':col2,'Num_Transactions':transactions})

So df looks like this:

enter image description here

Now here's the code I'm using to create and plot the graph:

G = nx.MultiDiGraph()
G.add_nodes_from(names)

E = list(zip(df['Sender'].tolist(),df['Recipient'].tolist(),df['Num_Transactions'].tolist()))

G.add_weighted_edges_from(E)

def draw_graph(G, nodes_position,weight):
    nx.draw(G,nodes_position, with_labels=True, font_size=15, node_size=400,edge_color='gray',arrowsize=10)
    if weight==True:
        edge_labels = nx.get_edge_attributes(G,'weight')
    nx.draw_networkx_edge_labels(G,nodes_position, edge_labels=edge_labels)

draw_graph(G,nx.circular_layout(G),True)

And this is the error message I'm getting:

enter image description here

How do I fix this?

AI92
  • 387
  • 1
  • 8
  • The error is occurring because [`nx.get_edge_attributes()`](https://networkx.org/documentation/stable/reference/generated/networkx.classes.function.get_edge_attributes.html) returns a tuple of length 3 where the additional value is the key for the edge. I'd suggest just using a `DiGraph` instead of `MultiDiGraph` unless you know you'll need additional edges between nodes. However, since networkx doesn't support *multiple edges with edge labels* very well, you'll have to use a trick from [this post](https://stackoverflow.com/questions/22785849) or another plotting package to show both weights. – Frodnar Nov 12 '21 at 19:25
  • Does this answer your question? [Drawing multiple edges between two nodes with networkx](https://stackoverflow.com/questions/22785849/drawing-multiple-edges-between-two-nodes-with-networkx) – Frodnar Nov 12 '21 at 19:26

0 Answers0