DEV Community

Cover image for Embedding Graphs Into Your Sphinx Documents
Jürgen Hermann
Jürgen Hermann

Posted on • Originally published at jhermann.github.io on

Embedding Graphs Into Your Sphinx Documents

Embed GraphViz ‘dot language’ graphs into your documentation, and hot-link the nodes to any HTTP resource.

The sphinx.ext.graphviz extension allows you to directly embed GraphViz ‘dot language’ graphs into your document files. They are then rendered to PNG or SVG images, which get added to your generated HTML documentation. Using SVG allows you to hot-link your nodes to any HTTP resource.

Before use, you have to activate the extension with just a few changes to your docs/conf.py

extensions = [
    # …
    'sphinx.ext.graphviz',
]

# …

# -- GraphViz configuration ----------------------------------
graphviz_output_format = 'svg'

This is an example for what you can then add to your documentation:

Sphinx and GraphViz Data Flow

As long as the nodes have a href attribute, the SVG rendering contains them and thus node labels become clickable hyperlinks.

And here's the related markup that needs to be added to one of your .rst files:

.. graphviz::
    :name: sphinx.ext.graphviz
    :caption: Sphinx and GraphViz Data Flow
    :alt: How Sphinx and GraphViz Render the Final Document
    :align: center

     digraph "sphinx-ext-graphviz" {
         size="6,4";
         rankdir="LR";
         graph [fontname="Verdana", fontsize="12"];
         node [fontname="Verdana", fontsize="12"];
         edge [fontname="Sans", fontsize="9"];

         sphinx [label="Sphinx", shape="component",
                 href="https://www.sphinx-doc.org/",
                 target="_blank"];
         dot [label="GraphViz", shape="component",
              href="https://www.graphviz.org/",
              target="_blank"];
         docs [label="Docs (.rst)", shape="folder",
               fillcolor=green, style=filled];
         svg_file [label="SVG Image", shape="note", fontcolor=white,
                   fillcolor="#3333ff", style=filled];
         html_files [label="HTML Files", shape="folder",
                     fillcolor=yellow, style=filled];

         docs -> sphinx [label=" parse "];
         sphinx -> dot [label=" call ", style=dashed, arrowhead=none];
         dot -> svg_file [label=" draw "];
         sphinx -> html_files [label=" render "];
         svg_file -> html_files [style=dashed];
     }

For all this to work, you need the GraphViz suite of tools installed on the machine that renders the documentation.

Oldest comments (0)