Skip to content

11.2 Draw a graph with Graphviz

You write a graph in the DOT language of Graphviz, with labels from your own data.

You want a picture of a graph. Graphviz is a program that lays out graphs by itself and draws them as SVG, PNG or PDF. It reads a small text language called DOT and handles graphs larger than Mermaid does. You need this for:

  • a picture of a graph for a document or a review;
  • a look at the result of an analysis, to understand it;
  • a graph too large for a Mermaid flowchart.

The example graph dependencies models the dependencies between the eight packages of a small program. It has an edge from each package to each package it uses. The array names holds the names of the packages. The graph should be drawn from left to right, with the names of the packages on the nodes.

DotWriter writer = DotWriter.of(dependencies)
.graphAttribute("rankdir", "LR")
.nodeLabel(node -> names[node]);
StringWriter out = new StringWriter(); // or a file, through a Writer
writer.write(out);
String dot = out.toString();
// digraph {
// rankdir="LR";
// 0 [label="app"];
// ...
// 0 -> 1;
// ...
// }
Full example
let writer = DotWriter::of(&dependencies)
.graph_attribute("rankdir", "LR")
.node_label(|node| Some(names[node as usize].into()));
let mut out = Vec::new(); // or a BufWriter on a File, through any io::Write
writer.write(&mut out)?;
let dot = String::from_utf8(out)?;
// digraph {
// rankdir="LR";
// 0 [label="app"];
// ...
// 0 -> 1;
// ...
// }
Full example
const writer = DotWriter.of(dependencies)
.graphAttribute("rankdir", "LR")
.nodeLabel((node) => names[node]);
const chunks: string[] = [];
// or a file, through a WriteStream
const out = { write: (text: string) => chunks.push(text) };
writer.write(out);
const dot = chunks.join("");
// digraph {
// rankdir="LR";
// 0 [label="app"];
// ...
// 0 -> 1;
// ...
// }
Full example
DotWriter writer = DotWriter.Of(dependencies)
.GraphAttribute("rankdir", "LR")
.NodeLabel(node => names[node]);
using var output = new StringWriter(); // or a file, through a StreamWriter
writer.Write(output);
string dot = output.ToString();
// digraph {
// rankdir="LR";
// 0 [label="app"];
// ...
// 0 -> 1;
// ...
// }
Full example

The writer writes the graph attributes, then every node with its label, then every edge. Nodes and edges follow the order of the node IDs and edge indices, so that the same graph always gives the same text. The result is this text:

digraph {
rankdir="LR";
0 [label="app"];
1 [label="cli"];
2 [label="ui"];
3 [label="service"];
4 [label="model"];
5 [label="storage"];
6 [label="json"];
7 [label="util"];
0 -> 1;
0 -> 2;
0 -> 3;
1 -> 7;
2 -> 3;
2 -> 4;
2 -> 7;
3 -> 4;
3 -> 5;
4 -> 5;
5 -> 4;
5 -> 6;
5 -> 7;
6 -> 7;
}

The command dot -Tsvg packages.dot -o packages.svg turns the text into a picture:

The dependencies between the packages, drawn by Graphviz from left to right