1
votes

@zohar.kom helped me immensely with his response to my query asking how to add my own dictionary of labels to a directed graph

Is it also possible to set the edge attribute to include the edge weight labels for weighted, directed graphs having self-loops? For example, I have the following for a simple weighted, directed graph having five nodes, labelled A, B, C, D, and E stored in a dictionary called labels.

# Digraph from nonsymmetric adjacency matrix.
 A=npy.matrix([[2,2,7,0,0],[0,2,6,3,0],[0,0,0,2,1],[0,0,0,0,4],
 [4,0,0,0,0]])
 labels={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
 G=nx.DiGraph(A)

 # Set node labels to A, B, C, D, E
 nx.set_node_attributes(G, {k:{'label':labels[k]} for k in 
 labels.keys()})
 D=to_agraph(G)

 # Modify node fillcolor and edge color.
 D.node_attr.update(color='blue',style='filled',fillcolor='yellow')
 D.edge_attr.update(color='blue',arrowsize=1,label="???")
 D.layout('dot')
 D.draw('Graph.eps')

Is there a way to insert something where I have ??? to include labelled edge weights, or perhaps a way to set the edge attribute on G before using D=to_agraph(G)?

1

1 Answers

1
votes

This can be done as follows:

  1. Read edges weights when creating the original (networkx) graph.
  2. Set an attribute named 'label' with the appropriate value, in your case it can be the weight value for example.

The rest stays the same:

import networkx as nx
import numpy as npy

A = npy.matrix([[2, 2, 7, 0, 0], [0, 2, 6, 3, 0], [0, 0, 0, 2, 1], [0, 0, 0, 0, 4],
                [4, 0, 0, 0, 0]])
labels = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)

# Set node labels to A, B, C, D, E
nx.set_node_attributes(G, {k: {'label': labels[k]} for k in labels.keys()})
nx.set_edge_attributes(G, {(e[0], e[1]): {'label': e[2]['weight']} for e in G.edges(data=True)})
D = nx.drawing.nx_agraph.to_agraph(G)

# Modify node fillcolor and edge color.
D.node_attr.update(color='blue', style='filled', fillcolor='yellow')
D.edge_attr.update(color='blue', arrowsize=1)
pos = D.layout('dot')
D.draw('Graph.eps')

Creating the graph is here done by G = nx.from_numpy_matrix(A, create_using=nx.DiGraph) which will keep the weights (unlike the original implementation).

Adding 'label' attribute to the edges is done with nx.set_edge_attributes(G, {(e[0], e[1]): {'label': e[2]['weight']} for e in G.edges(data=True)}).

The result is:

enter image description here