PyGraphviz
PyGraphviz is a Python interface to the Graphviz graph layout and visualization package. It enables users to create, edit, read, write, and draw graphs using Python by accessing Graphviz's graph data structure and layout algorithms. It offers a programming interface similar to NetworkX. The current stable version is 1.14, with minor releases typically occurring a few times a year, alongside less frequent major version updates.
Warnings
- breaking PyGraphviz 0.32 introduced significant API changes, being a rewrite not backward compatible with earlier versions (e.g., 0.2x). Programs written for older versions will not work without modification.
- gotcha The Graphviz C library (not the Python `graphviz` package) is a mandatory prerequisite and must be installed separately on your operating system *before* installing `pygraphviz`. Failure to do so typically results in `ImportError: libagraph.so.1: cannot open shared object file` or similar compilation errors during `pip install`.
- gotcha Installing PyGraphviz on Windows can be particularly challenging. It often requires specific Graphviz versions (e.g., 2.46+ for PyGraphviz 1.7+), a C/C++ compiler (like Visual C++ Build Tools), and potentially manually specifying Graphviz include and library paths during `pip install` using `--config-settings`.
- breaking PyGraphviz regularly drops support for older Python versions. For example, PyGraphviz 1.14 dropped Python 3.8 support. PyGraphviz 1.9 dropped Python 3.7, and 1.7 dropped 3.6.
- breaking Specific minimum Graphviz C library versions are required by newer PyGraphviz releases. For instance, PyGraphviz 1.7 requires Graphviz 2.46.0 or higher, and PyGraphviz 1.11 also requires Graphviz 2.46+.
Install
-
pip install pygraphviz -
sudo apt-get install graphviz graphviz-dev pip install pygraphviz -
brew install graphviz pip install pygraphviz
Imports
- AGraph
import pygraphviz.AGraph
from pygraphviz import AGraph
Quickstart
import pygraphviz as pgv
# Create a directed graph
G = pgv.AGraph(directed=True, strict=False)
# Add nodes
G.add_node('A', shape='box', color='red')
G.add_node('B', shape='circle')
G.add_node('C', label='Node C')
# Add edges
G.add_edge('A', 'B', label='connects', penwidth=2)
G.add_edge('B', 'C', color='blue', style='dashed')
G.add_edge('C', 'A')
# Set graph attributes
G.graph_attr['label'] = 'My Sample Graph'
G.graph_attr['overlap'] = 'false'
G.graph_attr['splines'] = 'true'
# Layout the graph (using dot engine by default)
# and draw to a file
G.layout(prog='dot')
output_filename = 'sample_graph.png'
G.draw(output_filename)
print(f"Graph saved to {output_filename}")
# print(G) # Uncomment to see the DOT language representation