当前位置:   article > 正文

AttributeError: module 'networkx' has no attribute 'draw_graphviz'解决方案_network' object has no attribute 'draw

network' object has no attribute 'draw

环境:

Python2.7 (64)、ubuntu环境下


被运行的代码来自《Python自然语言处理》的P185-186,代码如下:

P185-186.py

  1. import networkx as nx
  2. import matplotlib
  3. from nltk.corpus import wordnet as wn
  4. def traverse(graph, start, node):
  5. graph.depth[node.name] = node.shortest_path_distance(start)
  6. for child in node.hyponyms():
  7. graph.add_edge(node.name, child.name)
  8. traverse(graph, start, child)
  9. def hyponym_graph(start):
  10. G = nx.Graph()
  11. G.depth = {}
  12. traverse(G, start, start)
  13. return G
  14. def graph_draw(graph):
  15. nx.draw_graphviz(graph,
  16. node_size = [16 * graph.degree(n) for n in graph],
  17. node_color = [graph.depth[n] for n in graph],
  18. with_labels = False)
  19. matplotlib.pyplot.show()
  20. if __name__=='__main__':
  21. dog=wn.synset('dog.n.01')
  22. graph=hyponym_graph(dog)
  23. graph_draw(graph)

代码无法运行,直接报错:

AttributeError: module 'networkx' has no attribute 'draw_graphviz'

非常坑,消耗了我好几个小时,stackflow上面也没有答案,本文末尾的参考链接3中直接放弃了draw_graphviz这个函数,把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函数,所以不行)

当然到这里,还是没完,这个时候,重新运行上面的P185-186.py,错误会变成:

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

继续修改

draw_graphviz,换了一种import那个 graphviz_layout的方法就好了。


修改好的nx_pylab.py

  1. """
  2. **********
  3. Matplotlib
  4. **********
  5. Draw networks with matplotlib.
  6. See Also
  7. --------
  8. matplotlib: http://matplotlib.sourceforge.net/
  9. pygraphviz: http://networkx.lanl.gov/pygraphviz/
  10. """
  11. # Copyright (C) 2004-2012 by
  12. # Aric Hagberg <hagberg@lanl.gov>
  13. # Dan Schult <dschult@colgate.edu>
  14. # Pieter Swart <swart@lanl.gov>
  15. # All rights reserved.
  16. # BSD license.
  17. import networkx as nx
  18. from networkx.drawing.layout import shell_layout,\
  19. circular_layout,spectral_layout,spring_layout,random_layout
  20. __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
  21. __all__ = ['draw',
  22. 'draw_networkx',
  23. 'draw_networkx_nodes',
  24. 'draw_networkx_edges',
  25. 'draw_networkx_labels',
  26. 'draw_networkx_edge_labels',
  27. 'draw_circular',
  28. 'draw_random',
  29. 'draw_spectral',
  30. 'draw_spring',
  31. 'draw_shell',
  32. 'draw_graphviz']
  33. def draw(G, pos=None, ax=None, hold=None, **kwds):
  34. """Draw the graph G with Matplotlib.
  35. Draw the graph as a simple representation with no node
  36. labels or edge labels and using the full Matplotlib figure area
  37. and no axis labels by default. See draw_networkx() for more
  38. full-featured drawing that allows title, axis labels etc.
  39. Parameters
  40. ----------
  41. G : graph
  42. A networkx graph
  43. pos : dictionary, optional
  44. A dictionary with nodes as keys and positions as values.
  45. If not specified a spring layout positioning will be computed.
  46. See networkx.layout for functions that compute node positions.
  47. ax : Matplotlib Axes object, optional
  48. Draw the graph in specified Matplotlib axes.
  49. hold : bool, optional
  50. Set the Matplotlib hold state. If True subsequent draw
  51. commands will be added to the current axes.
  52. **kwds : optional keywords
  53. See networkx.draw_networkx() for a description of optional keywords.
  54. Examples
  55. --------
  56. >>> G=nx.dodecahedral_graph()
  57. >>> nx.draw(G)
  58. >>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout
  59. See Also
  60. --------
  61. draw_networkx()
  62. draw_networkx_nodes()
  63. draw_networkx_edges()
  64. draw_networkx_labels()
  65. draw_networkx_edge_labels()
  66. Notes
  67. -----
  68. This function has the same name as pylab.draw and pyplot.draw
  69. so beware when using
  70. >>> from networkx import *
  71. since you might overwrite the pylab.draw function.
  72. With pyplot use
  73. >>> import matplotlib.pyplot as plt
  74. >>> import networkx as nx
  75. >>> G=nx.dodecahedral_graph()
  76. >>> nx.draw(G) # networkx draw()
  77. >>> plt.draw() # pyplot draw()
  78. Also see the NetworkX drawing examples at
  79. http://networkx.lanl.gov/gallery.html
  80. """
  81. try:
  82. import matplotlib.pyplot as plt
  83. except ImportError:
  84. raise ImportError("Matplotlib required for draw()")
  85. except RuntimeError:
  86. print("Matplotlib unable to open display")
  87. raise
  88. if ax is None:
  89. cf = plt.gcf()
  90. else:
  91. cf = ax.get_figure()
  92. cf.set_facecolor('w')
  93. if ax is None:
  94. if cf._axstack() is None:
  95. ax = cf.add_axes((0, 0, 1, 1))
  96. else:
  97. ax = cf.gca()
  98. # allow callers to override the hold state by passing hold=True|False
  99. if 'with_labels' not in kwds:
  100. kwds['with_labels'] = False
  101. b = plt.ishold()
  102. h = kwds.pop('hold', None)
  103. if h is not None:
  104. plt.hold(h)
  105. try:
  106. draw_networkx(G, pos=pos, ax=ax, **kwds)
  107. ax.set_axis_off()
  108. plt.draw_if_interactive()
  109. except:
  110. plt.hold(b)
  111. raise
  112. plt.hold(b)
  113. return
  114. def draw_networkx(G, pos=None, with_labels=True, **kwds):
  115. """Draw the graph G using Matplotlib.
  116. Draw the graph with Matplotlib with options for node positions,
  117. labeling, titles, and many other drawing features.
  118. See draw() for simple drawing without labels or axes.
  119. Parameters
  120. ----------
  121. G : graph
  122. A networkx graph
  123. pos : dictionary, optional
  124. A dictionary with nodes as keys and positions as values.
  125. If not specified a spring layout positioning will be computed.
  126. See networkx.layout for functions that compute node positions.
  127. with_labels : bool, optional (default=True)
  128. Set to True to draw labels on the nodes.
  129. ax : Matplotlib Axes object, optional
  130. Draw the graph in the specified Matplotlib axes.
  131. nodelist : list, optional (default G.nodes())
  132. Draw only specified nodes
  133. edgelist : list, optional (default=G.edges())
  134. Draw only specified edges
  135. node_size : scalar or array, optional (default=300)
  136. Size of nodes. If an array is specified it must be the
  137. same length as nodelist.
  138. node_color : color string, or array of floats, (default='r')
  139. Node color. Can be a single color format string,
  140. or a sequence of colors with the same length as nodelist.
  141. If numeric values are specified they will be mapped to
  142. colors using the cmap and vmin,vmax parameters. See
  143. matplotlib.scatter for more details.
  144. node_shape : string, optional (default='o')
  145. The shape of the node. Specification is as matplotlib.scatter
  146. marker, one of 'so^>v<dph8'.
  147. alpha : float, optional (default=1.0)
  148. The node transparency
  149. cmap : Matplotlib colormap, optional (default=None)
  150. Colormap for mapping intensities of nodes
  151. vmin,vmax : float, optional (default=None)
  152. Minimum and maximum for node colormap scaling
  153. linewidths : [None | scalar | sequence]
  154. Line width of symbol border (default =1.0)
  155. width : float, optional (default=1.0)
  156. Line width of edges
  157. edge_color : color string, or array of floats (default='r')
  158. Edge color. Can be a single color format string,
  159. or a sequence of colors with the same length as edgelist.
  160. If numeric values are specified they will be mapped to
  161. colors using the edge_cmap and edge_vmin,edge_vmax parameters.
  162. edge_cmap : Matplotlib colormap, optional (default=None)
  163. Colormap for mapping intensities of edges
  164. edge_vmin,edge_vmax : floats, optional (default=None)
  165. Minimum and maximum for edge colormap scaling
  166. style : string, optional (default='solid')
  167. Edge line style (solid|dashed|dotted,dashdot)
  168. labels : dictionary, optional (default=None)
  169. Node labels in a dictionary keyed by node of text labels
  170. font_size : int, optional (default=12)
  171. Font size for text labels
  172. font_color : string, optional (default='k' black)
  173. Font color string
  174. font_weight : string, optional (default='normal')
  175. Font weight
  176. font_family : string, optional (default='sans-serif')
  177. Font family
  178. label : string, optional
  179. Label for graph legend
  180. Examples
  181. --------
  182. >>> G=nx.dodecahedral_graph()
  183. >>> nx.draw(G)
  184. >>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout
  185. >>> import matplotlib.pyplot as plt
  186. >>> limits=plt.axis('off') # turn of axis
  187. Also see the NetworkX drawing examples at
  188. http://networkx.lanl.gov/gallery.html
  189. See Also
  190. --------
  191. draw()
  192. draw_networkx_nodes()
  193. draw_networkx_edges()
  194. draw_networkx_labels()
  195. draw_networkx_edge_labels()
  196. """
  197. try:
  198. import matplotlib.pyplot as plt
  199. except ImportError:
  200. raise ImportError("Matplotlib required for draw()")
  201. except RuntimeError:
  202. print("Matplotlib unable to open display")
  203. raise
  204. if pos is None:
  205. pos = nx.drawing.spring_layout(G) # default to spring layout
  206. node_collection = draw_networkx_nodes(G, pos, **kwds)
  207. edge_collection = draw_networkx_edges(G, pos, **kwds)
  208. if with_labels:
  209. draw_networkx_labels(G, pos, **kwds)
  210. plt.draw_if_interactive()
  211. def draw_networkx_nodes(G, pos,
  212. nodelist=None,
  213. node_size=300,
  214. node_color='r',
  215. node_shape='o',
  216. alpha=1.0,
  217. cmap=None,
  218. vmin=None,
  219. vmax=None,
  220. ax=None,
  221. linewidths=None,
  222. label=None,
  223. **kwds):
  224. """Draw the nodes of the graph G.
  225. This draws only the nodes of the graph G.
  226. Parameters
  227. ----------
  228. G : graph
  229. A networkx graph
  230. pos : dictionary
  231. A dictionary with nodes as keys and positions as values.
  232. Positions should be sequences of length 2.
  233. ax : Matplotlib Axes object, optional
  234. Draw the graph in the specified Matplotlib axes.
  235. nodelist : list, optional
  236. Draw only specified nodes (default G.nodes())
  237. node_size : scalar or array
  238. Size of nodes (default=300). If an array is specified it must be the
  239. same length as nodelist.
  240. node_color : color string, or array of floats
  241. Node color. Can be a single color format string (default='r'),
  242. or a sequence of colors with the same length as nodelist.
  243. If numeric values are specified they will be mapped to
  244. colors using the cmap and vmin,vmax parameters. See
  245. matplotlib.scatter for more details.
  246. node_shape : string
  247. The shape of the node. Specification is as matplotlib.scatter
  248. marker, one of 'so^>v<dph8' (default='o').
  249. alpha : float
  250. The node transparency (default=1.0)
  251. cmap : Matplotlib colormap
  252. Colormap for mapping intensities of nodes (default=None)
  253. vmin,vmax : floats
  254. Minimum and maximum for node colormap scaling (default=None)
  255. linewidths : [None | scalar | sequence]
  256. Line width of symbol border (default =1.0)
  257. label : [None| string]
  258. Label for legend
  259. Returns
  260. -------
  261. matplotlib.collections.PathCollection
  262. `PathCollection` of the nodes.
  263. Examples
  264. --------
  265. >>> G=nx.dodecahedral_graph()
  266. >>> nodes=nx.draw_networkx_nodes(G,pos=nx.spring_layout(G))
  267. Also see the NetworkX drawing examples at
  268. http://networkx.lanl.gov/gallery.html
  269. See Also
  270. --------
  271. draw()
  272. draw_networkx()
  273. draw_networkx_edges()
  274. draw_networkx_labels()
  275. draw_networkx_edge_labels()
  276. """
  277. try:
  278. import matplotlib.pyplot as plt
  279. import numpy
  280. except ImportError:
  281. raise ImportError("Matplotlib required for draw()")
  282. except RuntimeError:
  283. print("Matplotlib unable to open display")
  284. raise
  285. if ax is None:
  286. ax = plt.gca()
  287. if nodelist is None:
  288. nodelist = G.nodes()
  289. if not nodelist or len(nodelist) == 0: # empty nodelist, no drawing
  290. return None
  291. try:
  292. xy = numpy.asarray([pos[v] for v in nodelist])
  293. except KeyError as e:
  294. raise nx.NetworkXError('Node %s has no position.'%e)
  295. except ValueError:
  296. raise nx.NetworkXError('Bad value in node positions.')
  297. node_collection = ax.scatter(xy[:, 0], xy[:, 1],
  298. s=node_size,
  299. c=node_color,
  300. marker=node_shape,
  301. cmap=cmap,
  302. vmin=vmin,
  303. vmax=vmax,
  304. alpha=alpha,
  305. linewidths=linewidths,
  306. label=label)
  307. node_collection.set_zorder(2)
  308. return node_collection
  309. def draw_networkx_edges(G, pos,
  310. edgelist=None,
  311. width=1.0,
  312. edge_color='k',
  313. style='solid',
  314. alpha=None,
  315. edge_cmap=None,
  316. edge_vmin=None,
  317. edge_vmax=None,
  318. ax=None,
  319. arrows=True,
  320. label=None,
  321. **kwds):
  322. """Draw the edges of the graph G.
  323. This draws only the edges of the graph G.
  324. Parameters
  325. ----------
  326. G : graph
  327. A networkx graph
  328. pos : dictionary
  329. A dictionary with nodes as keys and positions as values.
  330. Positions should be sequences of length 2.
  331. edgelist : collection of edge tuples
  332. Draw only specified edges(default=G.edges())
  333. width : float
  334. Line width of edges (default =1.0)
  335. edge_color : color string, or array of floats
  336. Edge color. Can be a single color format string (default='r'),
  337. or a sequence of colors with the same length as edgelist.
  338. If numeric values are specified they will be mapped to
  339. colors using the edge_cmap and edge_vmin,edge_vmax parameters.
  340. style : string
  341. Edge line style (default='solid') (solid|dashed|dotted,dashdot)
  342. alpha : float
  343. The edge transparency (default=1.0)
  344. edge_ cmap : Matplotlib colormap
  345. Colormap for mapping intensities of edges (default=None)
  346. edge_vmin,edge_vmax : floats
  347. Minimum and maximum for edge colormap scaling (default=None)
  348. ax : Matplotlib Axes object, optional
  349. Draw the graph in the specified Matplotlib axes.
  350. arrows : bool, optional (default=True)
  351. For directed graphs, if True draw arrowheads.
  352. label : [None| string]
  353. Label for legend
  354. Returns
  355. -------
  356. matplotlib.collection.LineCollection
  357. `LineCollection` of the edges
  358. Notes
  359. -----
  360. For directed graphs, "arrows" (actually just thicker stubs) are drawn
  361. at the head end. Arrows can be turned off with keyword arrows=False.
  362. Yes, it is ugly but drawing proper arrows with Matplotlib this
  363. way is tricky.
  364. Examples
  365. --------
  366. >>> G=nx.dodecahedral_graph()
  367. >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))
  368. Also see the NetworkX drawing examples at
  369. http://networkx.lanl.gov/gallery.html
  370. See Also
  371. --------
  372. draw()
  373. draw_networkx()
  374. draw_networkx_nodes()
  375. draw_networkx_labels()
  376. draw_networkx_edge_labels()
  377. """
  378. try:
  379. import matplotlib
  380. import matplotlib.pyplot as plt
  381. import matplotlib.cbook as cb
  382. from matplotlib.colors import colorConverter, Colormap
  383. from matplotlib.collections import LineCollection
  384. import numpy
  385. except ImportError:
  386. raise ImportError("Matplotlib required for draw()")
  387. except RuntimeError:
  388. print("Matplotlib unable to open display")
  389. raise
  390. if ax is None:
  391. ax = plt.gca()
  392. if edgelist is None:
  393. edgelist = G.edges()
  394. if not edgelist or len(edgelist) == 0: # no edges!
  395. return None
  396. # set edge positions
  397. edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
  398. if not cb.iterable(width):
  399. lw = (width,)
  400. else:
  401. lw = width
  402. if not cb.is_string_like(edge_color) \
  403. and cb.iterable(edge_color) \
  404. and len(edge_color) == len(edge_pos):
  405. if numpy.alltrue([cb.is_string_like(c)
  406. for c in edge_color]):
  407. # (should check ALL elements)
  408. # list of color letters such as ['k','r','k',...]
  409. edge_colors = tuple([colorConverter.to_rgba(c, alpha)
  410. for c in edge_color])
  411. elif numpy.alltrue([not cb.is_string_like(c)
  412. for c in edge_color]):
  413. # If color specs are given as (rgb) or (rgba) tuples, we're OK
  414. if numpy.alltrue([cb.iterable(c) and len(c) in (3, 4)
  415. for c in edge_color]):
  416. edge_colors = tuple(edge_color)
  417. else:
  418. # numbers (which are going to be mapped with a colormap)
  419. edge_colors = None
  420. else:
  421. raise ValueError('edge_color must consist of either color names or numbers')
  422. else:
  423. if cb.is_string_like(edge_color) or len(edge_color) == 1:
  424. edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
  425. else:
  426. raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')
  427. edge_collection = LineCollection(edge_pos,
  428. colors=edge_colors,
  429. linewidths=lw,
  430. antialiaseds=(1,),
  431. linestyle=style,
  432. transOffset = ax.transData,
  433. )
  434. edge_collection.set_zorder(1) # edges go behind nodes
  435. edge_collection.set_label(label)
  436. ax.add_collection(edge_collection)
  437. # Note: there was a bug in mpl regarding the handling of alpha values for
  438. # each line in a LineCollection. It was fixed in matplotlib in r7184 and
  439. # r7189 (June 6 2009). We should then not set the alpha value globally,
  440. # since the user can instead provide per-edge alphas now. Only set it
  441. # globally if provided as a scalar.
  442. if cb.is_numlike(alpha):
  443. edge_collection.set_alpha(alpha)
  444. if edge_colors is None:
  445. if edge_cmap is not None:
  446. assert(isinstance(edge_cmap, Colormap))
  447. edge_collection.set_array(numpy.asarray(edge_color))
  448. edge_collection.set_cmap(edge_cmap)
  449. if edge_vmin is not None or edge_vmax is not None:
  450. edge_collection.set_clim(edge_vmin, edge_vmax)
  451. else:
  452. edge_collection.autoscale()
  453. arrow_collection = None
  454. if G.is_directed() and arrows:
  455. # a directed graph hack
  456. # draw thick line segments at head end of edge
  457. # waiting for someone else to implement arrows that will work
  458. arrow_colors = edge_colors
  459. a_pos = []
  460. p = 1.0-0.25 # make head segment 25 percent of edge length
  461. for src, dst in edge_pos:
  462. x1, y1 = src
  463. x2, y2 = dst
  464. dx = x2-x1 # x offset
  465. dy = y2-y1 # y offset
  466. d = numpy.sqrt(float(dx**2 + dy**2)) # length of edge
  467. if d == 0: # source and target at same position
  468. continue
  469. if dx == 0: # vertical edge
  470. xa = x2
  471. ya = dy*p+y1
  472. if dy == 0: # horizontal edge
  473. ya = y2
  474. xa = dx*p+x1
  475. else:
  476. theta = numpy.arctan2(dy, dx)
  477. xa = p*d*numpy.cos(theta)+x1
  478. ya = p*d*numpy.sin(theta)+y1
  479. a_pos.append(((xa, ya), (x2, y2)))
  480. arrow_collection = LineCollection(a_pos,
  481. colors=arrow_colors,
  482. linewidths=[4*ww for ww in lw],
  483. antialiaseds=(1,),
  484. transOffset = ax.transData,
  485. )
  486. arrow_collection.set_zorder(1) # edges go behind nodes
  487. arrow_collection.set_label(label)
  488. ax.add_collection(arrow_collection)
  489. # update view
  490. minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))
  491. maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0]))
  492. miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1]))
  493. maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1]))
  494. w = maxx-minx
  495. h = maxy-miny
  496. padx, pady = 0.05*w, 0.05*h
  497. corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
  498. ax.update_datalim(corners)
  499. ax.autoscale_view()
  500. # if arrow_collection:
  501. return edge_collection
  502. def draw_networkx_labels(G, pos,
  503. labels=None,
  504. font_size=12,
  505. font_color='k',
  506. font_family='sans-serif',
  507. font_weight='normal',
  508. alpha=1.0,
  509. ax=None,
  510. **kwds):
  511. """Draw node labels on the graph G.
  512. Parameters
  513. ----------
  514. G : graph
  515. A networkx graph
  516. pos : dictionary
  517. A dictionary with nodes as keys and positions as values.
  518. Positions should be sequences of length 2.
  519. labels : dictionary, optional (default=None)
  520. Node labels in a dictionary keyed by node of text labels
  521. font_size : int
  522. Font size for text labels (default=12)
  523. font_color : string
  524. Font color string (default='k' black)
  525. font_family : string
  526. Font family (default='sans-serif')
  527. font_weight : string
  528. Font weight (default='normal')
  529. alpha : float
  530. The text transparency (default=1.0)
  531. ax : Matplotlib Axes object, optional
  532. Draw the graph in the specified Matplotlib axes.
  533. Returns
  534. -------
  535. dict
  536. `dict` of labels keyed on the nodes
  537. Examples
  538. --------
  539. >>> G=nx.dodecahedral_graph()
  540. >>> labels=nx.draw_networkx_labels(G,pos=nx.spring_layout(G))
  541. Also see the NetworkX drawing examples at
  542. http://networkx.lanl.gov/gallery.html
  543. See Also
  544. --------
  545. draw()
  546. draw_networkx()
  547. draw_networkx_nodes()
  548. draw_networkx_edges()
  549. draw_networkx_edge_labels()
  550. """
  551. try:
  552. import matplotlib.pyplot as plt
  553. import matplotlib.cbook as cb
  554. except ImportError:
  555. raise ImportError("Matplotlib required for draw()")
  556. except RuntimeError:
  557. print("Matplotlib unable to open display")
  558. raise
  559. if ax is None:
  560. ax = plt.gca()
  561. if labels is None:
  562. labels = dict((n, n) for n in G.nodes())
  563. # set optional alignment
  564. horizontalalignment = kwds.get('horizontalalignment', 'center')
  565. verticalalignment = kwds.get('verticalalignment', 'center')
  566. text_items = {} # there is no text collection so we'll fake one
  567. for n, label in labels.items():
  568. (x, y) = pos[n]
  569. if not cb.is_string_like(label):
  570. label = str(label) # this will cause "1" and 1 to be labeled the same
  571. t = ax.text(x, y,
  572. label,
  573. size=font_size,
  574. color=font_color,
  575. family=font_family,
  576. weight=font_weight,
  577. horizontalalignment=horizontalalignment,
  578. verticalalignment=verticalalignment,
  579. transform=ax.transData,
  580. clip_on=True,
  581. )
  582. text_items[n] = t
  583. return text_items
  584. def draw_networkx_edge_labels(G, pos,
  585. edge_labels=None,
  586. label_pos=0.5,
  587. font_size=10,
  588. font_color='k',
  589. font_family='sans-serif',
  590. font_weight='normal',
  591. alpha=1.0,
  592. bbox=None,
  593. ax=None,
  594. rotate=True,
  595. **kwds):
  596. """Draw edge labels.
  597. Parameters
  598. ----------
  599. G : graph
  600. A networkx graph
  601. pos : dictionary
  602. A dictionary with nodes as keys and positions as values.
  603. Positions should be sequences of length 2.
  604. ax : Matplotlib Axes object, optional
  605. Draw the graph in the specified Matplotlib axes.
  606. alpha : float
  607. The text transparency (default=1.0)
  608. edge_labels : dictionary
  609. Edge labels in a dictionary keyed by edge two-tuple of text
  610. labels (default=None). Only labels for the keys in the dictionary
  611. are drawn.
  612. label_pos : float
  613. Position of edge label along edge (0=head, 0.5=center, 1=tail)
  614. font_size : int
  615. Font size for text labels (default=12)
  616. font_color : string
  617. Font color string (default='k' black)
  618. font_weight : string
  619. Font weight (default='normal')
  620. font_family : string
  621. Font family (default='sans-serif')
  622. bbox : Matplotlib bbox
  623. Specify text box shape and colors.
  624. clip_on : bool
  625. Turn on clipping at axis boundaries (default=True)
  626. Returns
  627. -------
  628. dict
  629. `dict` of labels keyed on the edges
  630. Examples
  631. --------
  632. >>> G=nx.dodecahedral_graph()
  633. >>> edge_labels=nx.draw_networkx_edge_labels(G,pos=nx.spring_layout(G))
  634. Also see the NetworkX drawing examples at
  635. http://networkx.lanl.gov/gallery.html
  636. See Also
  637. --------
  638. draw()
  639. draw_networkx()
  640. draw_networkx_nodes()
  641. draw_networkx_edges()
  642. draw_networkx_labels()
  643. """
  644. try:
  645. import matplotlib.pyplot as plt
  646. import matplotlib.cbook as cb
  647. import numpy
  648. except ImportError:
  649. raise ImportError("Matplotlib required for draw()")
  650. except RuntimeError:
  651. print("Matplotlib unable to open display")
  652. raise
  653. if ax is None:
  654. ax = plt.gca()
  655. if edge_labels is None:
  656. labels = dict(((u, v), d) for u, v, d in G.edges(data=True))
  657. else:
  658. labels = edge_labels
  659. text_items = {}
  660. for (n1, n2), label in labels.items():
  661. (x1, y1) = pos[n1]
  662. (x2, y2) = pos[n2]
  663. (x, y) = (x1 * label_pos + x2 * (1.0 - label_pos),
  664. y1 * label_pos + y2 * (1.0 - label_pos))
  665. if rotate:
  666. angle = numpy.arctan2(y2-y1, x2-x1)/(2.0*numpy.pi)*360 # degrees
  667. # make label orientation "right-side-up"
  668. if angle > 90:
  669. angle -= 180
  670. if angle < - 90:
  671. angle += 180
  672. # transform data coordinate angle to screen coordinate angle
  673. xy = numpy.array((x, y))
  674. trans_angle = ax.transData.transform_angles(numpy.array((angle,)),
  675. xy.reshape((1, 2)))[0]
  676. else:
  677. trans_angle = 0.0
  678. # use default box of white with white border
  679. if bbox is None:
  680. bbox = dict(boxstyle='round',
  681. ec=(1.0, 1.0, 1.0),
  682. fc=(1.0, 1.0, 1.0),
  683. )
  684. if not cb.is_string_like(label):
  685. label = str(label) # this will cause "1" and 1 to be labeled the same
  686. # set optional alignment
  687. horizontalalignment = kwds.get('horizontalalignment', 'center')
  688. verticalalignment = kwds.get('verticalalignment', 'center')
  689. t = ax.text(x, y,
  690. label,
  691. size=font_size,
  692. color=font_color,
  693. family=font_family,
  694. weight=font_weight,
  695. horizontalalignment=horizontalalignment,
  696. verticalalignment=verticalalignment,
  697. rotation=trans_angle,
  698. transform=ax.transData,
  699. bbox=bbox,
  700. zorder=1,
  701. clip_on=True,
  702. )
  703. text_items[(n1, n2)] = t
  704. return text_items
  705. def draw_circular(G, **kwargs):
  706. """Draw the graph G with a circular layout.
  707. Parameters
  708. ----------
  709. G : graph
  710. A networkx graph
  711. **kwargs : optional keywords
  712. See networkx.draw_networkx() for a description of optional keywords,
  713. with the exception of the pos parameter which is not used by this
  714. function.
  715. """
  716. draw(G, circular_layout(G), **kwargs)
  717. def draw_random(G, **kwargs):
  718. """Draw the graph G with a random layout.
  719. Parameters
  720. ----------
  721. G : graph
  722. A networkx graph
  723. **kwargs : optional keywords
  724. See networkx.draw_networkx() for a description of optional keywords,
  725. with the exception of the pos parameter which is not used by this
  726. function.
  727. """
  728. draw(G, random_layout(G), **kwargs)
  729. def draw_spectral(G, **kwargs):
  730. """Draw the graph G with a spectral layout.
  731. Parameters
  732. ----------
  733. G : graph
  734. A networkx graph
  735. **kwargs : optional keywords
  736. See networkx.draw_networkx() for a description of optional keywords,
  737. with the exception of the pos parameter which is not used by this
  738. function.
  739. """
  740. draw(G, spectral_layout(G), **kwargs)
  741. def draw_spring(G, **kwargs):
  742. """Draw the graph G with a spring layout.
  743. Parameters
  744. ----------
  745. G : graph
  746. A networkx graph
  747. **kwargs : optional keywords
  748. See networkx.draw_networkx() for a description of optional keywords,
  749. with the exception of the pos parameter which is not used by this
  750. function.
  751. """
  752. draw(G, spring_layout(G), **kwargs)
  753. def draw_shell(G, **kwargs):
  754. """Draw networkx graph with shell layout.
  755. Parameters
  756. ----------
  757. G : graph
  758. A networkx graph
  759. **kwargs : optional keywords
  760. See networkx.draw_networkx() for a description of optional keywords,
  761. with the exception of the pos parameter which is not used by this
  762. function.
  763. """
  764. nlist = kwargs.get('nlist', None)
  765. if nlist is not None:
  766. del(kwargs['nlist'])
  767. draw(G, shell_layout(G, nlist=nlist), **kwargs)
  768. def draw_graphviz(G, prog="neato", **kwargs):
  769. from nx_agraph import graphviz_layout
  770. """Draw networkx graph with graphviz layout.
  771. Parameters
  772. ----------
  773. G : graph
  774. A networkx graph
  775. prog : string, optional
  776. Name of Graphviz layout program
  777. **kwargs : optional keywords
  778. See networkx.draw_networkx() for a description of optional keywords.
  779. """
  780. # pos = nx.drawing.graphviz_layout(G, prog)
  781. pos=graphviz_layout(G, prog)
  782. draw(G, pos, **kwargs)
  783. def draw_nx(G, pos, **kwds):
  784. """For backward compatibility; use draw or draw_networkx."""
  785. draw(G, pos, **kwds)
  786. # fixture for nose tests
  787. def setup_module(module):
  788. from nose import SkipTest
  789. try:
  790. import matplotlib as mpl
  791. mpl.use('PS', warn=False)
  792. import matplotlib.pyplot as plt
  793. except:
  794. 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


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/637690
推荐阅读
相关标签
  

闽ICP备14008679号