user1717931
user1717931

Reputation: 2501

display edge weights on networkx graph

I have a dataframe with 3 columns: f1, f2 and score. I want to draw a graph (using NetworkX) to display the nodes (in f1 and f2) and edge-values to be the 'score'. I am able to draw the graph with nodes and their names. But, I am unable to display the edge-scores. Can anyone help please?

This is what I have so far:

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt


feature_1 = ['Boston', 'Boston', 'Chicago', 'ATX', 'NYC']
feature_2 = ['LA', 'SFO', 'LA', 'ATX', 'NJ']
score = ['1.00', '0.83', '0.34', '0.98', '0.89']

df = pd.DataFrame({'f1': feature_1, 'f2': feature_2, 'score': score})
print(df)

G = nx.from_pandas_edgelist(df=df, source='feature_1', target='feature_2', edge_attr='score')
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)

#nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()

Upvotes: 7

Views: 8291

Answers (1)

vurmux
vurmux

Reputation: 10020

You correctly tried to use nx.draw_networkx_edge_labels. But it uses labels as edge_labels and you didn't specified it anywhere. You should create this dict:

labels = {e: G.edges[e]['score'] for e in G.edges}

And uncomment nx.draw_networkx_edge_labels function:

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt


feature_1 = ['Boston', 'Boston', 'Chicago', 'ATX', 'NYC']
feature_2 = ['LA', 'SFO', 'LA', 'ATX', 'NJ']
score = ['1.00', '0.83', '0.34', '0.98', '0.89']

df = pd.DataFrame({'f1': feature_1, 'f2': feature_2, 'score': score})
print(df)

G = nx.from_pandas_edgelist(df=df, source='f1', target='f2', edge_attr='score')
pos = nx.spring_layout(G, k=10)  # For better example looking
nx.draw(G, pos, with_labels=True)
labels = {e: G.edges[e]['score'] for e in G.edges}
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()

So the result will looks like:

enter image description here


P.S. You also have incorrect source/target in nx.from_pandas_edgelist. You should have:

source='f1', target='f2'

Instead of:

source='feature_1', target='feature_2'

Upvotes: 13

Related Questions