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

标签 python networkx

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

我需要以类似于 here 的结构显示数据.虽然我没有子图。

我怎样才能保证这样的结构?

不信者的例子:

Various NetworkX layouts

我已经能够使用 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')

Graphviz output

NetworkX/Matplotlib output

更新

这是为 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')

enter image description here

关于python - 有没有办法保证 NetworkX 的分层输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479624/

相关文章:

python - 使用 cython : all strings are empty 包装一个 c++ DLL

python - 使用 Networkx 绘制带边的图

python - 从字典创建图形工具图形

python - 如何将 Tornado 与线程池一起使用?

python - 在Python for循环中改变 float 的值

python - 为什么 "del x"不会改变生成器的结果而 x.append 会改变?

python - 在 networkx 中标记边

python - 在 MySQL 表中生成唯一字符列表

Python:如何将 pickled txt 文件转换为用于networkx的gpickles?

python - Networkx - 找到加权网络中出现次数最多的路径