How to build Graphviz diagrams in Python

Last modified: March 2, 2023

1. Install Graphviz

The first step is to install Graphviz on your system. You can download Graphviz from their official website or install it using your operating system's package manager.

2. Install Graphviz Python package

To interact with Graphviz in Python, you need to install the Graphviz Python package. You can install it using pip with the following command

pip install graphviz

In this example, we define two participants, A and B, and show two messages being sent between them.

3. Import the Graphviz module

Once you have installed the Graphviz Python package, you can import the graphviz module in your Python script.

import graphviz

4. Define the graph

To create a Graphviz diagram, you need to define the nodes and edges of the graph. You can define the graph using the Digraph class in the graphviz module.

dot = graphviz.Digraph()
dot.node('A', 'Node A')
dot.node('B', 'Node B')
dot.edge('A', 'B', 'Edge 1')
dot.edge('B', 'A', 'Edge 2')

In this example, we define a directed graph with two nodes (A and B) and two edges (A -> B and B -> A).

5. Render the graph

Once you have defined the graph, you can render it using the render method of the Digraph object.

dot.render('graph', view=True)

In this example, we render the graph to a file named "graph.pdf" and open it in the default PDF viewer.