Creating Graphs From Terminal

Aug. 11, 2022 [guides] [technology] [libre]

In the post about Visualizing Dependencies I shared a graphic relating some APIs. In the past, I would have painstakingly used something like GIMP or LibreOffice Draw to produce that. But recently I discovered graphviz, a brilliant command line tool to whip up complex relational graphs programatically. The more items you have to plot, the more sense it makes to use such a tool.

Let’s say you want to graph out a small social network. Create a graphviz file (.gv) and populate it as:

graph {
    Alice - {Bob,Carlos,Dan,Eve,Frank,Grace}
    Bob - {Alice,Carlos,Dan,Eve}
    Carlos - {Victor,Wendy,Walter}

Then pass the graphviz file to a plotter like dot:

dot -Tpng social_network.gv -o graph.png

An image file will be created in which the relationships will automatically get drawn in the most optimal pattern according to dot. There are other layouts as well. circo for circular layouts, patchwork for squarified layouts, and so on.

Also helpful is the directional graph functionality to indicate flow which can be declared like:

digraph {
    Dog -> Cat
    Cat -> Mouse

And if you want to export that as a scalable vector graphic it can be done with the -Tsvg switch:

twopi -Tsvg animals.gv -o graph.svg

I wish I had known about graphviz sooner, and I definitely wish I had known about it while going through school or when I had family trying to map out genealogy. It can also be used for flowcharts, block diagrams, lineages and is highly customizable. Just have a look at the man pages or the always fantastic Arch wiki. Whatever the appilcation, it is another good non-networked tool that can be used wherever you have access to a *nix shell.