1

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()
user2209979
  • 159
  • 1
  • 5
  • 10
  • You have given us a list of requirements, but what have you tried to solve your own problem? What is not working as you expect? Do you understand the code you posted? – tacaswell Oct 26 '13 at 15:30
  • Did I not post my code and an image? – user2209979 Oct 27 '13 at 01:22
  • Your code is 90% setting up the network and then calling two function from `nx`, removing one of which will solve one of your problems. You will get better results here if you show honest effort to solve your own problem first. – tacaswell Oct 27 '13 at 03:46
  • I don't understand what is not honest about my effort – user2209979 Oct 27 '13 at 07:59
  • What have you tried to remove the edgeweights? What didn't work about it? What have you tried to put arrow heads on the directed edges? What didn't work about it? What have you tried to get self-loops? What didn't work about it? You did not post a question, you posted a list of requirements. People here tend to be happy to help you solve your problems, but are less willing to do your work for you. – tacaswell Oct 27 '13 at 17:55
  • OK I figure out the weights issue. I didn't realise I could just delete the nx.draw_networkx_edge_labels code. I also made it look a bit prettier, however, I am still having problems with self-loops. Would you mind if I posted my code? Or could you direct me to some code? – user2209979 Oct 28 '13 at 01:23
  • You should edit the question with what you have tried for the self loops. – tacaswell Oct 28 '13 at 02:20
  • I have edited the code. I tried G.add_edge(1,1) without any luck. – user2209979 Oct 29 '13 at 06:15
  • possible duplicate of [Networkx, Edge label in self loop not printed.](http://stackoverflow.com/questions/11973955/networkx-edge-label-in-self-loop-not-printed) – mdml Nov 01 '13 at 00:24

1 Answers1

2

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

enter image description here

Aric
  • 24,511
  • 5
  • 78
  • 77