树的可视化
networkx虽然提供了基于树的接口,但是对于树这种特殊结构没有良好的构建、显示功能,一切还是基于图来处理的,比如一个简单的二叉树会画成这样:
# -*- encoding: utf-8 -*- from matplotlib import pyplot as plt import networkx as nx T = nx.balanced_tree(2, 3) nx.draw(T, with_labels=True) plt.show()
找了下,发现一个专门针对Tree的Python库ETE2,有很多针对树的数据读写、计算的函数。但是绘图函数很丑,凑合用下吧。
# -*- encoding: utf-8 -*- from ete2 import Tree, TreeStyle T = Tree('((A,B),(C),(D,(E,F)));') style = TreeStyle() style.mode = 'c' style.show_scale = False style.arc_start = -180 # 0 degrees = 3 o'clock style.arc_span = 180 T.render('tree2.png', w=300, h=300, units='px', tree_style=style) T.show(tree_style=style)