使用networkX输出树结构

Using networkX to output a tree structure

我正在使用 networkX 生成如下树结构(我正在关注 answer of this question)。

import networkx as nx
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.write_dot(G,'test.dot')

# same layout using matplotlib with no labels
plt.title('draw_networkx')
pos=nx.graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=False, arrows=False)
plt.savefig('nx_test.png')

我想画一棵树,如下图所示。

但是,我收到一条错误消息 AttributeError: module 'networkx' has no attribute 'write_dot'。我的 networkx 版本是 1.11(使用 conda)。我尝试了不同的 hacks,但其中 none 有效。

所以,我很想知道是否有另一种使用 networkx 绘制树结构的方法来获得类似于图中提到的输出。请告诉我。

我认为这个问题已在 networkx 2.x 上解决,但在此之前你应该像这样显式导入函数。

from networkx.drawing.nx_agraph import write_dot

from networkx.drawing.nx_pydot import write_dot

我希望这能奏效。

你完全可以用pygraphviz画出二合字母。

需要先执行以下步骤,因为 pygraphviz 没有 graphviz 就无法工作(截至目前)。

  1. http://www.graphviz.org/Download_windows.php 下载 graphviz-2.38.msi 并安装
  2. http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygraphviz
  3. 下载 2.7 或 3.4 pygraphviz wheel 文件
  4. 导航到您下载 wheel 文件的目录和 运行 您的平台特定的 wheel pip install pygraphviz‑1.3.1‑cp34‑none‑win32.whl
  5. 添加 dot.exe 到主机路径 例如在 windows 控制面板 -> 系统 -> 编辑环境变量 -> 修改 PATH

之后可以创建 dotpng 文件,如下所示。

工作代码

import pygraphviz as pgv

G=pgv.AGraph(directed=True)

#Attributes can be added when adding nodes or edge
G.add_node("ROOT", color='red')
for i in range(5):
    G.add_node("Child_%i" % i, color='blue')
    G.add_node("Grandchild_%i" % i, color='blue')
    G.add_node("Greatgrandchild_%i" % i, color='blue')

    G.add_edge("ROOT", "Child_%i" % i, color='blue')
    G.add_edge("Child_%i" % i, "Grandchild_%i" % i, color='blue')
    G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i, color='blue')

# write to a dot file
G.write('test.dot')

#create a png file
G.layout(prog='dot') # use dot
G.draw('file.png')

PNG 文件