Python中的树图绘制
我想用Python来画树,比如决策树、组织结构图等等。有哪个库可以帮我做到这些吗?
6 个回答
47
对于基本的可视化,我建议可以使用treelib。
这个工具非常简单易用:
from treelib import Node, Tree
tree = Tree()
tree.create_node("Harry", "harry") # No parent means its the root node
tree.create_node("Jane", "jane" , parent="harry")
tree.create_node("Bill", "bill" , parent="harry")
tree.create_node("Diane", "diane" , parent="jane")
tree.create_node("Mary", "mary" , parent="diane")
tree.create_node("Mark", "mark" , parent="jane")
tree.show()
输出结果:
Harry
├── Bill
└── Jane
├── Diane
│ └── Mary
└── Mark
40
有一个工具叫做 graphviz,网址是 http://www.graphviz.org/。它使用一种叫做“DOT”的语言来绘制图形。你可以自己生成 DOT 代码,或者使用 pydot,网址是 https://github.com/pydot/pydot。另外,你还可以使用 networkx,网址是 http://networkx.lanl.gov/tutorial/tutorial.html#drawing-graphs,这个工具可以方便地将图形绘制到 graphviz 或 matplotlib 上。
结合使用 networkx、matplotlib 和 graphviz,你可以获得最大的灵活性和功能,但这需要安装很多东西。
如果你想要一个快速的解决方案,可以试试:
先安装 Graphviz。
open('hello.dot','w').write("digraph G {Hello->World}")
import subprocess
subprocess.call(["path/to/dot.exe","-Tpng","hello.dot","-o","graph1.png"])
# I think this is right - try it form the command line to debug
然后安装 pydot,因为 pydot 已经为你做了这些工作。接着,你可以用 networkx 来“操控” pydot。