Adding edge labels with networkx

Question:

I have the following matrix

print(adj)

[[  0   0   7   0   0   0   2   1   0   0]
 [  0   0   5  10   8  10   4  62  13   1]
 [  7   5   0  17  13  90   3  10   0   1]
 [  0  10  17   0   2  11 218  20   0   0]
 [  0   8  13   2   0   2   0  30   0   0]
 [  0  10  90  11   2   0   4  43   9   0]
 [  2   4   3 218   0   4   0  11   0   0]
 [  1  62  10  20  30  43  11   0   2   2]
 [  0  13   0   0   0   9   0   2   0   1]
 [  0   1   1   0   0   0   0   2   1   0]]

displayed as the following graph using

count=10
rows, cols = np.where(adj > count)
edges = zip(rows.tolist(), cols.tolist())
G = nx.DiGraph()
G.add_edges_from(edges)
p = to_pydot(G)
p.write_dot('test.dot')

enter image description here

How do I label the edges using the values in the matrix? i.e., the arrow from 5->7 should have the label 43, and likewise the arrow from 7->5 should also be labelled 43.

The plot was produced using

% dot -Gdpi=600 -Gfontsize=12 -Glabel=count_10 -Tjpg -Grankdir=LR test.dot -o test.jpg
Asked By: Mike Yearworth

||

Answers:

Use set_edge_attributes and a dictionary comprehension:

# G.add_edges_from(edges)
nx.set_edge_attributes(G, {tuple(k): {'label': v} for *k, v in
                           zip(rows, cols, adj[rows, cols])})
# p = to_pydot(G)

graph with labeled edges

Output of the dictionary comprehension:

{(1, 7): {'label': 62},
 (1, 8): {'label': 13},
 (2, 3): {'label': 17},
 ...
 (7, 5): {'label': 43},
 (7, 6): {'label': 11},
 (8, 1): {'label': 13}}
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.