2015-05-18 40 views
1

我試圖用連接的組件表示一些數字作爲圖的邊。爲此,我一直在使用python的networkX模塊。
我的圖是G,並具有初始化節點和邊如下:矩陣對象沒有屬性節點networkX python

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) 

一旦我添加以下行,

pos = nx.spring_layout(adj_matrix) 

我得到上述錯誤。 如果它可能有用,所有節點的編號都是9-15位。有412個節點和422個邊緣。

詳細的出錯:

 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' 

編輯:下面解決。有用的信息:pos爲每個節點創建一個帶有座標的字典。做nx.draw(G,pos)創建一個pylab圖。但它不顯示它,因爲pylab不會自動顯示。

+0

不清楚你在這裏嘗試的是什麼['spring_layout'](https://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.layout.spring_layout.html)將圖形作爲第一個param,不是矩陣數組 – EdChum

+0

@EdChum:我不知道,謝謝。我如何才能讓圖形顯示出來? nx.draw(G)不會拋出任何錯誤,但它也不會出現。 – tvishwa107

+0

'sprint_layout'返回節點位置,您需要將此傳遞給'nx.draw',所以'nx.draw(G,nx.spring_layout(G))'會起作用,我可以發佈一個示例 – EdChum

回答

1

(一些這個答案在您的意見解決了一些東西,你可以添加這些到您的以便後來的用戶獲得更多的上下文)

pos創建一個帶有座標的字典爲每個節點添加一個。做nx.draw(G,pos)創建一個pylab圖。但它不顯示它,因爲pylab不會自動顯示。

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 

最後的py.show()會顯示出來。 py.savefig('filename.extension')將根據您用於extension的內容保存爲多個文件類型中的任意一種。

1

spring_layout需要一個網絡圖,因爲它是第一個參數,而不是一個numpy數組。它返回的是根據Fruchterman-Reingold力定向算法的節點位置。

所以,你需要這個傳遞給draw例如:

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

產量:

enter image description here

+0

我試過了,是否需要包含nx.lollipop_graph部分? 雖然沒有錯誤發生,但我的程序實際上並沒有顯示圖形。 編輯:有一次,我添加了一個節目 – tvishwa107

+0

棒棒糖圖只是一個圖形發生器,我不知道你想要構建什麼圖,但我認爲這將演示它如何工作以及它是如何顯示的。如果我的答案完全解決了您的問題,請接受它,答案左上角會出現一個空的勾號,謝謝 – EdChum