有没有办法保证 NetworkX 的分层输出?

2024-04-26

我正在尝试制作一个流程图tree结构。我已经能够使用 networkx 创建代表性图表,但我需要一种方法来显示tree当我输出绘图时的结构。我正在使用 matplotlib.pylab 来绘制图表。

我需要以类似于所示的结构显示数据here https://graphviz.gitlab.io/_pages/Gallery/directed/Genetic_Programming.html。虽然我没有子图。

我如何保证这样的结构?

给不信者的例子:

我已经能够使用 pylab 和 graphviz 显示图表,但两者都没有提供我正在寻找的树结构。我已经尝试了 Networkx 提供的所有布局,但没有一个显示等级制度。我只是不确定什么选项/模式给它OR如果我需要使用重量。任何建议都会有帮助。

@j露台:

这是我用来生成上面的图的粗略轮廓。我添加了一些标签,但除此之外都是一样的。

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')

UPDATED

这是 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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法保证 NetworkX 的分层输出? 的相关文章

随机推荐