
Create diagrams with code using Graphviz - adrianancona
https://ncona.com/2020/06/create-diagrams-with-code-using-graphviz/
======
graphviz
We're reluctant to be exposed to too much anger about misfeatures in 20 year
old code that was basically a prototype that escaped from the lab, but go
ahead, ask us anything.

We've gotten a lot of help lately from Magnus Jacobsson, Matthew Fernandez and
Mark Hansen on cleaning up the website and the code base, even some persistent
bugs we could never find ourselves.

Improvements that would benefit the community the most?

\- better default styles that don't look like troff from 1985

\- better default layout parameters in neato than statistical multidimensional
scaling based on shortest path

\- more expressive graph language with classes or templates

\- more robust handling of error conditions like out of memory

\- better documentation to help people find useful tools or just know what
they should be looking for

\- find someone to donate a generic orthogonal routing algorithm based on a
modern algorithm since people want this

\- it would be a big effort, but move the core algorithms to a framework that
supports interaction with layout generation

Hope this makes sense.

~~~
karatestomp
I'd rather have graphviz expose a kind of layout engine such that it can take
the size each node will occupy (determined by whatever's going to draw them)
and use that to create a layout, feeding path info to something that can
handle the actual drawing, than have more drawing options in Graphviz itself.
I think that doing so is (so far as I could tell, last time I tried) extremely
awkward at best is why it's not embedded in basically everything that has any
need whatsoever to draw graphs.

So, I guess:

> \- it would be a big effort, but move the core algorithms to a framework
> that supports interaction with layout generation

If that's what you mean by that.

It'd make it _way_ easier to pretty up Graphviz output. I'd rather have
"renderer" applications that run on top of Graphviz and have Graphviz itself
lose all but its most basic build-in drawing capabilities, than have more of
that built into Graphviz itself.

~~~
cm2187
Doesn't the export to plain give you what you need in term of location and
size of the different items?

[https://graphviz.org/doc/info/output.html#d:plain](https://graphviz.org/doc/info/output.html#d:plain)

~~~
karatestomp
That doesn't let you tell graphviz how large you want to draw each node,
right? Just how large graphviz would draw them? What I'd like is a way to take
styling and drawing outside GraphViz. It's important (for what I'd like) that
graphviz know how large each node is going to be so it can route around them.
If you apply, say, a typeface or padding even very slightly different than
what graphviz was using, or if there are just slight differences in, say, how
a given browser renders a <div>, it could change the size of the rendered
nodes, and you end up with edges drawn under/over nodes.

Much cleaner (and _way_ more useful) to be able to tell graphviz "this is how
large I need this node to be, and that one this size, and the other one such-
and-such, and they are connected thusly, now please give me coords for a
layout"

This isn't just for looks, either: if you want the resulting graph to be
_interactive_ , and perhaps even graphically (drag-n-drop) editable after the
initial graphviz auto-arranging, you're probably wanting output that's not
exactly in graphviz's wheelhouse. You want to tell it node sizes and have it
tell you where to put them.

~~~
cm2187
I think you can have fixed size nodes where you can specify the dimensions.

------
jetrink
I found a great use for Graphviz recently. I needed to implement a model that
was created by a scientist with no programming experience outside of a Fortran
class in the early 1980s. Meanwhile, I didn't have much knowledge of the
subject matter or terminology. The model was described in a multipage Excel
file and an accompanying PDF and I implemented it in Clojure.

In order to help us communicate, I wrote a script that built a data-dependency
graph directly from the code and produced a diagram with Graphviz for the
scientist to review. It helped us to catch a couple errors resulting from my
misinterpretations and it gave the scientist confidence that the code
accurately reflected his design.

~~~
truculent
I have used rather nice clojure library that also uses graphviz under the
bonnet, with great success:

[https://github.com/Engelberg/ubergraph](https://github.com/Engelberg/ubergraph)

Did you use something similar or roll your own?

In any case, your project sounds great and I am glad it was a success.

~~~
jetrink
I used Rhizome[1]. (It looks like it is no longer being maintained, but I
didn't run into any issues.)

1\. [https://github.com/ztellman/rhizome](https://github.com/ztellman/rhizome)

~~~
truculent
Very nice! (and pleasingly similar)

Thanks

------
kragen
A couple of important tips that the article omits:

1\. For manual editing, dot -Tx11 foo.dot displays the graph in a window _and
updates it automatically whenever you save_. So you can have an editor window
open and the dot window and see the results of every tweak. For automatically
generated graphs, this provides you with a window that you can update by
overwriting a file with a new graph description.

2\. Although HTML nodes are more versatile, shape=record is much easier, and
sufficient for a pretty wide range of diagrams.

For doing quick stuff by hand if you don't have Graphviz installed, or if
you're stuck on a Mac without X-Windows, there's
[https://graphviz.christine.website/](https://graphviz.christine.website/). I
like Graphviz a lot; as other people point out, TikZ is capable of a wider
range of graphics, and also you can write programs to generate graphs in TikZ.
But Graphviz is often enough.

A really simple graph like
[https://graphviz.christine.website/#digraph%20G%20%7Ba-%3E%7...](https://graphviz.christine.website/#digraph%20G%20%7Ba-%3E%7Bb-%3E%7Bc-%3E%7Bd-%3E%7Be-%3E%7Bf-%3E%7Bg-%3E%7Bh-%3E%7Bi-%3E%7Bj-%3E%7Bk%7D%7D%7D%7D%7D%7D%7D%7D%7D%7D%3B%7D)
is sometimes good enough without further tweaking, but for, _e.g._ , the top
diagram in [https://github.com/kragen/dumpulse#dumpulse-an-embeddable-
du...](https://github.com/kragen/dumpulse#dumpulse-an-embeddable-dumb-
heartbeat-daemon-in-260-bytes-of-ram-and-350-bytes-of-code), you usually have
to tweak stuff a bit.

~~~
m000
3\. dot pairs nicely with m4 [1] and a Makefile. Without m4, it's a pain to
apply a uniform style on groups of nodes.

[1]
[https://en.wikipedia.org/wiki/M4_(computer_language)](https://en.wikipedia.org/wiki/M4_\(computer_language\))

~~~
kragen
You can put the group of nodes in a subgraph and apply the uniform style to
the subgraph. In
[https://gitlab.com/kragen/bubbleos/-/tree/master/yeso#callin...](https://gitlab.com/kragen/bubbleos/-/tree/master/yeso#calling-
interface-diagram) I did that for example as follows in
[https://gitlab.com/kragen/bubbleos/-/blob/master/yeso/api-
ty...](https://gitlab.com/kragen/bubbleos/-/blob/master/yeso/api-types.dot):

    
    
            subgraph types {
                    node [shape=square];
                    subgraph ints {
                            node [label=int];
                            int bool fd u32in die stride;
                    }
                    long int s32 u8 u32 -> ypix ywin;
                    ...
    

Its expressivity is limited, since it depends on a hierarchical classification
of your nodes and arcs that doesn't always eliminate all duplication, but it's
usually enough to manually style the nodes the way I want without too much
hassle. Because "types" and "ints" aren't "clusters", they don't affect the
layout. (If you do want to use clusters, that can make this approach more
difficult.)dnl

I haven't ever been quite desperate enough to use m4 to generate Graphviz
files, although clearly it is a good fit. My experiences with m4 are more in
the nature of getting way too much rope to hang myself with and then having a
terrible time debugging. I wrote an HTML-generating macro language in m4 in
1994 and have never stopped regretting it.dnl

I do agree about the Makefile. In Dumpulse I used the following Makefile rule:

    
    
        %.png: %.dot
         dot -Tpng < $< > $@
    

That way I can rebuild the README diagrams (if outdated) just by listing
"diagram.png heartbeat.png health-report.png" as dependencies of the "all"
target.
[https://github.com/kragen/dumpulse/blob/master/Makefile](https://github.com/kragen/dumpulse/blob/master/Makefile)

~~~
m000
You only need a couple of line to plug in automatic m4 preprocessing in
Makefile. And perhaps add a .SECONDARY line if you are debugging to prevent
the intermediate .dot files from being deleted.

    
    
        %.dot: %.dot.m4
            m4 < $< > $@
    
    

I use m4 to implement something akin to css classes, only a bit more powerful
because you can do pseudo-subclassing. E.g.

    
    
        define(`base_node', `width=1.75, height=1.0, fontname="Menlo", fontsize=13')
        define(`file',`base_node, shape=note')
        define(`directory',`base_node, shape=folder')
        define(`important', `fontname="Menlo Italic"')
    
        ...
    
        tarball [file, label="foo.tar"];
        vardir  [directory, label="/var"];
        etcdir  [directory, important, label="/etc"];

~~~
kragen
Right! That kind of crosscutting thing is tricky to do with the hierarchical
nature of subgraphs. Without some kind of macro preprocessor you'd end up
doing something like

    
    
        node [width=1.75, height=1.0, fontname="Menlo"];
    
        subgraph files {
            node [shape=note];
            tarball [label="foo.tar"];
            subgraph importantfiles {
                node [fontname="Menlo Italic"];
                ...
            }
        }
    
        subgraph dirs {
            node [shape=folder];
            vardir [label="/var"];
            subgraph importantdirs {
                node [fontname="Menlo Italic"];
                etcdir [label="/etc"];
            }
        }
    

This obviously has the drawback that if you change the importance font, you
have to change it twice instead of once, and you might forget. And clearly
there are cases where that kind of duplication is a bigger problem than the
difficulties with m4.

------
nikeee
Shameless plug: I created an online Graphviz/dot editor which is powered by a
language server that provides auto completion and refactorings. It uses a WASM
version of Graphviz to render the graph. You can try it out here:

[https://edotor.net](https://edotor.net)

~~~
kstenerud
Looks cool, but either the default graph has incorrect comments, or it's buggy
on firefox. There were no lightbulbs, and clicking on "a" did nothing.

------
Schiphol
I like graphviz a lot, but I almost always end up using
[Tikz]([http://www.ctan.org/tex-
archive/graphics/pgf/](http://www.ctan.org/tex-archive/graphics/pgf/)), which
is quite a bit more flexible.

One huge advantage of Tikz is that you can use LaTeX equations natively. E.g.
subscripts and superscripts in graphviz involve jumping through a few hoops,
iirc.

~~~
pletnes
Does it have graph-drawing included?

~~~
Schiphol
That's one of its main uses. One thing it does not do (or I don't know how)
and graphviz does, though, is arranging nodes intelligently so as to minimize
clutter and edge distances. That's one of the nice things in graphviz.

~~~
enriquto
> One thing it does not do (or I don't know how) and graphviz does, though, is
> arranging nodes intelligently

That's exactly what "graph drawing" means [0]. Can tikz choose the position of
the vertices itself or you have to specify the positions yourself? If it is
you who chooses the positions, then tikz does not do "graph drawing".

[0]
[https://en.wikipedia.org/wiki/Graph_drawing](https://en.wikipedia.org/wiki/Graph_drawing)

~~~
mkl
Yes, TikZ can position the vertices itself. E.g. [http://www.tcs.uni-
luebeck.de/downloads/papers/2011/2011-con...](http://www.tcs.uni-
luebeck.de/downloads/papers/2011/2011-configurable-graph-drawing-algorithms-
jannis-pohlmann.pdf) [http://www.tcs.uni-
luebeck.de/downloads/mitarbeiter/tantau/2...](http://www.tcs.uni-
luebeck.de/downloads/mitarbeiter/tantau/2012-gd-presentation.pdf)
[https://tex.stackexchange.com/questions/203692/how-to-
automa...](https://tex.stackexchange.com/questions/203692/how-to-
automatically-draw-a-graph)

~~~
enriquto
That's great! Did these people really implement graph drawing algorithms as
latex macros, or does it call an external program? I'm afraid to look it
myself, lest I discover the truth.

~~~
mkl
Some of it is LaTeX, but the more intensive algorithms are done with embedded
Lua, using LuaLaTeX. There is no external program.

~~~
nyir
Wow, that was a long time ago, very fun project to work on. But yeah, without
deep knowledge of the TeX side you'd likely still struggle a bit to understand
how the two sides interact, at least it was a bit of a struggle for me, maybe
/ hopefully it got a bit better in the meantime.

And thankfully LuaLaTex was ready enough at that time, I can't imagine how bad
it would've been to do this in pure Tex ...

~~~
enriquto
Are you one of the authors of tikz graphdrawing?

~~~
nyir
Just a former student who participated in the first version (let's say draft)
of it, which had no really interesting algorithms in it yet, just the overall
graph framework and integration with the rest of PGF/TikZ.

Really cool project though, one of the few that made it outside of uni.

------
rcarmo
As much as I like Graphviz (and I've been using it for ages) I keep looking
for an equivalent with two features:

\- Nicer, more modern looks (the original is too... LaTeX-y for my tastes)

\- A different layout engine that uses straight arrows and 90 degree turns

So far I haven't been able to find any good replacements, although a few JS
libraries come reasonably close.

~~~
ribasushi
> A different layout engine that uses straight arrows and 90 degree turns

It's not a property of the engine but of the graph itself:

[http://www.graphviz.org/doc/info/attrs.html#d:splines](http://www.graphviz.org/doc/info/attrs.html#d:splines)

[https://stackoverflow.com/a/9055243](https://stackoverflow.com/a/9055243)

------
DavidPeiffer
I love how quickly you can generate a large GraphViz diagram! In a past job we
had the "network drive of shame" (actually all 4 of my internships had that).
So many Excel files which had dependencies which weren't documented at all.

I once made a script which would go through each subdirectory, open every
Excel file, and document all dependencies, and output to a GraphViz diagram.
This enabled me to move a file and know which files would break, absolutely
vital for making changes in that environment.

It wasn't beautiful - VBA checking properties of tables, pivot tables,
examining embedded VBA code searching for the network share URI - but it did
work.

For safety, I copied 200 GB from the network drive locally. 6 months later the
guy in IT was curious why imaging my replacement machine took _so_ long.

\--

Last week I documented how money moves around my various bank accounts. I
needed to make sure all the bills get paid even though I'm switching banks. A
quick GraphViz diagram is proving to be really handy.

------
lihaoyi
I use Graphviz throughout my book
[https://www.handsonscala.com](https://www.handsonscala.com) to render
diagrams. I honestly think it looks pretty good:

\- Dependency graph between chapters in the book:
[https://www.handsonscala.com/chapter-1-hands-on-
scala.html#s...](https://www.handsonscala.com/chapter-1-hands-on-
scala.html#section-1-3-1-chapter-dependency-graph)

\- Tree-shaped `Vector` with structural sharing:
[https://www.handsonscala.com/chapter-4-scala-
collections.htm...](https://www.handsonscala.com/chapter-4-scala-
collections.html#section-4-2-2-structural-sharing)

\- Singly-linked `List` with shared tails:
[https://www.handsonscala.com/chapter-4-scala-
collections.htm...](https://www.handsonscala.com/chapter-4-scala-
collections.html#section-4-2-5-immutable-lists)

\- Collections class inheritance hierarchy:
[https://www.handsonscala.com/chapter-4-scala-
collections.htm...](https://www.handsonscala.com/chapter-4-scala-
collections.html#section-4-4-common-interfaces)

The book's home page above also has a nice actor-message-passing diagram
rendered with Graphviz (might need to scroll down a bit).

My only preferred change to the default style is `node [shape=box width=0
height=0]`. Otherwise the nodes have tons of white space that makes the graph
a lot more bulky than it really needs to be.

The automated layout engine gives me exactly what I want 90% of the time, and
the last 10% is usually isn't too hard to coax into looking good via
`rank=same`s or `constraint=false` or similar. In particular, the examples
above required zero coaxing: I just specified the graph structure, and that's
the layout that popped out.

I ended up doing a lot of prototyping in
[http://www.webgraphviz.com/](http://www.webgraphviz.com/) and before pasting
the final DOT into my markdown file. IntelliJ has a Graphviz/DOT plugin, but
it's not as seamless as using that web editor. The graphs definitely end up
looking a lot more consistent than anything I could come up with dragging
boxes around in microsoft office or google docs.

The graphs don't look fancy and design-y, but they're simple and
straightforward and get the point across clearly.

~~~
kragen
Those all look great! I'm jealous! I think the green arrows do look fancy and
design-y.

I've sometimes been able to get surprisingly flashy results with cluster
subgraphs with background colors.

------
ColinWright
I use GraphViz a lot. Here it the Twitter conversation that ensued when I
asked a question about the use of Group Theory "In Real Life":

[https://www.solipsys.co.uk/Chitter/GroupTheory_IRL.svg](https://www.solipsys.co.uk/Chitter/GroupTheory_IRL.svg)

~~~
Lunatic666
I'm using it at work, e.g. to visualize state machines. It makes it a lot
easier to discuss it with business people. In Java there is a great library
which translates code into graphviz markup: guru.nidi/graphviz-java

~~~
h91wka
I don't want to diminish importance of graphviz, but PlantUML is better suited
for visualizing state machines, message sequence diagrams and whatnot.

~~~
xamde
PlantUML is a good syntax. Under the hood... it renders via GraphViz

~~~
baq
which is exactly why it's great! :)

------
bregma
Fun hidden use of graphviz: if you use GCC's <regex> in your code, try
defining _GLIBCXX_DEBUG and call the member function _M_dot() on your regex
objects.

We left that in when developing the <regex> module because it turned out to be
very useful for debugging regular expressions, not just the regex
implementation itself.

~~~
shpongled
That's cool! Every time I end up implementing some kind of graph structure,
writing a simple dot output method is one of the first things I do. It's
incredibly useful for debugging stuff, and only takes a couple minutes to put
together.

------
hnarayanan
One interesting thing is that graphviz can output to many formats, including
SVG. This makes it great for websites, where one can later do things like
later tweak the colours on the fly.

e.g. [https://harishnarayanan.org/writing/kubernetes-
django/](https://harishnarayanan.org/writing/kubernetes-django/)

~~~
lihaoyi
Being SVG also means you can style them via CSS, allowing simple
interactivity. For example, you can make graph edges change color or become
thicker when you mouse over them, making it easier to follow edges in a large
messy graph

------
edparcell
I'm a big fan of Graphviz. My old team created a library called Loman, which
we open-sourced, which uses DAGs to represent calculations. Each node
represents a part of the calculation and contains a value, similar to a cell
in an spreadsheet, and Loman tracks what is stale as you update inputs. Loman
includes built in support for creating diagrams using Graphviz. In our quant
research we have found that invaluable when revisiting old code, as it allows
you to quickly see the structure and meaning of graphs with hundreds of nodes,
containing thousands of lines of code.

We've found it quite useful for quant research, and in production it works
nicely because you can serialize entire computation graph which gives an easy
way to diagnose what failed and why in hundreds of interdependent
computations. It's also useful for real-time displays, where you can bind
market and UI inputs to nodes and calculated nodes back to the UI - some
things you want to recalculate frequently, whereas some are slow and need to
happen infrequently in the background.

[1] Github:
[https://github.com/janushendersonassetallocation/loman](https://github.com/janushendersonassetallocation/loman)

[2] Docs:
[https://loman.readthedocs.io/en/latest/](https://loman.readthedocs.io/en/latest/)

[3] Examples:
[https://github.com/janushendersonassetallocation/loman/tree/...](https://github.com/janushendersonassetallocation/loman/tree/master/examples)

------
speeder
I wasted in my current project too many time trying to make GViz behave. It is
a tool that has lots of potential but has some insanely obvious flaws, I
literally wasted 8 work days just trying to make a small planning document,
because Graphviz won't cooperate unless you start to pile up attributes one
after the other in Byzantine hacks.

1\. Why the "cluster" word is needed on subgraph names? I am not making my
project in English.

2\. Why I can't move a whole subgraph to the "end" or "start" ? GViz attempts
to make all graphs compact (regardless your settings) and thus tends to shove
subgraphs in "random" places.

3\. Why nodes sometimes leave their subgraph and end on another one? Even when
the end result makes no sense? (My graph ended with several places where "a"
and "c" is on one cluster and "b" is in a another, with lots of "U" shaped
edges connecting then)

The official website has a bunch of broken links.

"Weight" attribute often is ignored...

And the list goes on.

Stack overflow is full of bizarre solutions to Graphviz behavior, for example
minimum edge length (that for some reason is in inches despite most of the
planet using mm)

------
RobinL
At ObservbleHQ they use this to automatically visualise dependencies:
[https://observablehq.com/@observablehq/notebook-
visualizer](https://observablehq.com/@observablehq/notebook-visualizer)

More generally, Observable gives you a 'playground' where you can
interactively see graphviz results:
[https://observablehq.com/@observablehq/graphviz](https://observablehq.com/@observablehq/graphviz)

Another option - which for some applications is visually more appealing - is
Elk: [https://observablehq.com/@observablehq/notebook-
visualizer-e...](https://observablehq.com/@observablehq/notebook-visualizer-
elk-edition)

There's a simple start notebook here:
[https://observablehq.com/@tmcw/elk](https://observablehq.com/@tmcw/elk)

------
dan199
I find plantuml a more useful abstraction for software stuff (uses graphviz
under the covers)

[https://plantuml.com/](https://plantuml.com/)

------
rakoo
The Zim wiki software has a plugin for graphviz ([https://www.zim-
wiki.org/manual/Plugins/Diagram_Editor.html](https://www.zim-
wiki.org/manual/Plugins/Diagram_Editor.html)), where you can edit your graph
and see the results in real time. Very helpful if only for this feature

------
siraben
Graphviz's syntax easy enough to programmatically generate, here's the course
dependencies for CS classes at my university, for instance, generated by a
Haskell program that scraped the appropriate data.

[https://i.imgur.com/OZarGSg.png](https://i.imgur.com/OZarGSg.png)

------
hmottestad
I love generating DOT from my Java programs. I recently implemented a query
explainer that would output the query plan as DOT.

Btw. For those working with DOT I've always found it great to be able to copy-
paste it right onto a webpage and see the results. My current favourite tool:
[https://dreampuf.github.io/GraphvizOnline/](https://dreampuf.github.io/GraphvizOnline/)

------
ciceryadam
[https://github.com/mingrammer/diagrams](https://github.com/mingrammer/diagrams)
\- uses graphviz under the hood, and it's super easy to extend the list of
available nodes. Also you can tweak it with node/edge/graph attributes to fit
in your style/needs.

------
bvrmn
I've been trying to use graphviz for many years. Idea of storing graph data as
text with presentation hints is very appealing. But simple diagrams can be
made in corresponding software (draw.io) way too faster. For complex diagrams
I had to constantly fight with layout engine and place too many hints.

------
kmstout
I've gotten a lot of mileage from Graphviz over the years. As an example
outside of work, I wanted a way to depict parse trees for an article I was
writing. So, after I wrote an EBNF parser generator (great fun!), I wrote a
little utility to apply a grammar to stdin and emit to stdout a JSON
representation of the resulting parse tree; another utility handles converting
the JSON to dot, which I can plot at my leisure.

[https://github.com/reindeereffect/tools-from-
blog/tree/maste...](https://github.com/reindeereffect/tools-from-
blog/tree/master/yakety)

~~~
jjice
I was writing a parser recently, and I was fed up with having to look at a
textual tree output. I did a bit of Googling, found Graphviz, and I had the
whole thing working in like 15 minutes. I think it's absolutely essential to
me now anytime I work with trees/graphs that I need to visualize.

------
RBerenguel
I used graphviz as the main visualisation for bear-note-graph [1], and it's
super-easy to use programmmatically, and gives decent-looking results even for
large graphs. It is also pretty customizable.

I have a WIP version now using D3, and that one has been harder to manage
(when the graph is too large you don't want to have it animate the layout on
the fly). If you are curious, I used the same D3 code I have in the WIP to
present a sitemap of my blog [2]

    
    
        [1] https://github.com/rberenguel/bear-note-graph
        [2] https://mostlymaths.net/sitemap/

~~~
abathur
Curious what you think about something, since it seems like you've been
iterating on the challenge of a big interactive graph lately.

I've been pondering building a big interactive chart, like a decision tree or
differential diagnosis chart, that maps goals/needs/problems to
docs/examples/tools (for the Nix/NixOS/Nixpkgs ecosystem, but the basic
concept applies to any sprawling ecosystem where discovery is hard).

I recently stumbled on [https://github.com/mermaid-
js/mermaid](https://github.com/mermaid-js/mermaid), which seems like it has an
interaction model that could support what I have in mind (minus the question
of whether there are performance cliffs that'd make it unsuitable).

If you considered mermaid while working on bear-note-graph, could you share
the conclusions you came to?

~~~
RBerenguel
I didn't check mermaid for bng, but had checked it before (I like visual
representations of knowledge, no matter what they are for). Although I found
it interesting, my gut feeling here was that if my problem's solution (at that
point it was just out of curiosity) was going to be JS-based at some point, I
should go directly for D3 (I already had experience, but not recent, with D3).

Mermaid uses D3 under the scenes, so depending on your specifics it could be
the best solution anyway, though. Performance wise, I'd expect it to be OK (D3
is pretty fast in most cases) although if there are any issues down the road,
fixing them from such a high level library as mermaid could be daunting (it's
"easier" to move down from D3 to paper.js or g.js or any other high
performance canvas renderer if the case arises).

------
buserror
I use graphviz a lot; here I generate a 'call graph' of the codebase of
simavr[0] as a pdf for example [1]. But I also use it for introspection for
complex data structure.

[0]: [http://github.com/buserror/simavr](http://github.com/buserror/simavr)
[1]:
[https://github.com/buserror/simavr/blob/master/doc/simavr_ca...](https://github.com/buserror/simavr/blob/master/doc/simavr_callgraph.pdf)

~~~
yboris
This is excellent! Thank you for the share!

I'm working on a Typescript Call Graph [0] and am leaning towards D3 for my
visualization. But I hope I can generate something as pretty and useful as
your link [1]

[0]: [https://github.com/whyboris/TypeScript-Call-
Graph](https://github.com/whyboris/TypeScript-Call-Graph)

~~~
mthoms
Nice. This will be useful, I'm looking forward to it.

Are you aware of any similar tools for creating class diagrams from TS code?

~~~
yboris
The closest I found was TS-Call-Graph [0] which works well but only on
_classes_ while mine is aimed at _functions_

I have a very rough draft of a graph working [1] (currently hardcoded with a
specific function name) but I intend to make it interactive and to have more
than one visualization of the files.

[0] [https://github.com/Deskbot/TS-Call-Graph](https://github.com/Deskbot/TS-
Call-Graph)

[1] [https://github.com/whyboris/TypeScript-Call-
Graph/pull/1](https://github.com/whyboris/TypeScript-Call-Graph/pull/1)

------
databasher
I use GraphViz to produce a visual, browsable version of the NIEM data model.
GraphViz can output images and HTML maps, which allows easy building of
clickable web pages with hover notes.

See the diagram at
[https://niem.github.io/model/4.2/nc/ItemType/](https://niem.github.io/model/4.2/nc/ItemType/)
. Hover over a term to see its definition. Click on a term to navigate to its
diagram.

------
zwischenzug
Another plug: I wrote about using Graphviz for representing project management
dependencies in code and collaborating with my team here:

[https://zwischenzugs.com/2017/12/18/project-management-as-
co...](https://zwischenzugs.com/2017/12/18/project-management-as-code-with-
graphviz/)

The OP page is a really great intro, I could have used it as a reference when
I was doing that work.

------
Der_Einzige
You might as well just use something like plantUML instead of this from a
productivity standpoint.

However, I don't want to discount the value of Graphviz. Python has a little
known class diagram generator built into pylint which uses Graphviz for its
rendering and its pretty cool. You can find out just how bad your #BIGCORPS
code architecture is just by checking a reasonably large project with Pylints
class diagraming tool...

------
bollu
There seems to be somewhat of a myth that it's hard to get GraphViz diagrams
to "look nice". I (obviously biased) feel that the diagrams I generated for my
reference implementation of RETE look quite clean:
[https://github.com/bollu/rete#example-rete-diagrams-to-
learn...](https://github.com/bollu/rete#example-rete-diagrams-to-learn-from)

~~~
bvrmn
The instant place to look for graphviz issues is a distance between arrow
head/tail to node. But yes your diagrams are very clean indeed!

------
kristiandupont
I'm going to hijack this thread to ask if anyone knows of a library that
creates "hand drawn"-style sequence diagrams from code? I basically want this:
[https://bramp.github.io/js-sequence-diagrams/](https://bramp.github.io/js-
sequence-diagrams/) \-- but sadly, this one only seems to run inside a
browser.

~~~
mpk
PlantUML supports this
[https://plantuml.com/handwritten](https://plantuml.com/handwritten)

Add this to any diagram to get the effect you want,

    
    
      skinparam handwritten true
      skinparam monochrome true
    

Demo: [https://tinyurl.com/ycdu7owa](https://tinyurl.com/ycdu7owa)

~~~
AlexITC
Also, you can use [https://collabuml.com](https://collabuml.com) to
collaboratively build diagrams.

------
asdkhadsj
Can anyone recommend a resource for learning how to diagram?

Notably, I don't want to free-design directional relationships that are
counter intuitive to what people expect. Eg, if Service A calls Service B,
does the arrow go to Service B? What about the response? I imagine there are a
ton of little questions like this and I'd like to learn to write what people
expect to see.

~~~
mr_tristan
I’d actually start with Tufte:
[https://www.edwardtufte.com/tufte/books_vdqi](https://www.edwardtufte.com/tufte/books_vdqi)

There are standards like UML, but I’ve never found those to be as useful to
start with. It’s best to treat this as a “design problem”: first, answer the
question: “what am I communicating”.

Then, maybe look into conventions - but often you’ll find less need for one
“master UML diagram” and instead use many, smaller diagrams embedded within
reference docs.

I feel like project reactor did a good job here:
[https://projectreactor.io/docs/core/release/api/reactor/core...](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#merge-
int-org.reactivestreams.Publisher...-)

Personally I’d like to see more related to inheritance, but I’ll take what I
can get. The tooling can be a pain to embed automatic diagrams in

------
kinow
Great post. I've used it to generate UML diagrams from databases with
sqlalchemy, and more recently to generate protobuf diagrams in Python (needed
it quickly to update some documentation): [https://github.com/kinow/protobuf-
uml-diagram](https://github.com/kinow/protobuf-uml-diagram)

One thing that I think was not mentioned in the article, are invisible nodes,
which are really handy:
[https://stackoverflow.com/search?q=invisible+node+%5Bgraphvi...](https://stackoverflow.com/search?q=invisible+node+%5Bgraphviz%5D)

Some times the existing layouts, ranks, clusters, etc, won't help you to
produce the diagram you have in your mind. So instead of giving up and drawing
it in draw.io or Inkspace (which I used to do), a co-worker showed me how he
was using this technique in several of his diagrams.

------
typpo
I run a web service "QuickChart" that renders Graphviz charts to PNG/SVG so
you can easily bring graphviz diagrams into a web app or spreadsheet. Some
Graphviz fans may find it useful (it's intended as a replacement for the old
Google Image Charts graphviz renderer).

    
    
       https://quickchart.io/chart?cht=gv&chl=<DOT here>
    

e.g.

    
    
       https://quickchart.io/chart?cht=gv&chl=digraph%20MyGraph%20%7Bbegin%20-%3E%20end%7D
    

The service is open source:
[https://github.com/typpo/quickchart](https://github.com/typpo/quickchart)

------
jcpst
Graphviz has improved my development workflow.

I use dot notation, and in spacemacs I can have a buffer with the the png file
that reloads on save.

When debugging distributed enterprise systems, being able to type in the
workflow as you go and then share your findings is awesome.

------
ppsreejith
One of my favourite online graphviz editors for quickly creating something is:
[https://dreampuf.github.io/GraphvizOnline/](https://dreampuf.github.io/GraphvizOnline/)

------
paphillips
GraphViz is great. I used it in a Cypress DSP processor development mini-IDE
(C#) [1]. A diagram is generated for each step of the assembler code showing
the data and addressing. Being able to visual the pipelining of instructions
and data flow was the main motivation. Scrubbing through the program step by
step to see how the state changes made the VLIW assembler programming much
easier.

MIT-license code is here with screenshots:

[1] [https://github.com/paphillips/DFB](https://github.com/paphillips/DFB)

------
brasetvik
Big fan of graphviz.

Lots of interesting tools that use it being posted here, so here's a toy of
mine:
[https://github.com/alexbrasetvik/graphspec](https://github.com/alexbrasetvik/graphspec)

I've used it mostly to mix edge+node definitions in comments in asciidoc or
code, and the non-nested nature makes it easy to compose different sources of
edges and nodes.

(It's just a POC. If you know of something similar that's more actively
developed, I'd be very interested)

~~~
abathur
I'm also interested in this (or something more actively-developed), as it's
the first time I've seen what looks like an answer to a question I've had
recently.

If it helps to know how someone else thinks about it: I've been looking for a
way to _compose_ or _import_ or _include_ a graph or subgraph defined in one
file into multiple other graphs. I've started to assume I'll just need a
preprocessor or template engine.

In my case, I'm interested in the feasibility of building a really big
interactive chart, like a decision tree or differential diagnosis chart, to
help users discover docs/examples/tools/tutorials etc. that can meet their
needs or fix their problems, and I suspect a single-file approach just isn't
going to scale well. (Composition/inclusion is a bit of an MVP focus, I guess.
I think it would also be nice to be able to have a good way to generate
versions of the graphs from multiple perspectives--like 1. a diagnosis chart
that helps users identify a common formulation of their problem and its most-
canonical solution, 2. a graph that helps users figure out what a command-line
tool is used for by mapping each one to the problems they solve, 3. a graph
that helps users who've run into trouble solving X with Y by mapping it to
more known solutions and showing additional context on the pros/cons/limits of
each.)

An aside: I noticed a TODO on your repo about supporting a comment syntax.
Your existing syntax is very close to directives from reStructuredText
([https://docutils.sourceforge.io/docs/ref/rst/restructuredtex...](https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#directives)).
Since it's already a Python project, I wonder if it makes sense to piggy-back
on docutils, or at least borrow the comment syntax
([https://docutils.sourceforge.io/docs/ref/rst/restructuredtex...](https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#comments)).

------
tejtm
DOT all the things!

(simple) Makefiles [0] XML [1] Json [2]

[0]
[https://github.com/TomConlin/MakefileViz](https://github.com/TomConlin/MakefileViz)
[1]
[https://github.com/TomConlin/xpath2dot](https://github.com/TomConlin/xpath2dot)
[2]
[https://github.com/TomConlin/json_to_paths](https://github.com/TomConlin/json_to_paths)

------
stilisstuk
Dokuwiki has a very usefull graphviz plugin.
[https://www.dokuwiki.org/plugin:graphviz](https://www.dokuwiki.org/plugin:graphviz)

------
alexchantavy
For Python I love using Pyan
([https://github.com/davidfraser/pyan](https://github.com/davidfraser/pyan),
though I'm not sure this is the main repo but it's the first result on Google
and it seems to work fine). My workflow is

cd ~/projectdir pyan3 path/to/file/i/want.py --uses --no-defines --colored
--grouped --annotated --dot > dotfile.dot dot -Tsvg dotfile.dot > diagram.svg

------
martyvis
Graphviz got me a company paid trip to Orlando back in 2003. I built a Perl
script that parsed a firewall configuration file to produce a visualisation of
the policy and relationships between the various entities like network
addresses, protocols and so on. My abstract I wrote on it was good enough to
be selected to attend our company technical conference, but fortunately not so
good that I would have to write a full paper add present ;-)

------
simonsarris
If you need a library with a _lot_ more power out of the box (interaction
tools, undo manager, data binding, lots of layouts, and many more
visualization options), I make GoJS:
[https://gojs.net/latest/index.html](https://gojs.net/latest/index.html)

It's not free, however, though you can use the evaluation version indefinitely
if you wanted to make your own graphs for personal use.

------
iso-8859-1
Used Viz.js (Graphviz compiled to JavaScript) for an animated B-Tree
visualization, and it works great:

[http://ysangkok.github.io/js-clrs-
btree/btree.html#{%22actio...](http://ysangkok.github.io/js-clrs-
btree/btree.html#{%22actions%22:\[\[%22initTree2%22%2C{%22keys%22:\[1%2C2%2C3\]}\]%2C\[%22insert%22%2C4\]%2C\[%22insert%22%2C5\]%2C\[%22insert%22%2C6\]%2C\[%22insert%22%2C7\]\]%7D)

------
jxramos
Navigation is very important too for large graphs. Go with yEd instead and
graphml, networkx is great too
[https://networkx.github.io/documentation/stable/reference/re...](https://networkx.github.io/documentation/stable/reference/readwrite/graphml.html)

------
hukola
Just wanted to show my appreciation to the team supporting Graphviz. It's an
instrumental capability of a library[0] we developed to turn Java DSL code
into a diagram.

Thank you, keep it as it is, it's just great!

[0] [https://github.com/ing-bank/baker](https://github.com/ing-bank/baker)

------
wodenokoto
I’d like to write some scripts that can take some of my code and produce a
graph of it.

Things I’d like is for example to draw a GCP cloud build file, or something
like that.

What would be a good intermediate format for this? I’ll read an xml or yaml
file into a python list of dicts and then loop through it and write ...
Graphviz? Mermaid? Tikz?

What do you guys recommend?

~~~
q3k
Using graphviz for visualizing these things is fast and easy.

    
    
        print('digraph foo {')
        # adj_list contains tuples of (parent node name, child node name)
        for parent, child in adj_list:
            print(f'{parent} -> {child}')
        print('}')
    

Redirect that to a file and view with `xdot`, done.

I've done exactly this a few days ago to visualize the Linux build graph:
[https://q3k.org/u/73839114a0e5ee65002029892a069dd1b645a8f9f0...](https://q3k.org/u/73839114a0e5ee65002029892a069dd1b645a8f9f0b336e4cc3f622874772960.png)

~~~
wodenokoto
Sweet! It was excactly this kind of advice I was hoping to get. Thank you.

------
magjac
Great article. You might also have use for [http://magjac.com/graphviz-visual-
editor/](http://magjac.com/graphviz-visual-editor/) and the new
[https://forum.graphviz.org](https://forum.graphviz.org)

------
cosmic_quanta
How convenient, I just added graphviz support to my Pandoc filter, pandoc-
plot. It renders graphviz code blocks into graphs (also works with other
plotting toolkits).

[https://github.com/LaurentRDC/pandoc-
plot](https://github.com/LaurentRDC/pandoc-plot)

------
lalo2302
What I've been craving for is a way to respect the order of the nodes when
being drawn. Since currently it re-orders them to occupy less space.

With this I would be able to finish my data flow diagram out of a functional
programming project. To describe in a visual way how the function calls are
happening.

~~~
chrisseaton
Isn't the point of data flow that the order doesn't matter? Otherwise it's
control flow isn't it? I use GraphViz to render both data flow and control
flow without issue
[https://engineering.shopify.com/blogs/engineering/understand...](https://engineering.shopify.com/blogs/engineering/understanding-
programs-using-graphs).

------
leephillips
I use this quite often. Graphviz and the dot language are really useful tools.
Here is my roundup of a collection of free-software network graphing tools:

[https://lwn.net/Articles/639998/](https://lwn.net/Articles/639998/)

------
yzeisler
I thought this article might of been about creating diagrams from already
created code, which is a project I worked on with Ruby code
[https://visualize-ruby.herokuapp.com/](https://visualize-ruby.herokuapp.com/)

------
zozbot234
I like Graphviz, but it's sad that we get such a tiny selection of graph-
drawing algorithms to go with it. For instance, I don't see a way to draw a
force-directed layout that also tries to account for edge direction, like a
more flexible version of _dot_.

------
braythwayt
I ended up with a different tool, but I was uncomfortable using drawing apps
for diagrams, and only rarely included them in my blog until I could use text
to define them.

I’m all-in on Markdown + Github for writing, so working with text-driven
diagrams is a natural fit.

~~~
prepend
What tool did you use? I’ve been using mermaid and its markdown plug-ins and
like it quite a bit, but am always looking for new ways.

~~~
braythwayt
I am also using mermaid. Like Markdown, it has a ton of shortcomings. But just
like Markdown, the big win is that it forces me to keep things simple.

Markdown forces me to focus on just the words, not the layout and fancy
formatting. Mermaid does the same thing for diagrams: Anything I can draw with
a pencil but can't express in Mermaid must be simplified or broken into
separate sub-diagrams.

This would be terrible if I was trying to draw a diagram of the entire
infrastructure of a modern SaaS company, but is actually good when I am trying
to write a post explaining ideas: Multiple simple diagrams interspersed with
text get the job done.

------
ngneer
I have used Graphviz successfully to communicate with other software engineers
about non-trivial state machines in the program. Specifically, C# Stateless
allows exporting DOT files. Does anyone know if graphing nested nodes has
already been solved?

~~~
steveroush
I wouldn't quite call it nesting, but you can draw nodes on top of other nodes
and to a large degree edges still work. But it requires explicit positioning
of the "upper" nodes.

------
jgalt212
While the stylings on graphviz are somewhat limited, as others have indicated,
I have yet to find a modern js based in browser library makes the layouts as
aesthetically balanced right out of the box as much as graphiz/dot does.

------
jimmySixDOF
RIP NetViz (90s - 2015) Back then it was one of the first to link with a db of
nodes to auto update diagrams the job I'm thinking of had thousands of sites &
it saved so much work once you had templates set up.

------
FarhadG
Been super interested to write my own layout engine. Does anyone have
resources, tutorials, etc. that I should look into if someone wants to write
the layout engine that powers something like GraphViz?

~~~
suyjuris
I was looking into that a while ago, but sadly I did not find anything great.
Back then I wanted to draw animated Binary Decision Diagrams, so I had to come
with an incremental (and simple and fast) layout algorithm, which could
determine positions for new nodes without interfering with the original graph.
The result works fine, but it did require a fair amount of tweaking. (The
comments document these tweaks extensively [1].)

If you want to write something more general, then that would probably be much
more complicated.

[1]
[https://github.com/suyjuris/obst/blob/feb8e766ce226ca1afe862...](https://github.com/suyjuris/obst/blob/feb8e766ce226ca1afe862950bef67d976e2eaa4/obst.cpp#L2941)

------
machawinka
I have used it to visualize dependency trees for several thousand nodes and
show my team loops and broken deps. For this kind of situations, a picture is
better than a thousand lines of code.

------
mendeza
Great tutorial! Is there a way to extract the bounding box of nodes, and the
endpoints of lines? This would be useful to generate ML models to
automatically parse graphs!

~~~
steveroush
There are multiple ways. Several of the output file formats contain this info
as text.

------
davidgerard
I heartily recommend the Graphviz plugin for MediaWiki.

Also, [http://www.webgraphviz.com/](http://www.webgraphviz.com/)

------
cm2187
Has anyone seen a library to draw genealogy trees programatically? Every time
I look at it, it looks like an impossible problem.

~~~
op03
[https://github.com/fredatgithub/FamilyShow](https://github.com/fredatgithub/FamilyShow)

------
wmu
Really nice, well written introduction. Graphviz is a cool tool, we used this
when debugging some graph-related algorithms.

------
johnwalkr
Graphviz works great with LaTeX. It removes the pain point of moving your
workflow out of LaTeX.

------
ngcc_hk
Still remember learning to generate dot by lisp in the book learning lisp one
game at a time.

------
sevensor
I really like graphviz for visualizing the call graphs generated by the Python
profiler.

~~~
yboris
Is there code publicly available to do this?

~~~
sevensor
What you need is gprof2dot. It will chew up your pstats file and spit out a
dot file. Enjoy!

------
_ZeD_
chime in just to add that I discovered grapviz using the venerable doxygen[0]
tool and the availability of the calling graph

[0] [https://www.doxygen.nl/index.html](https://www.doxygen.nl/index.html)

------
zero37z
It would be nice, if they add theme effect like a game called Detroit become
human

------
mv4
Used Graphviz to visualize gstreamer pipelines, and it was awesome for the
task.

------
zengid
I wonder if this could be used on windows via the Windows Subsystem for Linux?

------
GnarfGnarf
Can't find a Windows binary to download.

~~~
Jwarder
Looks like you need to grab the build artifacts from their CI/CD system.

[https://ci.appveyor.com/project/ellson/graphviz-
pl238/builds...](https://ci.appveyor.com/project/ellson/graphviz-
pl238/builds/32032002/job/yih2iyesctaji7wa/artifacts)

Not something I would trust out of the blue, but that's the best I see off of
[https://graphviz.org/download/](https://graphviz.org/download/)

------
roenxi
Graphviz is almost deceptively bad. If I see a graph in a book; I expect it
was made in TikZ.

TikZ isn't fun, but at least it has the flexibility to get a great looking
image at the end of the process. The theoretical simplicity advantages of
Graphviz usually get worn down by the fact that the diagrams look bad. Use
PowerPoint, and if code is needed bite the bullet and struggle through TikZ.

------
npiit
Graphviz is for noobs. Try TikZ, aka the Gigachad of vector graphics. I spent
more time creating TikZ diagrams than actually writing my whole MSc. thesis.

~~~
enriquto
> Graphviz is for noobs. Try TikZ, aka the Gigachad of vector graphics.

Maybe you are right, in today's decaying world. But any civilized person can
see that tikz, latex and even graphviz are all ultimately hipster tools. Real
men of course use pic and troff.

~~~
npiit
Now, 28 year old me after leaving academia and learning the superpower of
TikZ, LaTeX and Beamer, I just use draw.io and google docs/slides.

~~~
enriquto
the horror, the horror

