Graphviz flowchart in Python¶
Date: 2024-04-27
Graphviz is a great tool to make graphs and charts. I use it occasionally but not so often that I remember exactly how to make a graph when I need it. Below are flowcharts created using this python interface for graphviz. There are also multiple examples on their website.
A flowchart¶
This flowchart documents an annoying problem and the reason I want to write blog posts about some of the things I do. The graph is created with the color #123456
but then I replace that color with var(--main-foreground)
so the browser will display the SVG in a suitable color in both dark and light mode. This is possible because the SVG is included directly in the HTML and can use the CSS of the website. It doesn’t work when sourcing an SVG image file.
[1]:
import graphviz
from textwrap import fill
from string import ascii_uppercase
from IPython.display import HTML
wrap_length = 16
fake_color = "#123456"
d = graphviz.Digraph(
format='svg',
graph_attr={"bgcolor":"transparent"},
node_attr={"shape": "box",
"width":"2", "height":"1.2",
"fixedsize":"true",
"color":fake_color,
"fontcolor":fake_color,
"fontname":"inherit"},
edge_attr={"arrowhead":"vee",
"fillcolor":fake_color,
"color":fake_color})
labels = [
"Discover some interesting new topic",
"Spend time to learn new things related to the topic",
"Get busy with other things",
"Think of a project where topic would be useful",
"Realise I don't remember how to apply topic",
"Remember how much time it took to learn topic",
"Decide not to proceed with project",
"Apply previously gained knowledge on topic",
"Quickly complete project",
"Profit!"]
for char, label in zip(ascii_uppercase, labels):
d.node(char, fill(label, wrap_length))
d.edges(["AB", "BC", "CD", "DE", "EF", "FG", "HI", "IJ"])
d.edge("D", "H", style="dotted")
svg = d.pipe(encoding='utf-8')
svg = svg.replace(fake_color, "var(--main-foreground)")
HTML(svg)
[1]:
Another flowchart¶
This SVG will not change color when switching between dark and light mode in the browser.
[2]:
d = graphviz.Digraph(
format='svg',
graph_attr={"bgcolor":"white"},
node_attr={"shape": "circle"}
)
d.edges(["42", "46", "21", "23", "65", "67"])
d
[2]: