Dimuth Ruwantha
Dimuth Ruwantha

Reputation: 705

Draw Graphs proportional to weight of edges using networkx

I'm having a Graph to display, but it should be displayed where edges are proportional to the weight. I used networkx library to draw the graph but it draw nodes randomly. Here is the part of my code to display graph:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
# Added nodes and Edges
pos = nx.spring_layout(G)
nx.draw(graph, pos=pos, nodelist=nodes, with_labels=True)
plt.show()

How can I create a graph where the edge length is weighted?
If it helps I'm also open to use a different library than matplotlib.

Upvotes: 1

Views: 1473

Answers (1)

dan
dan

Reputation: 1

The graphviz force directed algorithm outputs what I want. (But I am not sure why it is different than the spring layout from networkx)

import networkx as nx 
import pylab as plt 
from networkx.drawing.nx_agraph import graphviz_layout
    
G = nx.Graph()
G.add_node(1) 
G.add_node(2) 
G.add_node(3) 
G.add_node(4)
    
G.add_edge(1,2, len=4.5) 
G.add_edge(2,3, len=2.5) 
G.add_edge(3,4, len=7) 
G.add_edge(4,1, len=10) 
G.add_edge(3,1, len=4.5) 
G.add_edge(4,2, len=9) 

pos=graphviz_layout(G) 
nx.draw(G, pos, node_size=1600, node_color=range(len(G)), with_labels=True, cmap=plt.cm.Dark2) 
plt.show()

output

Upvotes: 0

Related Questions