4

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?

Community
  • 1
  • 1
VPfB
  • 14,927
  • 6
  • 41
  • 75
  • 2
    The file format seems to be simple enough, I see no reason to bring in a library (especially since any library will probably require you to provide your graph in their own data structures). – Matteo Italia Jan 29 '16 at 06:35
  • 1
    I suggest you use gvgen. Makes it really simple. – Paul Prescod Nov 08 '20 at 17:40

2 Answers2

11

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.

Frank Kusters
  • 2,544
  • 2
  • 21
  • 30
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
1

You can use gvgen. It is a pure Python library.

Install through pip install gvgen.

Example:

>>> from gvgen import GvGen
>>> g = GvGen()
>>> a = g.newItem('a')
>>> b = g.newItem('b')
>>> c = g.newItem('c')
>>> _ = g.newLink(b, c)
>>> g.dot()
/* Generated by GvGen v.1.0 (https://www.github.com/stricaud/gvgen) */

digraph G {
compound=true;
   node1 [label="a"];
   node2 [label="b"];
   node3 [label="c"];
node2->node3;
}

Credits to Paul Prescod's comment.

Frank Kusters
  • 2,544
  • 2
  • 21
  • 30