Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a DOT file in Python?

I have a digital circuit simulator and need to draw a circuit diagram almost exactly like in this question (and answer) Block diagram layout with dot/graphviz

This is my first encounter with DOT and graphviz. Fortunately the DOT language specification is available and there are many examples as well.

However one detail is still unclear to me and I'm asking as a total newbie: I have a complete data to draw a graph. How do I create a DOT file from it?

As a text line by line?

# SIMPLIFIED PSEUDOCODE
dotlines = ["digraph CIRCUIT {"]
for node in all_nodes:
    dotlines.append("  {}[{}];".format(node.name, node.data))
for edge in all_edges:
    dotlines.append("  {} -> {};".format(edge.from_name, edge.to_name))
dotlines.append['}']
dot = "\n".join(dotlines)

Or should I convert my data somehow and use some module which exports it in the DOT format?

like image 527
VPfB Avatar asked Oct 18 '25 15:10

VPfB


1 Answers

You might consider pygraphviz.

>>> import pygraphviz as pgv
>>> G=pgv.AGraph()
>>> G.add_node('a')
>>> G.add_edge('b','c')
>>> G
strict graph {
        a;
        b -- c;
}

I disagree with @MatteoItalia's comment (perhaps it's a matter of taste). You should become familiar with available packages for your task. You start off with simple graphs, and don't see a reason to use a (very simple) package. At some point, your graphs' complexity might grow, but you'll keep on rolling your own solution to something readily available.

like image 179
Ami Tavory Avatar answered Oct 20 '25 04:10

Ami Tavory