简体   繁体   中英

Matrix object has no attribute nodes networkX python

I'm trying to represent some numbers as edges of a graph with connected components. For this, I've been using python's networkX module.
My graph is G, and has nodes and edges initialised as follows:

    G = nx.Graph()
    for (x,y) in my_set:
       G.add_edge(x,y)

    print G.nodes() #This prints all the nodes
    print G.edges() #Prints all the edges as tuples
    adj_matrix = nx.to_numpy_matrix(G)

Once I add the following line,

    pos = nx.spring_layout(adj_matrix)

I get the abovementioned error. If it might be useful, all the nodes are numbered in 9-15 digits. There are 412 nodes and 422 edges.

Detailed error:

      File "pyjson.py", line 89, in <module>
      mainevent()        
      File "pyjson.py", line 60, in mainevent
      pos = nx.spring_layout(adj_matrix)
      File "/usr/local/lib/python2.7/dist-packages/networkx/drawing/layout.py", line 244, in fruchterman_reingold_layout
      A=nx.to_numpy_matrix(G,weight=weight)
      File "/usr/local/lib/python2.7/dist-packages/networkx/convert_matrix.py", line 128, in to_numpy_matrix
      nodelist = G.nodes()
      AttributeError: 'matrix' object has no attribute 'nodes'

Edit: Solved below. Useful information: pos creates a dict with coordinates for each node. Doing nx.draw(G,pos) creates a pylab figure. But it doesn't display it, because pylab doesn't display automatically.

spring_layout takes a network graph as it's first param and not a numpy array. What it returns are the positions of the nodes according to the Fruchterman-Reingold force-directed algorithm.

So you need to pass this to draw example:

import networkx as nx
%matplotlib inline
G=nx.lollipop_graph(14, 3)
nx.draw(G,nx.spring_layout(G))

yields:

在此处输入图片说明

(some of this answer addresses some things in your comments. Can you add those to your question so that later users get some more context)

pos creates a dict with coordinates for each node. Doing nx.draw(G,pos) creates a pylab figure. But it doesn't display it, because pylab doesn't display automatically.

import networkx as nx
import pylab as py

G = nx.Graph()
for (x,y) in my_set:
   G.add_edge(x,y)

print G.nodes() #This prints all the nodes
print G.edges() #Prints all the edges as tuples
pos = nx.spring_layout(G)
nx.draw(G,pos)
py.show() # or py.savefig('graph.pdf') if you want to create a pdf, 
          # similarly for png or other file types

The final py.show() will display it. py.savefig('filename.extension') will save as any of a number of filetypes based on what you use for extension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM