pydotplus
PyDotPlus is a Python interface to Graphviz's Dot language, acting as an improved version of the original `pydot` project. It allows users to programmatically create, read, and manipulate graphs defined in the DOT language and render them into various image formats using Graphviz. The current version is 2.0.2, with its last release in December 2014, indicating a maintenance rather than active development cadence.
Warnings
- breaking Graphviz must be installed separately and its executables must be in your system's PATH environment variable. Failure to do so will result in `pydotplus.graphviz.InvocationException: GraphViz's executables not found` when attempting to render graphs.
- gotcha When running on Windows, if the Graphviz installation path contains spaces (e.g., `C:\Program Files (x86)\Graphviz...`), you might encounter `InvocationException: 'C:\Program' is not recognized as an internal or external command`. This is due to how subprocesses handle unquoted paths.
- gotcha Confusion between `pydot` and `pydotplus` is common. `pydotplus` was created as an actively maintained fork to address issues in `pydot`, particularly Python 3 compatibility and `pyparsing` version support, during a period when `pydot` development was stalled.
Install
-
pip install pydotplus
Imports
- Dot
from pydotplus import Dot
import pydotplus graph = pydotplus.Dot()
- graph_from_dot_data
import pydotplus graph = pydotplus.graph_from_dot_data(dot_string)
Quickstart
import pydotplus
import os
# Create a directed graph
graph = pydotplus.Dot(graph_type='digraph')
# Add nodes
node_a = pydotplus.Node("A", style="filled", fillcolor="red")
node_b = pydotplus.Node("B", style="filled", fillcolor="green")
node_c = pydotplus.Node("C", style="filled", fillcolor="blue")
graph.add_node(node_a)
graph.add_node(node_b)
graph.add_node(node_c)
# Add edges
edge_ab = pydotplus.Edge("A", "B", label="connects")
edge_bc = pydotplus.Edge("B", "C", arrowhead="open")
graph.add_edge(edge_ab)
graph.add_edge(edge_bc)
# Try to save the graph to a file
try:
# This requires Graphviz to be installed and its executables in the system PATH
output_file = "simple_graph.png"
graph.write_png(output_file)
print(f"Graph '{output_file}' created successfully.")
except pydotplus.graphviz.InvocationException as e:
print(f"Error: Graphviz executables not found or not in PATH. {e}")
print("Please install Graphviz (https://graphviz.org/download/) and add its 'bin' directory to your system's PATH environment variable.")
print("For example, on Windows: ';C:\Program Files (x86)\Graphviz2.38\bin' should be added to PATH.")
print("On Linux/macOS, ensure Graphviz is installed via package manager and 'dot' command is accessible.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example of loading from DOT data
dot_data = "digraph { A -> B; B -> C; }"
loaded_graph = pydotplus.graph_from_dot_data(dot_data)
# loaded_graph.write_svg("loaded_graph.svg") # Uncomment to save