pydotplus

2.0.2 · maintenance · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple directed graph with nodes and edges using `pydotplus` and then attempts to render it to a PNG image. It also includes an example of loading a graph from a DOT string. **Crucially, for the rendering step to succeed, Graphviz must be installed on your system and its `bin` directory must be added to your system's PATH environment variable.**

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

view raw JSON →