Python NetworkX error: module 'networkx.drawing' has no attribute 'graphviz_layout'

Python NetworkX error: module 'networkx.drawing' has no attribute 'graphviz_layout'

我正在使用本书 "Natural Language Processing with Python" ("www.nltk.org/book") 自学 Python 和 NLTK 以供工作。

我卡在了 NetworkX 上的第 4 章第 4 节第 8 部分。当我尝试 运行 示例 4.15 时,它应该绘制一个图形,但我却收到以下错误消息:

AttributeError: module 'networkx.drawing' has no attribute 'graphviz_layout'

罪魁祸首代码行似乎是

>>> nx.draw_graphviz(graph,
    node_size = [16 * graph.degree(n) for n in graph],
    node_color = [graph.depth[n] for n in graph],
    with_labels = False)

这里是从 "networkx.github.io/documentation/networkx-1.10/tutorial/tutorial.html"

借用的简化代码
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
>>> G.add_node(1)
>>> G.add_nodes_from([2,3])
>>> nx.draw_graphviz(G)  
Traceback (most recent call last):
  File "<pyshell#92>", line 1, in <module>
    nx.draw_graphviz(G)
  File "C:\Users\Cheese\AppData\Local\Programs\Python\Python35-32\lib\site-packages\networkx\drawing\nx_pylab.py", line 984, in draw_graphviz
    pos = nx.drawing.graphviz_layout(G, prog)
AttributeError: module 'networkx.drawing' has no attribute 'graphviz_layout'
>>> 

你能告诉我如何解决这个问题吗?

我正在使用 Windows 7 家庭高级版,使用 Python 3.5、Graphviz2.38(那个目录在 PATH 环境变量中)和 NetworkX 1.11。

我用谷歌搜索了很多次,但找不到适合我的东西。我浏览了 NetworkX 和 graphviz 教程,但也没有帮助。

以下是我发现没有帮助的内容:

"whosebug.com/questions/39411102/attributeerror-module-object-has-no-attribute-graphviz-layout-with-networkx"(答案代码给了我同样的错误信息)

"python.thenaiveapproach.com/buggy-module-installation-networkx-pygraphviz/"(根据错误消息,需要 pygraphviz,我无法安装它。pip 表示它需要 Visual C++ 才能 运行,但我无法在我的工作计算机上安装它。 )

"codedump.io/share/c3aAbCneu2oA/1/attributeerror-39module39-object-has-no-attribute-39graphvizlayout39-with-networkx-111"(还需要 pygraphviz——见上文)

非常感谢, 詹妮弗

答案由@Bonlenfum 提供,代码来自 https://networkx.github.io/documentation/networkx-1.10/examples/drawing/simple_path.html

这是有效的代码:

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
>>> G.add_node(1)
>>> G.add_nodes_from([2,3])
>>> nx.draw(G)
>>> plt.savefig("simple_path.png")
>>> plt.show()

下面是 NLTK 书中调整后的代码:

try:
    import matplotlib.pyplot as plt
except:
    raise

def graph_draw(graph):
    nx.draw(graph,
         node_size = [16 * graph.degree(n) for n in graph],
         node_color = [graph.depth[n] for n in graph],
         with_labels = False)