Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using networkx and trying to find cycles in graphs. I wrote the following code:

import networkx as nx
import matplotlib.pyplot as plt
import pylab

tg = nx.Graph()

h_lat_dir = {1: [("A", "A"), ("B", "B"), ("A", "B")], 2: [("C", "D")],
    3: [("C", "F")], 4: [("F", "F")], 5: [("C", "C"), ("C", "E"), ("D", "E"), ("E", "E")],
    6: [("D", "D")]}

for wght, edgelist in h_lat_dir.iteritems():
    tg.add_edges_from(edgelist, weight=wght)

print nx.cycle_basis(tg)


nx.write_dot(tg, 'multi.dot')
nx.draw_graphviz(tg)
pylab.show()

the result is

[['A'], ['B'], ['C'], ['F'], ['E', 'D', 'C'], ['D'], ['E']]

and this drawing enter image description here

Why can't I see the self_loops? (every vertex has one) Is it possible to draw them somehow?

share|improve this question
    
If you can use graphviz here is an approach (requires pygraphviz or pydot) stackoverflow.com/questions/22312334/… –  Aric May 25 at 22:28
    
The example you provided works on Digraph. Mine is undirected. –  Yannis May 26 at 7:00
add comment

1 Answer

Using the NetworkX interface to Graphviz (through pygraphviz or pydot):

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([(0,1), (0,2), (1,1), (1,2)])
nx.write_dot(G,'graph.dot')

Then run

dot -Tpng graph.dot > graph.png

enter image description here

share|improve this answer
    
I copy paste your code, run the command and still get a directed - no self looped graph ??? –  Yannis May 27 at 8:53
    
Could you show the output dot file and associated drawing? –  Aric May 27 at 11:58
    
graph.dot: strict digraph { 0 -> 1; 0 -> 2; 1 -> 2; } and the image (how can I upload it here???) is like yours with directed edges 0->1 0->2 1->2 and no edge 1->1 –  Yannis May 28 at 7:16
    
It seems there is something wrong with the pygraphviz or pydot (not sure which one you are using) installation. If you use nx.Graph() and send that to nx.write_dot() you should get a graph not a digraph in the dot output. –  Aric May 29 at 3:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.