Skip to content

Drawing graphs in OCaml: Graphviz and ocamlgraph ​

Two libraries arrive in Basthon's OCaml kernel to work on graphs.

graphviz draws a graph described in the DOT language of Graphviz, directly in the notebook:

ocaml
#require "graphviz";;
module Gv = Basthon.Graphviz;;

Gv.display "digraph { a -> b; b -> c; c -> a }";;
Gv.display ~engine:"circo" "graph { 1 -- 2 -- 3 -- 4 -- 1 }";;

So writing a function that produces the DOT text of a structure is enough to draw a graph given by adjacency lists, a binary search tree or an automaton.

ocamlgraph is OCaml's reference graph library: many graph structures and the classic algorithms (traversals, Dijkstra, connected components, topological sort, spanning trees, flows…). It produces DOT too, which Gv.display draws:

ocaml
#require "ocamlgraph";;
module G = Graph.Pack.Digraph;;

let g = G.Classic.full 4;;
G.dot_output g "g.dot";;
Gv.display_file "g.dot";;

The example notebook shows ocamlgraph's two styles (the ready-to-use Pack module, and functors), with for instance the shortest path in red.

Play with it!

The shortest path found by Dijkstra, drawn by Graphviz