Pydot
Pydot is a pure-Python interface to Graphviz and its DOT language, enabling users to programmatically create, read, edit, and visualize graphs. It is currently at version 4.0.1 and is actively maintained with a regular release cadence, with recent updates focusing on parser fixes and type annotations.
Warnings
- breaking Pydot relies on Graphviz for rendering graphs. If Graphviz is not installed separately on your system (beyond `pip install pydot`) and its `dot` executable is not in your system's PATH, pydot will raise an `InvocationException`.
- gotcha Using colons (:) directly in node names or edge labels without proper escaping can lead to Graphviz syntax errors when rendering, resulting in `InvocationException`.
- gotcha There is a separate, older project called `pydotplus` which was an 'improved version of the old pydot project'. The current `pydot` (v4.0.1) is actively maintained and the recommended library. Using `pydotplus` might lead to outdated functionality or compatibility issues with modern Python versions or other libraries.
Install
-
pip install pydot -
# You *must* also install Graphviz separately on your system. # For Debian/Ubuntu: sudo apt install graphviz # For macOS (with Homebrew): brew install graphviz # For Windows, download from graphviz.org/download/ and add to PATH.
Imports
- pydot
import pydot
- Dot
import pydot graph = pydot.Dot(...)
- Node
import pydot node = pydot.Node(...)
- Edge
import pydot edge = pydot.Edge(...)
Quickstart
import pydot
import os
# Ensure Graphviz dot executable is found. On some systems or environments,
# pydot might not find it automatically. This is for demonstration; usually,
# ensuring Graphviz is in PATH is enough.
# You might need to set this if Graphviz is installed in a non-standard location.
# For example, on Windows: os.environ["PATH"] += os.pathsep + 'C:/Program Files/Graphviz/bin'
graph = pydot.Dot('my_graph', graph_type='digraph')
node_a = pydot.Node('A', style='filled', fillcolor='red')
node_b = pydot.Node('B', style='filled', fillcolor='blue')
node_c = pydot.Node('C')
graph.add_node(node_a)
graph.add_node(node_b)
graph.add_node(node_c)
graph.add_edge(pydot.Edge(node_a, node_b, label='edge_ab'))
graph.add_edge(pydot.Edge(node_b, node_c, label='edge_bc', color='green'))
graph.add_edge(pydot.Edge(node_c, node_a, label='edge_ca', arrowhead='vee'))
# Save the graph to a PNG file
try:
graph.write_png('output_graph.png')
print("Graph saved to output_graph.png")
except pydot.InvocationException as e:
print(f"Error generating graph: {e}")
print("Make sure Graphviz is installed and its 'dot' executable is in your system PATH.")
except Exception as e:
print(f"An unexpected error occurred: {e}")