I'm trying to create an image of a directed graph that shows self-loops using Python's networkx. Networkx does not show them, but other online forums suggest interfacing networkx with graphviz. Here's what I have entered for a five-node directed network, which is being done in Python.
# Import packages
import networkx as nx
import numpy as npy
from networkx.drawing.nx_agraph import to_agraph
#Non-symmetric adjacency matrix with self-loop at 1.
A=npy.matrix([[1,1,1,0,0],[1,0,1,0,0],[1,1,0,1,1],[0,0,1,0,1],
[0,0,1,1,0]])
#Create directed graph
G=nx.DiGraph(A)
#add graphviz layout options (as per advice at
#https://stackoverflow.com/a/39662097)
G.graph['edge'] = {'arrowsize': '0.8', 'splines':
'curved', 'shape': 'circle'}
G.graph['graph'] = {'scale': '3'}
G.graph['node']={'shape': 'circle','fillcolor':'red'}
D = to_agraph(G)
D.layout('dot')
D.draw('multi.png')
Everything works fine. However, I'd like to use the labels I have stored in a Python dictionary as labels={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
I'm not sure how to add this within the graphviz layout options. Obviously, this is for a simple graph, but my dictionary labels are in general larger.
You can do it by setting a 'label' attribute for each node before converting the NetworkX graph to a Graphviz AGraph:
...
labels={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
nx.set_node_attributes(G, {k:{'label':labels[k]} for k in labels.keys()})
D = to_agraph(G)
Which results with: