Skip to main content
 首页 » 编程设计

python之使用networkX输出树结构

2024年09月07日13JeffreyZhao

我正在使用 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 , 但它们都不起作用。

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

请您参考如下方法:

您可以完全使用 pygraphviz 绘制二合字母。

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

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

dot 和 png 文件可以如下创建。

工作代码

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文件