Basic usage

The graphviz package provides two main classes: graphviz.Graph and graphviz.Digraph. They create graph descriptions in the DOT language for undirected and directed graphs respectively. They have the same API.

Hint

Graph and Digraph produce different DOT syntax and have different values for directed.

Create a graph by instantiating a new Graph or Digraph object:

>>> import graphviz

>>> dot = graphviz.Digraph('round-table', comment='The Round Table')

>>> dot
<graphviz.graphs.Digraph object at 0x...>

Their constructors allow to set the graph’s name identifier, the filename for the DOT source and the rendered graph, an optional comment for the first source code line, etc.

Add nodes and edges to the graph object using its node() and edge() or edges() methods:

>>> dot.node('A', 'King Arthur')
>>> dot.node('B', 'Sir Bedevere the Wise')
>>> dot.node('L', 'Sir Lancelot the Brave')

>>> dot.edges(['AB', 'AL'])
>>> dot.edge('B', 'L', constraint='false')

The node() method takes a name identifier as first argument and an optional label. The edge() method takes the names of start node and end node, while edges() takes an iterable of name pairs. Keyword arguments are turned into (node and edge) attributes (see extensive Graphviz docs on available attributes).

Check the generated DOT source code:

>>> print(dot.source)
// The Round Table
digraph "round-table" {
    A [label="King Arthur"]
    B [label="Sir Bedevere the Wise"]
    L [label="Sir Lancelot the Brave"]
    A -> B
    A -> L
    B -> L [constraint=false]
}

Use the render() method to save the DOT source code and render it with the default dot layout engine (see below for using other layout engines).

>>> doctest_mark_exe()

>>> dot.render(directory='doctest-output').replace('\\', '/')
'doctest-output/round-table.gv.pdf'

Passing view=True will automatically open the resulting (PDF, SVG, PNG, etc.) file with your system’s default viewer application for the rendered file type.

>>> doctest_mark_exe()

>>> dot.render(directory='doctest-output', view=True)
'doctest-output/round-table.gv.pdf'
_images/round-table.svg

Attention

Backslash-escapes and strings of the form <...> have a special meaning in the DOT language and are currently passed on as is by this library. If you need to render arbitrary strings literally (e.g. from user input), consider wrapping them with the graphviz.escape() function first. See the sections on Backslash escapes and Quoting and HTML-like labels below for details.