AttributeError: module 'networkx' has no attribute 'draw_graphviz'解决方案
環(huán)境:
Python2.7 (64)、ubuntu環(huán)境下
被運行的代碼來自《Python自然語言處理》的P185-186,代碼如下:
P185-186.py
import networkx as nx import matplotlib from nltk.corpus import wordnet as wndef traverse(graph, start, node):graph.depth[node.name] = node.shortest_path_distance(start)for child in node.hyponyms():graph.add_edge(node.name, child.name) traverse(graph, start, child) def hyponym_graph(start):G = nx.Graph() G.depth = {}traverse(G, start, start)return G def graph_draw(graph):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)matplotlib.pyplot.show()if __name__=='__main__':dog=wn.synset('dog.n.01')graph=hyponym_graph(dog)graph_draw(graph)代碼無法運行,直接報錯:
AttributeError: module 'networkx' has no attribute 'draw_graphviz'
非常坑,消耗了我好幾個小時,stackflow上面也沒有答案,本文末尾的參考鏈接3中直接放棄了draw_graphviz這個函數(shù),把draw_graphviz改為draw。
最終解決方案如下:
一、
apt-get install graphviz
apt-get install graphviz-dev
apt-get install graphviz-doc
pip install pygraphviz
pip install networkx
pip install matplotlib
把本文末尾的參考鏈接2中的nx_pylab.py(因為是doc里面的源碼,所以要把所有的[doc]def改為def)
覆蓋以下路徑中的nx_pylab.py
/home/appleyuchi/.virtualenvs/python2.7/lib/python2.7/site-packages/networkx/drawing
(注意,不要使用github中的nx_pylab.py,這個太舊了,沒有draw_graphviz函數(shù),所以不行)
當然到這里,還是沒完,這個時候,重新運行上面的P185-186.py,錯誤會變成:
AttributeError: module 'networkx.drawing' has no attribute 'graphviz_layout'
繼續(xù)修改
draw_graphviz,換了一種import那個 graphviz_layout的方法就好了。
修改好的nx_pylab.py
""" ********** Matplotlib **********Draw networks with matplotlib.See Also --------matplotlib: http://matplotlib.sourceforge.net/pygraphviz: http://networkx.lanl.gov/pygraphviz/""" # Copyright (C) 2004-2012 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. import networkx as nx from networkx.drawing.layout import shell_layout,\circular_layout,spectral_layout,spring_layout,random_layout __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __all__ = ['draw','draw_networkx','draw_networkx_nodes','draw_networkx_edges','draw_networkx_labels','draw_networkx_edge_labels','draw_circular','draw_random','draw_spectral','draw_spring','draw_shell','draw_graphviz']def draw(G, pos=None, ax=None, hold=None, **kwds):"""Draw the graph G with Matplotlib.Draw the graph as a simple representation with no nodelabels or edge labels and using the full Matplotlib figure areaand no axis labels by default. See draw_networkx() for morefull-featured drawing that allows title, axis labels etc.Parameters----------G : graphA networkx graphpos : dictionary, optionalA dictionary with nodes as keys and positions as values.If not specified a spring layout positioning will be computed.See networkx.layout for functions that compute node positions.ax : Matplotlib Axes object, optionalDraw the graph in specified Matplotlib axes.hold : bool, optionalSet the Matplotlib hold state. If True subsequent drawcommands will be added to the current axes.**kwds : optional keywordsSee networkx.draw_networkx() for a description of optional keywords.Examples-------->>> G=nx.dodecahedral_graph()>>> nx.draw(G)>>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layoutSee Also--------draw_networkx()draw_networkx_nodes()draw_networkx_edges()draw_networkx_labels()draw_networkx_edge_labels()Notes-----This function has the same name as pylab.draw and pyplot.drawso beware when using>>> from networkx import *since you might overwrite the pylab.draw function.With pyplot use>>> import matplotlib.pyplot as plt>>> import networkx as nx>>> G=nx.dodecahedral_graph()>>> nx.draw(G) # networkx draw()>>> plt.draw() # pyplot draw()Also see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.html"""try:import matplotlib.pyplot as pltexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif ax is None:cf = plt.gcf()else:cf = ax.get_figure()cf.set_facecolor('w')if ax is None:if cf._axstack() is None:ax = cf.add_axes((0, 0, 1, 1))else:ax = cf.gca()# allow callers to override the hold state by passing hold=True|Falseif 'with_labels' not in kwds:kwds['with_labels'] = Falseb = plt.ishold()h = kwds.pop('hold', None)if h is not None:plt.hold(h)try:draw_networkx(G, pos=pos, ax=ax, **kwds)ax.set_axis_off()plt.draw_if_interactive()except:plt.hold(b)raiseplt.hold(b)returndef draw_networkx(G, pos=None, with_labels=True, **kwds):"""Draw the graph G using Matplotlib.Draw the graph with Matplotlib with options for node positions,labeling, titles, and many other drawing features.See draw() for simple drawing without labels or axes.Parameters----------G : graphA networkx graphpos : dictionary, optionalA dictionary with nodes as keys and positions as values.If not specified a spring layout positioning will be computed.See networkx.layout for functions that compute node positions.with_labels : bool, optional (default=True)Set to True to draw labels on the nodes.ax : Matplotlib Axes object, optionalDraw the graph in the specified Matplotlib axes.nodelist : list, optional (default G.nodes())Draw only specified nodesedgelist : list, optional (default=G.edges())Draw only specified edgesnode_size : scalar or array, optional (default=300)Size of nodes. If an array is specified it must be thesame length as nodelist.node_color : color string, or array of floats, (default='r')Node color. Can be a single color format string,or a sequence of colors with the same length as nodelist.If numeric values are specified they will be mapped tocolors using the cmap and vmin,vmax parameters. Seematplotlib.scatter for more details.node_shape : string, optional (default='o')The shape of the node. Specification is as matplotlib.scattermarker, one of 'so^>v<dph8'.alpha : float, optional (default=1.0)The node transparencycmap : Matplotlib colormap, optional (default=None)Colormap for mapping intensities of nodesvmin,vmax : float, optional (default=None)Minimum and maximum for node colormap scalinglinewidths : [None | scalar | sequence]Line width of symbol border (default =1.0)width : float, optional (default=1.0)Line width of edgesedge_color : color string, or array of floats (default='r')Edge color. Can be a single color format string,or a sequence of colors with the same length as edgelist.If numeric values are specified they will be mapped tocolors using the edge_cmap and edge_vmin,edge_vmax parameters.edge_cmap : Matplotlib colormap, optional (default=None)Colormap for mapping intensities of edgesedge_vmin,edge_vmax : floats, optional (default=None)Minimum and maximum for edge colormap scalingstyle : string, optional (default='solid')Edge line style (solid|dashed|dotted,dashdot)labels : dictionary, optional (default=None)Node labels in a dictionary keyed by node of text labelsfont_size : int, optional (default=12)Font size for text labelsfont_color : string, optional (default='k' black)Font color stringfont_weight : string, optional (default='normal')Font weightfont_family : string, optional (default='sans-serif')Font familylabel : string, optionalLabel for graph legendExamples-------->>> G=nx.dodecahedral_graph()>>> nx.draw(G)>>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout>>> import matplotlib.pyplot as plt>>> limits=plt.axis('off') # turn of axisAlso see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.htmlSee Also--------draw()draw_networkx_nodes()draw_networkx_edges()draw_networkx_labels()draw_networkx_edge_labels()"""try:import matplotlib.pyplot as pltexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif pos is None:pos = nx.drawing.spring_layout(G) # default to spring layoutnode_collection = draw_networkx_nodes(G, pos, **kwds)edge_collection = draw_networkx_edges(G, pos, **kwds)if with_labels:draw_networkx_labels(G, pos, **kwds)plt.draw_if_interactive()def draw_networkx_nodes(G, pos,nodelist=None,node_size=300,node_color='r',node_shape='o',alpha=1.0,cmap=None,vmin=None,vmax=None,ax=None,linewidths=None,label=None,**kwds):"""Draw the nodes of the graph G.This draws only the nodes of the graph G.Parameters----------G : graphA networkx graphpos : dictionaryA dictionary with nodes as keys and positions as values.Positions should be sequences of length 2.ax : Matplotlib Axes object, optionalDraw the graph in the specified Matplotlib axes.nodelist : list, optionalDraw only specified nodes (default G.nodes())node_size : scalar or arraySize of nodes (default=300). If an array is specified it must be thesame length as nodelist.node_color : color string, or array of floatsNode color. Can be a single color format string (default='r'),or a sequence of colors with the same length as nodelist.If numeric values are specified they will be mapped tocolors using the cmap and vmin,vmax parameters. Seematplotlib.scatter for more details.node_shape : stringThe shape of the node. Specification is as matplotlib.scattermarker, one of 'so^>v<dph8' (default='o').alpha : floatThe node transparency (default=1.0)cmap : Matplotlib colormapColormap for mapping intensities of nodes (default=None)vmin,vmax : floatsMinimum and maximum for node colormap scaling (default=None)linewidths : [None | scalar | sequence]Line width of symbol border (default =1.0)label : [None| string]Label for legendReturns-------matplotlib.collections.PathCollection`PathCollection` of the nodes.Examples-------->>> G=nx.dodecahedral_graph()>>> nodes=nx.draw_networkx_nodes(G,pos=nx.spring_layout(G))Also see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.htmlSee Also--------draw()draw_networkx()draw_networkx_edges()draw_networkx_labels()draw_networkx_edge_labels()"""try:import matplotlib.pyplot as pltimport numpyexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif ax is None:ax = plt.gca()if nodelist is None:nodelist = G.nodes()if not nodelist or len(nodelist) == 0: # empty nodelist, no drawingreturn Nonetry:xy = numpy.asarray([pos[v] for v in nodelist])except KeyError as e:raise nx.NetworkXError('Node %s has no position.'%e)except ValueError:raise nx.NetworkXError('Bad value in node positions.')node_collection = ax.scatter(xy[:, 0], xy[:, 1],s=node_size,c=node_color,marker=node_shape,cmap=cmap,vmin=vmin,vmax=vmax,alpha=alpha,linewidths=linewidths,label=label)node_collection.set_zorder(2)return node_collectiondef draw_networkx_edges(G, pos,edgelist=None,width=1.0,edge_color='k',style='solid',alpha=None,edge_cmap=None,edge_vmin=None,edge_vmax=None,ax=None,arrows=True,label=None,**kwds):"""Draw the edges of the graph G.This draws only the edges of the graph G.Parameters----------G : graphA networkx graphpos : dictionaryA dictionary with nodes as keys and positions as values.Positions should be sequences of length 2.edgelist : collection of edge tuplesDraw only specified edges(default=G.edges())width : floatLine width of edges (default =1.0)edge_color : color string, or array of floatsEdge color. Can be a single color format string (default='r'),or a sequence of colors with the same length as edgelist.If numeric values are specified they will be mapped tocolors using the edge_cmap and edge_vmin,edge_vmax parameters.style : stringEdge line style (default='solid') (solid|dashed|dotted,dashdot)alpha : floatThe edge transparency (default=1.0)edge_ cmap : Matplotlib colormapColormap for mapping intensities of edges (default=None)edge_vmin,edge_vmax : floatsMinimum and maximum for edge colormap scaling (default=None)ax : Matplotlib Axes object, optionalDraw the graph in the specified Matplotlib axes.arrows : bool, optional (default=True)For directed graphs, if True draw arrowheads.label : [None| string]Label for legendReturns-------matplotlib.collection.LineCollection`LineCollection` of the edgesNotes-----For directed graphs, "arrows" (actually just thicker stubs) are drawnat the head end. Arrows can be turned off with keyword arrows=False.Yes, it is ugly but drawing proper arrows with Matplotlib thisway is tricky.Examples-------->>> G=nx.dodecahedral_graph()>>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))Also see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.htmlSee Also--------draw()draw_networkx()draw_networkx_nodes()draw_networkx_labels()draw_networkx_edge_labels()"""try:import matplotlibimport matplotlib.pyplot as pltimport matplotlib.cbook as cbfrom matplotlib.colors import colorConverter, Colormapfrom matplotlib.collections import LineCollectionimport numpyexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif ax is None:ax = plt.gca()if edgelist is None:edgelist = G.edges()if not edgelist or len(edgelist) == 0: # no edges!return None# set edge positionsedge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])if not cb.iterable(width):lw = (width,)else:lw = widthif not cb.is_string_like(edge_color) \and cb.iterable(edge_color) \and len(edge_color) == len(edge_pos):if numpy.alltrue([cb.is_string_like(c)for c in edge_color]):# (should check ALL elements)# list of color letters such as ['k','r','k',...]edge_colors = tuple([colorConverter.to_rgba(c, alpha)for c in edge_color])elif numpy.alltrue([not cb.is_string_like(c)for c in edge_color]):# If color specs are given as (rgb) or (rgba) tuples, we're OKif numpy.alltrue([cb.iterable(c) and len(c) in (3, 4)for c in edge_color]):edge_colors = tuple(edge_color)else:# numbers (which are going to be mapped with a colormap)edge_colors = Noneelse:raise ValueError('edge_color must consist of either color names or numbers')else:if cb.is_string_like(edge_color) or len(edge_color) == 1:edge_colors = (colorConverter.to_rgba(edge_color, alpha), )else:raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')edge_collection = LineCollection(edge_pos,colors=edge_colors,linewidths=lw,antialiaseds=(1,),linestyle=style,transOffset = ax.transData,)edge_collection.set_zorder(1) # edges go behind nodesedge_collection.set_label(label)ax.add_collection(edge_collection)# Note: there was a bug in mpl regarding the handling of alpha values for# each line in a LineCollection. It was fixed in matplotlib in r7184 and# r7189 (June 6 2009). We should then not set the alpha value globally,# since the user can instead provide per-edge alphas now. Only set it# globally if provided as a scalar.if cb.is_numlike(alpha):edge_collection.set_alpha(alpha)if edge_colors is None:if edge_cmap is not None:assert(isinstance(edge_cmap, Colormap))edge_collection.set_array(numpy.asarray(edge_color))edge_collection.set_cmap(edge_cmap)if edge_vmin is not None or edge_vmax is not None:edge_collection.set_clim(edge_vmin, edge_vmax)else:edge_collection.autoscale()arrow_collection = Noneif G.is_directed() and arrows:# a directed graph hack# draw thick line segments at head end of edge# waiting for someone else to implement arrows that will workarrow_colors = edge_colorsa_pos = []p = 1.0-0.25 # make head segment 25 percent of edge lengthfor src, dst in edge_pos:x1, y1 = srcx2, y2 = dstdx = x2-x1 # x offsetdy = y2-y1 # y offsetd = numpy.sqrt(float(dx**2 + dy**2)) # length of edgeif d == 0: # source and target at same positioncontinueif dx == 0: # vertical edgexa = x2ya = dy*p+y1if dy == 0: # horizontal edgeya = y2xa = dx*p+x1else:theta = numpy.arctan2(dy, dx)xa = p*d*numpy.cos(theta)+x1ya = p*d*numpy.sin(theta)+y1a_pos.append(((xa, ya), (x2, y2)))arrow_collection = LineCollection(a_pos,colors=arrow_colors,linewidths=[4*ww for ww in lw],antialiaseds=(1,),transOffset = ax.transData,)arrow_collection.set_zorder(1) # edges go behind nodesarrow_collection.set_label(label)ax.add_collection(arrow_collection)# update viewminx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0]))miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1]))maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1]))w = maxx-minxh = maxy-minypadx, pady = 0.05*w, 0.05*hcorners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)ax.update_datalim(corners)ax.autoscale_view()# if arrow_collection:return edge_collectiondef draw_networkx_labels(G, pos,labels=None,font_size=12,font_color='k',font_family='sans-serif',font_weight='normal',alpha=1.0,ax=None,**kwds):"""Draw node labels on the graph G.Parameters----------G : graphA networkx graphpos : dictionaryA dictionary with nodes as keys and positions as values.Positions should be sequences of length 2.labels : dictionary, optional (default=None)Node labels in a dictionary keyed by node of text labelsfont_size : intFont size for text labels (default=12)font_color : stringFont color string (default='k' black)font_family : stringFont family (default='sans-serif')font_weight : stringFont weight (default='normal')alpha : floatThe text transparency (default=1.0)ax : Matplotlib Axes object, optionalDraw the graph in the specified Matplotlib axes.Returns-------dict`dict` of labels keyed on the nodesExamples-------->>> G=nx.dodecahedral_graph()>>> labels=nx.draw_networkx_labels(G,pos=nx.spring_layout(G))Also see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.htmlSee Also--------draw()draw_networkx()draw_networkx_nodes()draw_networkx_edges()draw_networkx_edge_labels()"""try:import matplotlib.pyplot as pltimport matplotlib.cbook as cbexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif ax is None:ax = plt.gca()if labels is None:labels = dict((n, n) for n in G.nodes())# set optional alignmenthorizontalalignment = kwds.get('horizontalalignment', 'center')verticalalignment = kwds.get('verticalalignment', 'center')text_items = {} # there is no text collection so we'll fake onefor n, label in labels.items():(x, y) = pos[n]if not cb.is_string_like(label):label = str(label) # this will cause "1" and 1 to be labeled the samet = ax.text(x, y,label,size=font_size,color=font_color,family=font_family,weight=font_weight,horizontalalignment=horizontalalignment,verticalalignment=verticalalignment,transform=ax.transData,clip_on=True,)text_items[n] = treturn text_itemsdef draw_networkx_edge_labels(G, pos,edge_labels=None,label_pos=0.5,font_size=10,font_color='k',font_family='sans-serif',font_weight='normal',alpha=1.0,bbox=None,ax=None,rotate=True,**kwds):"""Draw edge labels.Parameters----------G : graphA networkx graphpos : dictionaryA dictionary with nodes as keys and positions as values.Positions should be sequences of length 2.ax : Matplotlib Axes object, optionalDraw the graph in the specified Matplotlib axes.alpha : floatThe text transparency (default=1.0)edge_labels : dictionaryEdge labels in a dictionary keyed by edge two-tuple of textlabels (default=None). Only labels for the keys in the dictionaryare drawn.label_pos : floatPosition of edge label along edge (0=head, 0.5=center, 1=tail)font_size : intFont size for text labels (default=12)font_color : stringFont color string (default='k' black)font_weight : stringFont weight (default='normal')font_family : stringFont family (default='sans-serif')bbox : Matplotlib bboxSpecify text box shape and colors.clip_on : boolTurn on clipping at axis boundaries (default=True)Returns-------dict`dict` of labels keyed on the edgesExamples-------->>> G=nx.dodecahedral_graph()>>> edge_labels=nx.draw_networkx_edge_labels(G,pos=nx.spring_layout(G))Also see the NetworkX drawing examples athttp://networkx.lanl.gov/gallery.htmlSee Also--------draw()draw_networkx()draw_networkx_nodes()draw_networkx_edges()draw_networkx_labels()"""try:import matplotlib.pyplot as pltimport matplotlib.cbook as cbimport numpyexcept ImportError:raise ImportError("Matplotlib required for draw()")except RuntimeError:print("Matplotlib unable to open display")raiseif ax is None:ax = plt.gca()if edge_labels is None:labels = dict(((u, v), d) for u, v, d in G.edges(data=True))else:labels = edge_labelstext_items = {}for (n1, n2), label in labels.items():(x1, y1) = pos[n1](x2, y2) = pos[n2](x, y) = (x1 * label_pos + x2 * (1.0 - label_pos),y1 * label_pos + y2 * (1.0 - label_pos))if rotate:angle = numpy.arctan2(y2-y1, x2-x1)/(2.0*numpy.pi)*360 # degrees# make label orientation "right-side-up"if angle > 90:angle -= 180if angle < - 90:angle += 180# transform data coordinate angle to screen coordinate anglexy = numpy.array((x, y))trans_angle = ax.transData.transform_angles(numpy.array((angle,)),xy.reshape((1, 2)))[0]else:trans_angle = 0.0# use default box of white with white borderif bbox is None:bbox = dict(boxstyle='round',ec=(1.0, 1.0, 1.0),fc=(1.0, 1.0, 1.0),)if not cb.is_string_like(label):label = str(label) # this will cause "1" and 1 to be labeled the same# set optional alignmenthorizontalalignment = kwds.get('horizontalalignment', 'center')verticalalignment = kwds.get('verticalalignment', 'center')t = ax.text(x, y,label,size=font_size,color=font_color,family=font_family,weight=font_weight,horizontalalignment=horizontalalignment,verticalalignment=verticalalignment,rotation=trans_angle,transform=ax.transData,bbox=bbox,zorder=1,clip_on=True,)text_items[(n1, n2)] = treturn text_itemsdef draw_circular(G, **kwargs):"""Draw the graph G with a circular layout.Parameters----------G : graphA networkx graph**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords,with the exception of the pos parameter which is not used by this function."""draw(G, circular_layout(G), **kwargs)def draw_random(G, **kwargs):"""Draw the graph G with a random layout.Parameters----------G : graphA networkx graph**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords,with the exception of the pos parameter which is not used by this function."""draw(G, random_layout(G), **kwargs)def draw_spectral(G, **kwargs):"""Draw the graph G with a spectral layout.Parameters----------G : graphA networkx graph**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords,with the exception of the pos parameter which is not used by this function."""draw(G, spectral_layout(G), **kwargs)def draw_spring(G, **kwargs):"""Draw the graph G with a spring layout.Parameters----------G : graphA networkx graph**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords,with the exception of the pos parameter which is not used by this function."""draw(G, spring_layout(G), **kwargs)def draw_shell(G, **kwargs):"""Draw networkx graph with shell layout.Parameters----------G : graphA networkx graph**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords,with the exception of the pos parameter which is not used by this function."""nlist = kwargs.get('nlist', None)if nlist is not None:del(kwargs['nlist'])draw(G, shell_layout(G, nlist=nlist), **kwargs)def draw_graphviz(G, prog="neato", **kwargs):from nx_agraph import graphviz_layout"""Draw networkx graph with graphviz layout.Parameters----------G : graphA networkx graphprog : string, optionalName of Graphviz layout program**kwargs : optional keywordsSee networkx.draw_networkx() for a description of optional keywords."""# pos = nx.drawing.graphviz_layout(G, prog)pos=graphviz_layout(G, prog)draw(G, pos, **kwargs)def draw_nx(G, pos, **kwds):"""For backward compatibility; use draw or draw_networkx."""draw(G, pos, **kwds)# fixture for nose tests def setup_module(module):from nose import SkipTesttry:import matplotlib as mplmpl.use('PS', warn=False)import matplotlib.pyplot as pltexcept:raise SkipTest("matplotlib not available")最終結果:
注意,以上方法對python3.x無效,請知悉。
幾個重要的參考鏈接:
參考鏈接:
1
https://networkx.github.io/documentation/networkx-1.9/_modules/networkx/drawing/nx_pylab.html#draw_graphviz
2
https://github.com/networkx/networkx/blob/master/networkx/drawing/nx_pylab.py
3
https://stackoverflow.com/questions/41047362/python-networkx-error-module-networkx-drawing-has-no-attribute-graphviz-layo
總結
以上是生活随笔為你收集整理的AttributeError: module 'networkx' has no attribute 'draw_graphviz'解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 布朗语料库中不同部分的情态动词频率直方图
- 下一篇: ImportError: numpy.c