Python interface to Graphviz's Dot language for creating, reading, editing, and visualizing graphs
npx @tessl/cli install tessl/pypi-pydot@4.0.0A comprehensive Python interface to Graphviz's DOT language for creating, reading, editing, and visualizing graphs. pydot provides an intuitive Python API that enables developers to programmatically create complex graph visualizations with minimal code.
pip install pydotimport pydotCommon patterns for working with graphs:
from pydot import Dot, Node, Edge, Subgraph, Cluster
from pydot import graph_from_dot_file, graph_from_dot_dataimport pydot
# Create a new graph
graph = pydot.Dot("my_graph", graph_type="digraph")
# Add nodes
node_a = pydot.Node("A", label="Node A", shape="box")
node_b = pydot.Node("B", label="Node B", shape="circle")
graph.add_node(node_a)
graph.add_node(node_b)
# Add edge
edge = pydot.Edge("A", "B", color="blue", label="edge")
graph.add_edge(edge)
# Set graph attributes
graph.set_bgcolor("lightgray")
graph.set_rankdir("LR")
# Generate output
graph.write_png("output.png")
# Or get as DOT string
dot_string = graph.to_string()
print(dot_string)pydot uses an object-oriented hierarchy that mirrors Graphviz's DOT language structure:
All objects support dynamic attribute management through generated getter/setter methods that correspond to Graphviz's native attributes, ensuring full compatibility with Graphviz's extensive feature set.
Core graph objects (Dot, Node, Edge) and basic graph construction operations. These classes form the foundation for building and manipulating graph structures.
class Dot:
def __init__(self, graph_name='G', obj_dict=None, graph_type='digraph',
strict=False, suppress_disconnected=False, simplify=False, **attrs): ...
def add_node(self, node): ...
def add_edge(self, edge): ...
def get_node(self, name): ...
def get_edge(self, src, dst): ...
class Node:
def __init__(self, name='', obj_dict=None, **attrs): ...
class Edge:
def __init__(self, src='', dst='', obj_dict=None, **attrs): ...Functions for reading DOT files and strings, plus methods for generating output in various formats including PNG, SVG, PDF, and DOT.
def graph_from_dot_file(path, encoding=None):
"""Load graphs from DOT file."""
def graph_from_dot_data(s):
"""Create graphs from DOT description string."""
# Dot class format methods (examples)
def write_png(self, path, prog=None, encoding=None): ...
def create_svg(self, prog=None, encoding=None): ...
def write_pdf(self, path, prog=None, encoding=None): ...Utility functions for creating graphs from various data structures including edge lists, adjacency matrices, and incidence matrices.
def graph_from_edges(edge_list, node_prefix='', directed=False):
"""Creates graph from edge list."""
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
"""Creates graph from adjacency matrix."""
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False):
"""Creates graph from incidence matrix."""Advanced graph structuring with subgraphs and clusters for complex layouts and visual organization.
class Subgraph:
def __init__(self, graph_name='', obj_dict=None, suppress_disconnected=False,
simplify=False, **attrs): ...
class Cluster:
def __init__(self, graph_name='subG', obj_dict=None, suppress_disconnected=False,
simplify=False, **attrs): ...Helper functions for string processing, platform detection, and GraphViz integration.
def make_quoted(s):
"""Transform string into quoted string, escaping specials."""
def any_needs_quotes(s):
"""Determine if string needs to be quoted."""
def id_needs_quotes(s):
"""Check if string needs quotes as DOT language ID."""
def quote_id_if_necessary(s, unquoted_keywords=None):
"""Enclose identifier in quotes if needed."""
def quote_attr_if_necessary(s):
"""Enclose attribute value in quotes if needed."""
def is_windows():
"""Check if running on Windows."""
def is_anaconda():
"""Check if running under Anaconda."""
def get_executable_extension():
"""Get appropriate executable extension for platform."""
def call_graphviz(program, arguments, working_dir, **kwargs):
"""Call GraphViz programs directly."""# Valid attribute sets for different graph elements
GRAPH_ATTRIBUTES = {
"Damping", "K", "URL", "aspect", "bb", "bgcolor", "center",
"charset", "clusterrank", "colorscheme", "comment", "compound",
# ... 73 total attributes
}
NODE_ATTRIBUTES = {
"URL", "color", "colorscheme", "comment", "distortion",
"fillcolor", "fixedsize", "fontcolor", "fontname", "fontsize",
# ... 38 total attributes
}
EDGE_ATTRIBUTES = {
"URL", "arrowhead", "arrowsize", "arrowtail", "color",
"colorscheme", "comment", "constraint", "decorate", "dir",
# ... 61 total attributes
}
CLUSTER_ATTRIBUTES = {
"K", "URL", "bgcolor", "color", "colorscheme", "fillcolor",
# ... 22 total attributes
}
# Output formats supported by GraphViz
OUTPUT_FORMATS = {
"canon", "cmap", "cmapx", "cmapx_np", "dia", "dot", "fig",
"gd", "gd2", "gif", "hpgl", "imap", "imap_np", "ismap",
"jpe", "jpeg", "jpg", "mif", "mp", "pcl", "pdf", "pic",
"plain", "plain-ext", "png", "ps", "ps2", "svg", "svgz",
"vml", "vmlz", "vrml", "vtx", "wbmp", "xdot", "xlib"
}
# Default GraphViz programs
DEFAULT_PROGRAMS = {"dot", "twopi", "neato", "circo", "fdp", "sfdp"}class PydotException(Exception):
"""Base class for exceptions in pydot."""
class Error(PydotException):
"""General error handling class."""
def __init__(self, value): ...Common exceptions include parsing errors when reading malformed DOT files and execution errors when Graphviz programs are not found or fail.
class FrozenDict(dict):
"""Frozen dictionary, values are immutable after creation."""
def __init__(self, *args, **kwargs): ...
# Deprecated - use FrozenDict instead
class frozendict(FrozenDict):
"""Deprecated alias for FrozenDict."""
# Type aliases
AttributeDict = Dict[str, Any]
EdgeEndpoint = Union[str, int, float, FrozenDict]