Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw weight labels with networkx and matplotlib?

Im studying graphs so I'm trying to draw a graph given a dictionary in python using networkx and matplotlib, this is my code:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
graph = {
    "A":["B","C"],
    "B":["D","E"],
    "C":["E","F"],
    "D":["B","G"],
    "E":["B","C"],
    "F":["C","G"],
    "G":["D","F"]
}
x=10
for vertex, edges in graph.items():
    G.add_node("%s" % vertex)
    x+=2
    for edge in edges:
        G.add_node("%s" % edge)
        G.add_edge("%s" % vertex, "%s" % edge, weight = x)
        print("'%s' it connects with '%s'" % (vertex,edge))
nx.draw(G,with_labels=True)

plt.show()

I already tried the function draw_networkx_edge_labels but seems like I need a position for that which I dont have since I add the nodes dynamically, so I need a way to draw the edges labels which fit with my current implementation.

like image 926
Alexis Avatar asked Oct 17 '25 07:10

Alexis


1 Answers

You draw the graph after all nodes are added so you can calculate positions and use nx.draw_networkx_edge_labels(...) according to them:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
graph = {
    "A":["B","C"],
    "B":["D","E"],
    "C":["E","F"],
    "D":["B","G"],
    "E":["B","C"],
    "F":["C","G"],
    "G":["D","F"]
}
x=10
for vertex, edges in graph.items():
    G.add_node("%s" % vertex)
    x+=2
    for edge in edges:
        G.add_node("%s" % edge)
        G.add_edge("%s" % vertex, "%s" % edge, weight = x)
        print("'%s' it connects with '%s'" % (vertex,edge))
# ---- END OF UNCHANGED CODE ----

# Create positions of all nodes and save them
pos = nx.spring_layout(G)

# Draw the graph according to node positions
nx.draw(G, pos, with_labels=True)

# Create edge labels
labels = {e: str(e) for e in G.edges}

# Draw edge labels according to node positions
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()

enter image description here

like image 53
vurmux Avatar answered Oct 20 '25 14:10

vurmux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!