0
# pydot
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: pydot
7
- **Language**: Python
8
- **Installation**: `pip install pydot`
9
- **Dependencies**: pyparsing>=3.1.0, Graphviz (external)
10
11
## Core Imports
12
13
```python
14
import pydot
15
```
16
17
Common patterns for working with graphs:
18
19
```python
20
from pydot import Dot, Node, Edge, Subgraph, Cluster
21
from pydot import graph_from_dot_file, graph_from_dot_data
22
```
23
24
## Basic Usage
25
26
```python
27
import pydot
28
29
# Create a new graph
30
graph = pydot.Dot("my_graph", graph_type="digraph")
31
32
# Add nodes
33
node_a = pydot.Node("A", label="Node A", shape="box")
34
node_b = pydot.Node("B", label="Node B", shape="circle")
35
graph.add_node(node_a)
36
graph.add_node(node_b)
37
38
# Add edge
39
edge = pydot.Edge("A", "B", color="blue", label="edge")
40
graph.add_edge(edge)
41
42
# Set graph attributes
43
graph.set_bgcolor("lightgray")
44
graph.set_rankdir("LR")
45
46
# Generate output
47
graph.write_png("output.png")
48
49
# Or get as DOT string
50
dot_string = graph.to_string()
51
print(dot_string)
52
```
53
54
## Architecture
55
56
pydot uses an object-oriented hierarchy that mirrors Graphviz's DOT language structure:
57
58
- **Graph/Dot**: Top-level container for the entire graph structure
59
- **Node**: Individual vertices with customizable attributes
60
- **Edge**: Connections between nodes with styling options
61
- **Subgraph**: Nested graph structures for organizational purposes
62
- **Cluster**: Special subgraphs with visual grouping and styling
63
64
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.
65
66
## Capabilities
67
68
### Graph Creation and Management
69
70
Core graph objects (Dot, Node, Edge) and basic graph construction operations. These classes form the foundation for building and manipulating graph structures.
71
72
```python { .api }
73
class Dot:
74
def __init__(self, graph_name='G', obj_dict=None, graph_type='digraph',
75
strict=False, suppress_disconnected=False, simplify=False, **attrs): ...
76
def add_node(self, node): ...
77
def add_edge(self, edge): ...
78
def get_node(self, name): ...
79
def get_edge(self, src, dst): ...
80
81
class Node:
82
def __init__(self, name='', obj_dict=None, **attrs): ...
83
84
class Edge:
85
def __init__(self, src='', dst='', obj_dict=None, **attrs): ...
86
```
87
88
[Graph Management](./graph-management.md)
89
90
### File I/O Operations
91
92
Functions for reading DOT files and strings, plus methods for generating output in various formats including PNG, SVG, PDF, and DOT.
93
94
```python { .api }
95
def graph_from_dot_file(path, encoding=None):
96
"""Load graphs from DOT file."""
97
98
def graph_from_dot_data(s):
99
"""Create graphs from DOT description string."""
100
101
# Dot class format methods (examples)
102
def write_png(self, path, prog=None, encoding=None): ...
103
def create_svg(self, prog=None, encoding=None): ...
104
def write_pdf(self, path, prog=None, encoding=None): ...
105
```
106
107
[File Operations](./file-operations.md)
108
109
### Graph Building Utilities
110
111
Utility functions for creating graphs from various data structures including edge lists, adjacency matrices, and incidence matrices.
112
113
```python { .api }
114
def graph_from_edges(edge_list, node_prefix='', directed=False):
115
"""Creates graph from edge list."""
116
117
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
118
"""Creates graph from adjacency matrix."""
119
120
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False):
121
"""Creates graph from incidence matrix."""
122
```
123
124
[Graph Utilities](./graph-utilities.md)
125
126
### Subgraphs and Clusters
127
128
Advanced graph structuring with subgraphs and clusters for complex layouts and visual organization.
129
130
```python { .api }
131
class Subgraph:
132
def __init__(self, graph_name='', obj_dict=None, suppress_disconnected=False,
133
simplify=False, **attrs): ...
134
135
class Cluster:
136
def __init__(self, graph_name='subG', obj_dict=None, suppress_disconnected=False,
137
simplify=False, **attrs): ...
138
```
139
140
[Subgraphs and Clusters](./subgraphs-clusters.md)
141
142
### String and Utility Functions
143
144
Helper functions for string processing, platform detection, and GraphViz integration.
145
146
```python { .api }
147
def make_quoted(s):
148
"""Transform string into quoted string, escaping specials."""
149
150
def any_needs_quotes(s):
151
"""Determine if string needs to be quoted."""
152
153
def id_needs_quotes(s):
154
"""Check if string needs quotes as DOT language ID."""
155
156
def quote_id_if_necessary(s, unquoted_keywords=None):
157
"""Enclose identifier in quotes if needed."""
158
159
def quote_attr_if_necessary(s):
160
"""Enclose attribute value in quotes if needed."""
161
162
def is_windows():
163
"""Check if running on Windows."""
164
165
def is_anaconda():
166
"""Check if running under Anaconda."""
167
168
def get_executable_extension():
169
"""Get appropriate executable extension for platform."""
170
171
def call_graphviz(program, arguments, working_dir, **kwargs):
172
"""Call GraphViz programs directly."""
173
```
174
175
## Constants and Attribute Sets
176
177
```python { .api }
178
# Valid attribute sets for different graph elements
179
GRAPH_ATTRIBUTES = {
180
"Damping", "K", "URL", "aspect", "bb", "bgcolor", "center",
181
"charset", "clusterrank", "colorscheme", "comment", "compound",
182
# ... 73 total attributes
183
}
184
185
NODE_ATTRIBUTES = {
186
"URL", "color", "colorscheme", "comment", "distortion",
187
"fillcolor", "fixedsize", "fontcolor", "fontname", "fontsize",
188
# ... 38 total attributes
189
}
190
191
EDGE_ATTRIBUTES = {
192
"URL", "arrowhead", "arrowsize", "arrowtail", "color",
193
"colorscheme", "comment", "constraint", "decorate", "dir",
194
# ... 61 total attributes
195
}
196
197
CLUSTER_ATTRIBUTES = {
198
"K", "URL", "bgcolor", "color", "colorscheme", "fillcolor",
199
# ... 22 total attributes
200
}
201
202
# Output formats supported by GraphViz
203
OUTPUT_FORMATS = {
204
"canon", "cmap", "cmapx", "cmapx_np", "dia", "dot", "fig",
205
"gd", "gd2", "gif", "hpgl", "imap", "imap_np", "ismap",
206
"jpe", "jpeg", "jpg", "mif", "mp", "pcl", "pdf", "pic",
207
"plain", "plain-ext", "png", "ps", "ps2", "svg", "svgz",
208
"vml", "vmlz", "vrml", "vtx", "wbmp", "xdot", "xlib"
209
}
210
211
# Default GraphViz programs
212
DEFAULT_PROGRAMS = {"dot", "twopi", "neato", "circo", "fdp", "sfdp"}
213
```
214
215
## Exception Handling
216
217
```python { .api }
218
class PydotException(Exception):
219
"""Base class for exceptions in pydot."""
220
221
class Error(PydotException):
222
"""General error handling class."""
223
def __init__(self, value): ...
224
```
225
226
Common exceptions include parsing errors when reading malformed DOT files and execution errors when Graphviz programs are not found or fail.
227
228
## Types
229
230
```python { .api }
231
class FrozenDict(dict):
232
"""Frozen dictionary, values are immutable after creation."""
233
def __init__(self, *args, **kwargs): ...
234
235
# Deprecated - use FrozenDict instead
236
class frozendict(FrozenDict):
237
"""Deprecated alias for FrozenDict."""
238
239
# Type aliases
240
AttributeDict = Dict[str, Any]
241
EdgeEndpoint = Union[str, int, float, FrozenDict]
242
```