NetworkX directed graph, no weights and self arc

2019-07-23 06:46发布

问题:

I would like a self-loop from node 1 to itself. I tried G.add_edge(1,1) but that did not work. My code is as follows

import networkx as nx
import pylab

G = nx.DiGraph()

G.add_node(1,pos=(1,1))

G.add_node(2,pos=(0,0))
G.add_node(3,pos=(2,0))
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(1,1)


pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)

pylab.show()

回答1:

The edge is there - it just isn't drawn by the NetworkX Matplotlib drawing code. You can use Graphviz:

import networkx as nx
import pylab

G = nx.DiGraph()

G.add_node(1,pos="100,100")

G.add_node(2,pos="0,0")
G.add_node(3,pos="200,0")
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(1,1)

print G.edges(data=True)
# [(1, 1, {}), (1, 2, {}), (1, 3, {})]

nx.write_dot(G,'graph.dot')
# use -n to suppress node positioning (routes edges)
# run dot -n -Tpng graph.dot >graph.png