Search code examples
pythonjupyter-notebooknetworkxgraph-theorypygraphviz

AttributeError: 'DiGraph' object has no attribute 'number_of_selfloops'


I am trying to run graph drawing code in my pc via jupyter notebook. Networkx ,pygraphviz, and nxpd are installed in my pc.But I found AttributeError after running

draw(G, layout='circo')

How can I fix this problem? Error is in the description below:

AttributeError                            Traceback (most recent call last)
<ipython-input-2-d4524714330e> in <module>
----> 1 draw(G, layout='circo')

~/anaconda3/lib/python3.7/site-packages/nxpd/nx_pydot.py in draw_pydot(G, filename, format, prefix, suffix, layout, args, show)
    455 
    456     # Draw the image.
--> 457     G2 = to_pydot(G)
    458     G2.write(fobj, prog=prog, format=ext)
    459     if close:

~/anaconda3/lib/python3.7/site-packages/nxpd/nx_pydot.py in to_pydot(G, raise_exceptions)
    247         graph_type = 'graph'
    248 
--> 249     strict = G.number_of_selfloops() == 0 and not G.is_multigraph()
    250 
    251     # Create the Pydot graph.

AttributeError: 'DiGraph' object has no attribute 'number_of_selfloops'

The code is given below:

import networkx as nx
import pygraphviz as pgv
from nxpd import draw, nxpdParams
nxpdParams['show'] = 'ipynb'
G = nx.DiGraph()


G.add_edge("a", "b")
G.add_edge("b", "c")
G.add_edge("c", "d")
G.add_edge("d", "e")
G.add_edge("e", "c")
G.add_edge("a", "d")
draw(G, layout='circo')

Solution

  • The package nxpd seems like it was last updated years ago. You can modify the line by yourself (see https://github.com/chebee7i/nxpd/blob/master/nxpd/nx_pydot.py#L249) and exchange G.number_of_selfloops with nx.number_of_selfloops(G). However, I guess their are more issues with nxpd and I would recommend to simply use networkx own interface to graphviz, see e.g. graphviz_layout:

    pos = nx.nx_agraph.graphviz_layout(G, prog="circo")
    nx.draw(G, pos)