fishbacp
fishbacp

Reputation: 1263

What is the most efficient way to include edge labels when drawing a networkx graph?

I'd like to include edge weight labels when drawing a graph using networkx. I know how to combine the draw_networkx_edge_labels command with draw_networkx_nodes, etc. to do so, but I'm wondering if there's a way to simply add an option when just using draw_networkx instead.

Here's what I have for a simple weighted, undirected network

import networkx as nx
A=npy.matrix([[0,7,7,0,0],[7,0,6,0,0],[7,6,0,2,1],[0,0,2,0,4],[0,0,1,4,0]])
G=nx.from_numpy_matrix(A)
nx.draw_networkx(G, weighted=True)

I tried creating a dictionary whose keys are edge pairs and whose values are the weights and then adding this is an option as follows:

edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) 
nx.draw_networkx(G, weighted=True,edge_labels=edge_labels)

but this did not work either.

Upvotes: 0

Views: 353

Answers (1)

Aguy
Aguy

Reputation: 8059

Hopefully, this might set you in the right direction:

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

A = np.matrix([[0,7,7,0,0],[7,0,6,0,0],[7,6,0,2,1],[0,0,2,0,4],[0,0,1,4,0]])
G = nx.from_numpy_matrix(A)
pos = nx.spring_layout(G)
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])

plt.figure()
nx.draw(G, pos, weighted=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

plt.show()

Upvotes: 1

Related Questions