有人知道如何以美观合理的方式绘制多路树吗? 信息:
- 100 个左右
- 每个级别都有大致相同数量的项目
- 10 级
- 每个节点有 0(叶)到 6 个 child
- 每个节点指定它自己的级别,不管他的根。
我目前正在使用 PIL,在 img.size()[0]
/number of nodes 中划分每条“线”,并使用 draw.line
绘制线来表示边缘,但它完全搞砸了
我希望你能帮助我 =],我会发布任何需要的信息。
最佳答案
因此,渲染图表是 graphviz 的特殊天才,它也恰好有几个提供 python 绑定(bind)的库。在我看来,这些绑定(bind)库中最好的是 pygraphviz . Graphviz 可能是最好的解决方案,也可能是最简单的。
您在问题中描述的特定布局是一种分层的分层方案,由 graphviz 的 dot 布局引擎毫不费力地执行。 Dot 执行渲染以确保图形以自然树配置进行布局——即,父节点位于其子节点之上;同等级别的节点(从根开始的级别)在可能的情况下与 y 轴相对应,并且尽可能保留自然对称性。
(注意:令人困惑的是,dot 指的是构成 graphviz 的多个布局引擎之一,但 dot 也是名称和文件扩展名所有 graphviz 文档的文件格式,无论它们是如何呈现的)。
正如您在我接下来的代码中看到的那样,使用 pygraphviz,选择 dot 作为图形的布局引擎很简单,尽管它实际上不是默认设置(neato是)。
这是我制作并使用 dot 渲染的快速图表——通过 pygraphviz 使用 graphviz 创建和渲染。
请注意,该图具有完美的布局——相同度数的节点沿垂直轴位于同一水平面上,子节点呈现在父节点下方,并尽可能保留自然“对称性”(例如,父节点位于及其两个子节点之上。如您所见,我的代码都没有手动控制布局 -- graphviz,即 dot,会自动处理它。
import pygraphviz as PG
A = PG.AGraph(directed=True, strict=True)
A.add_edge("7th Edition", "32V")
A.add_edge("7th Edition", "Xenix")
# etc., etc.
# save the graph in dot format
A.write('ademo.dot')
# pygraphviz renders graphs in neato by default,
# so you need to specify dot as the layout engine
A.layout(prog='dot')
# opening the dot file in a text editor shows the graph's syntax:
digraph unix {
size="7,5";
node [color=goldenrod2, style=filled];
"7th Edition" -> "32V";
"7th Edition" -> "V7M";
"7th Edition" -> "Xenix";
"7th Edition" -> "UniPlus+";
"V7M" -> "Ultrix-11";
"8th Edition" -> "9th Edition";
"1 BSD" -> "2 BSD";
"2 BSD" -> "2.8 BSD";
"2.8 BSD" -> "Ultrix-11";
"2.8 BSD" -> "2.9 BSD";
"32V" -> "3 BSD";
"3 BSD" -> "4 BSD";
"4 BSD" -> "4.1 BSD";
"4.1 BSD" -> "4.2 BSD";
"4.1 BSD" -> "2.8 BSD";
"4.1 BSD" -> "8th Edition";
"4.2 BSD" -> "4.3 BSD";
"4.2 BSD" -> "Ultrix-32";
}
关于python - 在 Python 中绘制和渲染多路树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020741/