Skip to content

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 graphviz or conda install -c conda-forge graphviz.

Resources:

Create a simple example to create a graphviz dot file and draw a graph.

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
Output
strict graph "" {
1 -- 2;
1 -- 3;
2 -- 3;
}
Figure drawn by code cell 1

Create a graph from a dot object

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
Figure drawn by code cell 2

ganymede is made by Eugo