1

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?

2
  • If you can use graphviz here is an approach (requires pygraphviz or pydot) stackoverflow.com/questions/22312334/… Commented May 25, 2014 at 22:28
  • The example you provided works on Digraph. Mine is undirected. Commented May 26, 2014 at 7:00

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

I copy paste your code, run the command and still get a directed - no self looped graph ???
Could you show the output dot file and associated drawing?
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
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.
Sad that it is still not possible to do many years after =( I was hoping that networkx was the tool to switch from graphviz, I want to have some easy way to interactively draw graphs based on adj matrix and generating dot and processingt it with graphviz is a no-go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.