问题
I am teaching myself Python and NLTK for work using the book "Natural Language Processing with Python" ("www.nltk.org/book").
I am stuck on Chapter 4 Section 4 part 8 on NetworkX. When I try to run example 4.15, it should draw a graph, but instead I get the following error message:
AttributeError: module 'networkx.drawing' has no attribute 'graphviz_layout'
The culprit code line appears to be
>>> 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)
Here is simplified code borrowed from "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'
>>>
Can you tell me how to fix this please?
I am on Windows 7 home premium, using Python 3.5, Graphviz2.38 (and the directory for that one is in the PATH environment variable), and NetworkX 1.11.
I have googled multiple times and can't find anything that works for me. I went through the NetworkX and graphviz tutorials and that didn't help either.
Here's what I found that didn't help:
"stackoverflow.com/questions/39411102/attributeerror-module-object-has-no-attribute-graphviz-layout-with-networkx" (answer code gave me the same error message)
"python.thenaiveapproach.com/buggy-module-installation-networkx-pygraphviz/" (per error message, requires pygraphviz, which I can't install. pip says it needs Visual C++ to run, and I can't install that on my work computer.)
"codedump.io/share/c3aAbCneu2oA/1/attributeerror-39module39-object-has-no-attribute-39graphvizlayout39-with-networkx-111" (Requires pygraphviz also -- see above)
Many thanks, Jennifer
回答1:
The answer is courtesy @Bonlenfum and code from https://networkx.github.io/documentation/networkx-1.10/examples/drawing/simple_path.html
Here's the code that worked:
>>> 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()
And here's the adjusted code from the NLTK book:
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)
来源:https://stackoverflow.com/questions/41047362/python-networkx-error-module-networkx-drawing-has-no-attribute-graphviz-layo