This package facilitates the creation of graph descriptions in the DOT language of the Graphviz graph drawing software from Python.
Create a graph object, assemble the graph by adding nodes and edges, and retrieve its DOT source code string. Save the source code to a file and render it with the Graphviz installation of your system.
Use the view
option/method to directly inspect the resulting (PDF, PNG,
SVG, etc.) file with its default application.
This package runs under Python 2.7 and 3.3+, use pip to install:
$ pip install graphviz
To render the generated DOT source code, you also need to install Graphviz (download page).
Make sure that the dot
executable is on your systems' path.
Create a graph object:
>>> from graphviz import Digraph
>>> dot = Digraph(comment='The Round Table')
>>> dot #doctest: +ELLIPSIS
<graphviz.dot.Digraph object at 0x...>
Add nodes and edges:
>>> 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')
Check the generated source code:
>>> print(dot.source) # doctest: +NORMALIZE_WHITESPACE
// The Round Table
digraph {
A [label="King Arthur"]
B [label="Sir Bedevere the Wise"]
L [label="Sir Lancelot the Brave"]
A -> B
A -> L
B -> L [constraint=false]
}
Save and render the source code, optionally view the result:
>>> dot.render('test-output/round-table.gv', view=True)
'test-output/round-table.gv.pdf'
To use a different output file format than the default PDF, set the
format
argument when creating your Graph
or Digraph
object:
>>> from graphviz import Graph
>>> g = Graph(format='png')
You can also change the format
attribute on an existing graph object:
>>> dot.format = 'svg'
>>> dot.render()
'test-output/round-table.gv.svg'
Use the graph_attr
, node_attr
, and edge_attr
arguments to change
the default appearance of your graph, nodes, and edges.
>>> dot = Digraph(name='pet-shop', node_attr={'shape': 'plaintext'})
>>> dot.node('parrot')
>>> dot.node('dead')
>>> dot.edge('parrot', 'dead')
After creation, they can be edited on the graph object:
>>> dot.graph_attr['rankdir'] = 'LR'
>>> dot.edge_attr.update(arrowhead='vee', arrowsize='2')
>>> print(dot.source) # doctest: +NORMALIZE_WHITESPACE
digraph "pet-shop" {
graph [rankdir=LR]
node [shape=plaintext]
edge [arrowhead=vee arrowsize=2]
parrot
dead
parrot -> dead
}
To use a different layout command than the default dot
when rendering your
graph, set the engine
argument on graph creation.
>>> g = Graph(engine='neato')
You can also change the engine
attribute of an existing instance:
>>> dot.engine = 'circo'
- pygraphviz – full-blown interface wrapping the Graphviz C library with SWIG
- graphviz-python – official Python bindings (documentation)
- pydot – stable pure-Python approach, requires pyparsing
This package is distributed under the MIT license.