Graphviz Python Interface
The `graphviz` library provides a simple pure-Python interface for generating and rendering graph descriptions in the DOT language, which is used by the Graphviz graph-drawing software. It allows users to programmatically create directed and undirected graphs, add nodes and edges, apply attributes for styling, and then render them into various output formats (e.g., PDF, PNG, SVG). The current version is 0.21, and the project maintains an active release cadence with regular updates and Python version support.
Warnings
- breaking The `graphviz` Python package is a wrapper for the external Graphviz command-line tools. It is crucial to install the Graphviz software separately on your operating system and ensure its executables (e.g., `dot`, `neato`) are accessible in your system's PATH environment variable. Failure to do so will result in `graphviz.exceptions.ExecutableNotFound` errors.
- breaking Python 3.8 support was dropped in `graphviz` version 0.21. Previous versions (e.g., 0.20.2) dropped Python 3.7 support. Ensure your Python environment meets the minimum version requirement (currently Python 3.9+ for v0.21).
- gotcha Handling backslash escapes and special characters (like quotes) within DOT language strings, especially for `label` attributes, can be tricky. Prior to version 0.14, using `\"` for a literal quote could break the internal quoting mechanism. Raw string literals (`r'...'`) are often recommended to simplify backslash handling.
- gotcha Default graph layouts can sometimes result in overlapping nodes or edges, or an undesirable ordering. This is often due to the graph layout algorithms trying to optimize for compactness or other factors without specific user guidance.
Install
-
pip install graphviz -
sudo apt install graphviz -
sudo dnf install graphviz -
brew install graphviz -
choco install graphviz
Imports
- Graph
from graphviz import Graph
- Digraph
from graphviz import Digraph
- graphviz
import graphviz
Quickstart
import graphviz
dot = graphviz.Digraph('MyGraph', comment='A Simple Directed Graph')
# Add nodes
dot.node('A', 'Node A')
dot.node('B', 'Node B')
dot.node('C', 'Node C')
# Add edges
dot.edge('A', 'B', label='connects')
dot.edge('B', 'C', label='leads to')
dot.edge('C', 'A', label='cycles back')
# Render and view the graph
dot.render('my_simple_graph', view=True, format='png')