You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NetworkX 1.11绘制树形图遇write_dot属性错误,求替代方案

解决NetworkX 1.11中write_dot报错及树形结构绘制方案

你遇到的AttributeError是因为在NetworkX 1.11版本中,write_dot函数并不在主模块下,而是被放在了nx.drawing.nx_pydot子模块里。下面给你几种可行的方案,既能解决当前报错,也能绘制出层次分明的树形结构:

方案一:修正write_dot的调用方式

直接使用子模块下的函数,同时确保布局函数的调用路径正确:

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调用路径
nx.drawing.nx_pydot.write_dot(G, 'test.dot')

# 绘制部分也对应调整graphviz_layout的路径
plt.title('Hierarchical Tree Structure')
pos = nx.drawing.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=True, arrows=True, node_size=1500, font_size=10)
plt.savefig('nx_test.png')
plt.show()

方案二:不依赖graphviz,手动构建层次布局

如果你的graphviz环境配置有问题,也可以手动计算节点位置,实现规整的树形展示:

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)

# 手动定义层级位置:按树形层级分配y轴,同层级均匀分配x轴
pos = {}
# 第0层:根节点
pos["ROOT"] = (2.5, 3)
# 第1层:子节点
for i in range(5):
    pos["Child_%i" % i] = (i, 2)
# 第2层:孙节点
for i in range(5):
    pos["Grandchild_%i" % i] = (i, 1)
# 第3层:曾孙节点
for i in range(5):
    pos["Greatgrandchild_%i" % i] = (i, 0)

plt.title('Manual Hierarchical Tree')
nx.draw(G, pos, with_labels=True, arrows=True, node_color='lightblue', node_size=1500, font_size=10)
plt.savefig('manual_tree.png')
plt.show()

方案三:用pydot直接生成高质量树形图

如果更看重dot格式的绘图效果,可以借助pydot库(先通过conda install pydot安装):

import networkx as nx
import pydot

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)

# 转换为pydot格式并输出
pydot_graph = nx.drawing.nx_pydot.to_pydot(G)
pydot_graph.write_dot('test_pydot.dot')
pydot_graph.write_png('pydot_tree.png')

这些方案都适配NetworkX 1.11版本,其中方案一和三依赖已有的graphviz环境,方案二则完全不需要额外依赖,能快速生成树形结构。

内容的提问来源于stack exchange,提问作者J Cena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:59:56