pythonalgorithmgraphnetworkxedges

How do I add weights for edges, when I specified multiple edges, not just 1 specific edge? Networkx


For the following code:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

#Set 1
G.add_edges_from([('A','B'),('A','C'),('C','B')])
#Set 2
G.add_edges_from([('D','A'),('D','B'),('D','C')])
#Set 3
G.add_edges_from([('E','D'),('E','B'),('E','C')])

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G,pos, node_size=500, node_color = 'green')

nx.draw_networkx_edges(G,pos, edgelist = G.edges())

plt.show()

I want to add weights to the edges. To my understanding, the weights are just 1 for all the edges. I want to modify the weights of every single edge in the graph.

From the follow documentation, I see that you can change the weight of a single node by adding : https://networkx.org/documentation/stable/reference/generated/networkx.linalg.attrmatrix.attr_sparse_matrix.html

I want to add different weights to each edge. For example, ('A','B') is 0.1 weight, ('A', 'C') is 0.2 weight, etc.

I also looked at the following post: NetworkX: how to add weights to an existing G.edges()?

However, it looks like they are iterating through each edge for a specific weight for all all edges, which is not what I want, rather I want specific weights for specific edges.


Solution

  • When adding the edges one can specify a dictionary containing arbitrary edge properties:

    from networkx import DiGraph
    G = DiGraph()
    G.add_edges_from([('A','B', {'weight': 0.1}),('A','C', {'weight': 0.2})])
    print(G.edges(data=True))
    # [('A', 'B', {'weight': 0.1}), ('A', 'C', {'weight': 0.2})]
    

    Alternatively, one can specify a triplet, where the first two elements are source/destination and the third element is weight, and then use the .add_weighted_edges_from method:

    from networkx import DiGraph
    G = DiGraph()
    G.add_weighted_edges_from([('A','B', 0.1),('A','C', 0.2)])
    print(G.edges(data=True))
    # [('A', 'B', {'weight': 0.1}), ('A', 'C', {'weight': 0.2})]