ichbinangela
ichbinangela

Reputation: 55

Weight for edges according to number of occurence in NetworkX

Say that I have nodes ['a','b','c'] in the network, and the pairs are stored in a list:

[('a','b'), ('a','b'), ('b','a'), ('b','c'), ('a','c')]

I want to create a weighted network graph using NetworkX and matplotlib. Since the pair ('a','b') occurs 3 times (in an undirected network, ('b','a') also counts), while both ('b','c') and ('a','c') only occurs 1 time, I would like to change the width of the edges based on their weight.

Could anybody shed some light on this?

Upvotes: 2

Views: 2020

Answers (1)

elelias
elelias

Reputation: 4761

Something like this should work. Find out whether edge exists and if it does update the weights

default_weight = W
G = nx.Graph()
for nodes in node_list:
    n0 = nodes[0]
    n1 = nodes[1]
    if G.has_edge(n0,n1):   
       G[n0][n1]['weight'] += default_weight
    else:
       G.add_edge(n0,n1, weight=default_weight)

Upvotes: 3

Related Questions