13
10

More than 3 years have passed since last update.

Anaconda環境でGraphvizを使う

Last updated at Posted at 2020-05-31

概要

GraphvizをAnaconda環境下で使用する分には、condaプロンプトでインストールするだけで良さそうだったので、手順をまとめました。

※その他の環境で使用したい場合は、以下を参照してください。
【Windows10】Graphvizのインストール

パッケージのインストール

conda install python-graphviz

環境変数をセットする

binまでのパスを環境変数にセットします。

...\Anaconda3\pkgs\graphviz-2.38-hfd603c8_2\Library\bin

※環境変数の追加の仕方がわからない場合は、こちらを参照してください。

注:[OK]を押して環境変数の画面をちゃんと閉じること。パスが通らず1時間くらい悩んだ:confounded:

確認

DOTコマンドが使えるか確認する

コマンドプロンプトで、以下を実行します。

dot -V

// 以下が出力されればOK
dot - graphviz version 2.38.0 (20140413.2041)

DOT言語を使って確認する

メモ帳などでdotファイルを作成します。

sample.dot
digraph g{
1 [label="x0", color=orange, style=filled]
2 [label="x1", color=orange, style=filled]
3 [label="Add", color=lightblue, style=filled, shape=box]
4 [label="y", color=orange, style=filled]
1 -> 3 [label="2"]
2 -> 3 [label="3"]
3 -> 4 [label="5"]
}

コマンドプロンプトで以下を実行します。

dot sample.dot -T png -o sample.png

sample.dot:ソースとなるdotファイル
-T png:レンダリングする拡張子の指定(pdfやsvgなどにもできる)
-o sample.png:出力ファイル
aaa.png
sample.png

Pythonスクリプトで確認する

test\test.py
from graphviz import Digraph

G = Digraph(format="png")
G.attr("node", shape="square", style="filled")
G.edge("start","state1",label="0.8")
G.edge("start","state2",label="0.2")
G.edge("state1","state1",label="0.5")
G.edge("state2","state2", label="0.8")
G.edge("state1","state2",label="0.5")
G.edge("state2","end",label="0.2")
G.edge("end","count",label="1.0")
G.edge("count","start",label="1.0")
G.node("start", shape="circle", color="pink")
G.render("graphs") #png/直下

graphs.png
graphs.png

正しく環境変数が設定されていないと、renderをするときに以下のエラーがでます。

graphviz.backend.ExecutableNotFound: failed to execute ['dot.bat', '-Tpng', '-O', 'graphs'], make sure the Graphviz executables are on your systems' PATH
13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10