I think I used Graphviz, a tool that converts text to graphs, from Python3 to draw a tree structure.
Graphviz is a tool that converts text into a graph using a unique format called .dot.
sample.dot
digraph {
node [shape=circle]
A [label=A]
B [label=B]
C [label=C]
A -> B
A -> C
}
The following graph can be drawn from the above sample.
This time, I think I used this Graphviz from Python3 to draw a tree structure.
First, install Graphviz using brew
$brew install graphviz
$dot -V
>>> dot - graphviz version 2.38.0 (20140413.2041)
Install graphviz with pip
graphviz is a package that wraps Graphviz so that it can be used from Python.
$pip install graphviz
As a similar package, there is pygraphviz that can be linked with networkx, but this is not compatible with Python3. .. ..
Let's write a binary tree as an example.
binary_tree.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from graphviz import Digraph
#format specifies png(Other PDF, PNG,SVG etc. can be specified)
G = Digraph(format='png')
G.attr('node', shape='circle')
N = 15 #Number of nodes
#Add node
for i in range(N):
G.node(str(i), str(i))
#Add edge
for i in range(N):
if (i - 1) // 2 >= 0:
G.edge(str((i - 1) // 2), str(i))
# print()Then it will be output in dot format
print(G)
# binary_tree.Save as png
G.render('binary_tree')
Output result
Recommended Posts