【Python】Python + DOT言語で図作成するには

■ はじめに

以前のTerraformの記事で

https://dk521123.hatenablog.com/entry/2019/12/09/222057

~~~
terraform graphで、Terraformの依存関係をグラフ化することが可能

terraform graph | dot -Tsvg > graph.svg
~~~
って、Terraformの依存関係をグラフ化した際に、
「dot」や「GraphViz」ってのがでてきたが、あまり深堀りしなかった。

が、業務で、この辺がでてきたので、メモする。
ついでに、Pythonで作れるようにする。

目次

【1】前提知識
 1)DOT言語
 2)GraphViz
【2】環境設定
 1)補足
【3】サンプル
 例1:オブジェクトから図生成
 例2:From JSON string
 例3:DOTファイルから生成

【1】前提知識

1)DOT言語

* グラフをデータ構造として、テキストで表現するための言語
 => 詳細は、以下の関連記事を参照のこと

https://dk521123.hatenablog.com/entry/2023/06/15/004815

例:DOT言語

graph G{
    graph[label=HelloWorld]
    a -- b -- c
}

2)GraphViz

* DOT言語で記述されたグラフ構造を描画してくれるオープンソース

【2】環境設定

pip install graphviz

$ python -V
Python 3.10.4

$ pip show graphviz     
Name: graphviz
Version: 0.20.1
Summary: Simple Python interface for Graphviz
Home-page: https://github.com/xflr6/graphviz
・・・

1)補足

* Pythonのバージョンや環境によっては、新しいものがインストールされず
 実行エラーとかできる可能性があるので、
 pyenv などで奇麗な環境で作った方がいいかも。

仮想環境 ~ pyenv ~
https://dk521123.hatenablog.com/entry/2022/02/13/000000

【3】サンプル

例1:オブジェクトから図生成

from graphviz import Digraph

# Create graphviz object
dot = Digraph(format='png')
dot.attr('graph', rankdir="LR")
# Setting font
dot.attr('node', fontname="MS Gothic")
# Create nodes
dot.node("table1")
dot.node('table2')
dot.node("table3")
dot.node("table4")
# Create edges
dot.edge("table1", "table2")
dot.edge("table2", "table3")
dot.edge("table2", "table4")
dot.render("hello-world-dot")

print("See hello-world-dot.png...")

例2:From JSON string

import graphviz

sample = """
digraph {
  rankdir="LR"
  a -> b -> c;
}
"""
graph = graphviz.Source(sample, format="png")
graph.render(filename="hello-world-dot2", cleanup=True)

print("See hello-world-dot2.png...")

例3:DOTファイルから生成

import graphviz

# For DOT to PNG image
graph = graphviz.Source.from_file('sample.dot', format='png')
graph.render(filename="output1", cleanup=True)

print("Done...")

sample.dot

graph {
  a -- b -- c;
}

参考文献

http://kyle-in-jp.blogspot.com/2018/12/pythongraphviz_14.html

関連記事

Python で d3-graphviz を使ってアニメーション表示ツールを作る
https://dk521123.hatenablog.com/entry/2023/06/24/000000
Terraform ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2019/12/09/222057
Python ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/08/07/231242
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / 集合 Set ~
https://dk521123.hatenablog.com/entry/2021/04/02/000000
Python ~ 基本編 / ラムダ lambda ~
https://dk521123.hatenablog.com/entry/2019/09/23/000000
Python再帰関数 ~
https://dk521123.hatenablog.com/entry/2023/06/11/000000
仮想環境 ~ pyenv ~
https://dk521123.hatenablog.com/entry/2022/02/13/000000
DOT言語 ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2023/06/15/004815
DOT言語 ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/06/16/000531
sqlparser-rs ~ SQL Parser for Rust ~
https://dk521123.hatenablog.com/entry/2023/06/12/000000
Python ~ PDF ~
https://dk521123.hatenablog.com/entry/2023/07/19/001703