作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试制作树结构的流程图。我已经能够使用 networkx 创建具有代表性的图表,但是我需要一种方法来在输出绘图时显示 tree 结构。我正在使用 matplotlib.pylab 来绘制图表。
我需要以类似于 here 的结构显示数据.虽然我没有子图。
我怎样才能保证这样的结构?
不信者的例子:
我已经能够使用 pylab 和 graphviz 显示图表,但它们都没有提供我正在寻找的树结构。我已经尝试了 networkx 提供的所有布局,但没有一个显示出层次结构。我只是不确定如果我需要使用权重,应该给它或什么选项/模式。任何建议都会有所帮助。
@jterrace:
这是我用来制作上述图的粗略轮廓。我添加了一些标签,但除此之外都是一样的。
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_node("ROOT")
for i in xrange(5):
G.add_node("Child_%i" % i)
G.add_node("Grandchild_%i" % i)
G.add_node("Greatgrandchild_%i" % i)
G.add_edge("ROOT", "Child_%i" % i)
G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)
plt.title("draw_networkx")
nx.draw_networkx(G)
plt.show()
最佳答案
如果您使用有向图,那么 Graphviz 点布局将对树执行您想要的操作。这是一些类似于上述解决方案的代码,显示了如何做到这一点
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("ROOT")
for i in range(5):
G.add_node("Child_%i" % i)
G.add_node("Grandchild_%i" % i)
G.add_node("Greatgrandchild_%i" % i)
G.add_edge("ROOT", "Child_%i" % i)
G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)
# write dot file to use with graphviz
# run "dot -Tpng test.dot >test.png"
nx.nx_agraph.write_dot(G,'test.dot')
# same layout using matplotlib with no labels
plt.title('draw_networkx')
pos=graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=False, arrows=False)
plt.savefig('nx_test.png')
更新
这是为 networkx-2.0 更新的版本(以及即将推出的 networkx-2.1 也会绘制箭头)。
import networkx as nx
from networkx.drawing.nx_agraph import write_dot, graphviz_layout
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("ROOT")
for i in range(5):
G.add_node("Child_%i" % i)
G.add_node("Grandchild_%i" % i)
G.add_node("Greatgrandchild_%i" % i)
G.add_edge("ROOT", "Child_%i" % i)
G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)
# write dot file to use with graphviz
# run "dot -Tpng test.dot >test.png"
write_dot(G,'test.dot')
# same layout using matplotlib with no labels
plt.title('draw_networkx')
pos =graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=False, arrows=True)
plt.savefig('nx_test.png')
关于python - 有没有办法保证 NetworkX 的分层输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479624/
我是一名优秀的程序员,十分优秀!