Search code examples
pythonnetwork-programmingmatplotlibnetworkxweighted

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?


Solution

  • 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)