PyDot¶
Description:
- Is an interface to Graphviz and can parse and dump into the DOT language used by GraphViz.
Requirements:
pip install pydot, plus the Graphviz programs (dot) on your PATH:apt install graphviz,brew install graphvizorconda install -c conda-forge graphviz.
Resources:
- [GitHub] https://github.com/pydot/pydot
Example 1¶
Create a simple example to create a graphviz dot file and draw a graph.
In [1]:
Copied!
import pygraphviz as pgv
from pathlib import Path
import pydot
from IPython.display import Image
tmp = "/tmp/demo_notebooks"
Path(tmp).mkdir(exist_ok=True)
# Create a graph
A = pgv.AGraph()
A.add_edge(1, 2)
A.add_edge(2, 3)
A.add_edge(1, 3)
print(A.string()) # print to screen
A.write(f"{tmp}/simple.dot") # write to simple.dot
# Create a new graph
B = pgv.AGraph(f"{tmp}/simple.dot") # create a new graph from file
graphs = pydot.graph_from_dot_file(f"{tmp}/simple.dot")
graph = graphs[0]
Image(graph.create_png()) # render with Graphviz's dot program and show the PNG
import pygraphviz as pgv
from pathlib import Path
import pydot
from IPython.display import Image
tmp = "/tmp/demo_notebooks"
Path(tmp).mkdir(exist_ok=True)
# Create a graph
A = pgv.AGraph()
A.add_edge(1, 2)
A.add_edge(2, 3)
A.add_edge(1, 3)
print(A.string()) # print to screen
A.write(f"{tmp}/simple.dot") # write to simple.dot
# Create a new graph
B = pgv.AGraph(f"{tmp}/simple.dot") # create a new graph from file
graphs = pydot.graph_from_dot_file(f"{tmp}/simple.dot")
graph = graphs[0]
Image(graph.create_png()) # render with Graphviz's dot program and show the PNG
strict graph "" {
1 -- 2;
1 -- 3;
2 -- 3;
}
Out[1]:
Example 2¶
Create a graph from a dot object
In [2]:
Copied!
import pydot
from IPython.display import Image
graph = pydot.Dot("my_graph", graph_type="graph", bgcolor="yellow")
# Add nodes
my_node = pydot.Node("a", label="Foo")
graph.add_node(my_node)
# Or, without using an intermediate variable:
graph.add_node(pydot.Node("b", shape="circle"))
# Add edges
my_edge = pydot.Edge("a", "b", color="blue")
graph.add_edge(my_edge)
# Or, without using an intermediate variable:
graph.add_edge(pydot.Edge("b", "c", color="blue"))
Image(graph.create_png()) # render with Graphviz's dot program and show the PNG
import pydot
from IPython.display import Image
graph = pydot.Dot("my_graph", graph_type="graph", bgcolor="yellow")
# Add nodes
my_node = pydot.Node("a", label="Foo")
graph.add_node(my_node)
# Or, without using an intermediate variable:
graph.add_node(pydot.Node("b", shape="circle"))
# Add edges
my_edge = pydot.Edge("a", "b", color="blue")
graph.add_edge(my_edge)
# Or, without using an intermediate variable:
graph.add_edge(pydot.Edge("b", "c", color="blue"))
Image(graph.create_png()) # render with Graphviz's dot program and show the PNG
Out[2]: