Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add edge-weights to plot output in networkx

I am doing some graph theory in python using the networkx package. I would like to add the weights of the edges of my graph to the plot output. How can I do this?

For example How would I modify the following code to get the desired output?

import networkx as nx import matplotlib.pyplot as plt  G=nx.Graph() i=1 G.add_node(i,pos=(i,i)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,0)) G.add_edge(1,2,weight=0.5) G.add_edge(1,3,weight=9.8) pos=nx.get_node_attributes(G,'pos') nx.draw(G,pos) plt.savefig("path.png") 

I would like 0.5 and 9.8 to appear on the edges to which they refer in the graph.

like image 778
smilingbuddha Avatar asked Feb 06 '15 18:02

smilingbuddha


People also ask

How do I set weight to edges in NetworkX?

Each edge given in the list or container will be added to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number. weightstring, optional (default= 'weight') The attribute name for the edge weights to be added.

How do you assign weight to edge?

Examples: Input: 1 / | \ 2 3 4 S = 3 Output: 2 All the edges can be assigned weights of 1, so the longest path will in terms of weight will be 2--1--4 or 2--1--3 Input: 1 / 2 / \ 3 4 / \ 5 6 S = 1 Output: 0.50 Assign the given below weights to edges.

What are weights of edges in graphs?

In many applications, each edge of a graph has an associated numerical value, called a weight. Usually, the edge weights are non- negative integers. Weighted graphs may be either directed or undirected. The weight of an edge is often referred to as the "cost" of the edge.


1 Answers

You'll have to call nx.draw_networkx_edge_labels(), which will allow you to... draw networkX edge labels :)

EDIT: full modified source

#!/usr/bin/python import networkx as nx import matplotlib.pyplot as plt  G=nx.Graph() i=1 G.add_node(i,pos=(i,i)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,0)) G.add_edge(1,2,weight=0.5) G.add_edge(1,3,weight=9.8) pos=nx.get_node_attributes(G,'pos') nx.draw(G,pos) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) plt.savefig(<wherever>) 
like image 146
Marcus Müller Avatar answered Sep 23 '22 06:09

Marcus Müller