2015-03-24 39 views
-1

我有一個關於圖表的問題。我有30個節點(點)。我想以這樣一種方式構造一個鄰接矩陣,即每十個節點集合就像一個三角形的頂點。因此,假設一組10個節點位於三角形ABC的頂點A,B和C.在python中使用networkx創建固定節點集

兩個頂點集應該只有10個邊(基本上每個集羣內的每個節點都連接到另一個邊)。可以說,A和B組中的組有10個邊。第三個頂點集應該有11個邊(每個節點10個,一個節點連接兩個節點,因此該組中有11個邊)。可以說C中的一個有11個邊。

所有這三個集羣之間將有一條邊形成一個三角形。即A連接組與B連接組,一條邊連接B,C連接一條邊,C連接A連接一條邊。

稍後我會在B和C之間再增加一條邊。在附圖中用虛線表示。只要它們代表一個組,它就可以是一個圓或任何其他形式。

如何爲這樣的事情創建一個鄰接矩陣。我實際上知道如何爲這樣的矩陣創建鄰接矩陣,因爲它只是二元對稱矩陣(無向圖),但問題是當我嘗試繪製該鄰接矩陣時,它會將來自其他組的一個節點靠近該組哪個節點連接。因此,假設我通過連接兩個邊之間的邊來連接頂點A上的一個節點和頂點B上的一個節點。該邊緣將描繪三角形的邊AB。但是當我使用networkx描述它時,那些從這兩個不同組連接起來的兩個節點最終會靠近並看起來像是一個組的一部分。我如何保持它作爲單獨的組。 ?

請注意我正在使用python的networkx lib幫助繪製鄰接矩陣。

enter image description here

編輯:

我嘗試使用下面的啓發後,代碼:

G=nx.Graph() 
# Creating three separate groups of nodes (10 nodes each) 
node_clusters = [range(1,11), range(11,21) , range(21,31)] 

# Adding edges between each set of nodes in each group. 
for x in node_clusters: 
    for y in x: 
     if(y!=x[-1]): 
      G.add_edge(y,y+1,len=2) 
     else: 
      G.add_edge(y,x[0],len=2) 
# Adding three inter group edges separately: 
for x in range(len(node_clusters)): 
    if(x<2): 
     G.add_edge(node_clusters[x][-1],node_clusters[x+1][0],len=8) 
    else: 
     G.add_edge(node_clusters[x][-1],node_clusters[0][0],len=8) 

nx.draw_graphviz(G, prog='neato') 

提供了以下錯誤:

--> 260       '(not available for Python3)') 
    261  if root is not None: 
    262   args+="-Groot=%s"%root 

ImportError: ('requires pygraphviz ', 'http://networkx.lanl.gov/pygraphviz ', '(not available for Python3)') 

我的Python版本不3,它的2.我正在使用水蟒分佈

EDIT2:

我用馬呂斯的代碼,而是使用了以下繪製:

graph_pos=nx.spring_layout(G,k=0.20,iterations=50) 
nx.draw_networkx(G,graph_pos) 

它徹底摧毀了整個圖形。並顯示出這一點:

enter image description here

回答

2

我能夠只是在這個黑客客場得到的東西很快去,所有你需要做的就是把一起代表每個邊的元組,你還可以在設置一些任意長度邊緣得到一個體面的近似所需的佈局:

import networkx 
import string 

all_nodes = string.ascii_letters[:30] 
a_nodes = all_nodes[:10] 
b_nodes = all_nodes[10:20] 
c_nodes = all_nodes[20:] 

all_edges = [] 
for node_set in [a_nodes, b_nodes, c_nodes]: 
    # Link each node to the next 
    for i, node in enumerate(node_set[:-1]): 
     all_edges.append((node, node_set[i + 1], 2)) 
    # Finish off the circle 
    all_edges.append((node_set[0], node_set[-1], 2)) 

joins = [(a_nodes[0], b_nodes[0], 8), (b_nodes[-1], c_nodes[0], 8), (c_nodes[-1], a_nodes[-1], 8)] 

all_edges += joins 
# One extra edge for C: 
all_edges.append((c_nodes[0], c_nodes[5], 5)) 

G = networkx.Graph() 
for edge in all_edges: 
    G.add_edge(edge[0], edge[1], len=edge[2]) 

networkx.draw_graphviz(G, prog='neato') 

嘗試像networkx.to_numpy_matrix(G)如果再要導出爲鄰接矩陣。

enter image description here

+0

是否有可能將此作爲循環形式?每個頂點? – Baktaawar 2015-03-25 01:18:45

+0

如果你正在談論它如何繪製,你可以使用GraphViz,它有一些更好的佈局算法,例如, 'networkx.draw_graphviz(G,prog ='neato')'。你必須使用Python 2,Python 3中不存在「pygraphviz」。 – Marius 2015-03-25 01:24:33

+0

謝謝!在networkx中有一種方法給我這個G的鄰接矩陣嗎?二元對稱矩陣? – Baktaawar 2015-03-25 01:30:41