2017-02-16 1207 views
0

在一個簡單的圖表所示:NetworkX:如何將節點座標指定爲屬性?

import networkx as nx 
import matplotlib.pyplot as plt 

G = nx.Graph() 
G.add_edge('0','1') 
G.add_edge('1','2') 
G.add_edge('2','0') 
G.add_edge('0','3') 
G.add_edge('1','4') 
G.add_edge('5','0') 

pos={'0':(1,0),'1':(1,1),'2':(2,3),'3':(3,2),'4':(0.76,1.80),'5':(0,2)} #node:(x,y) 
nx.draw(G,pos=pos,with_labels=True) 
plt.show() 

如果我嘗試給每個節點分配包含節點ID及其(x,y)屬性的座標列表如下:

for i,n in enumerate(G.nodes()): 
    G.nodes()[i]['weight']=[G.nodes()[i],pos[n]] #List of attributes 

我得到以下錯誤:

Traceback (most recent call last): 

    File "<ipython-input-47-0f9ca94eeefd>", line 2, in <module> 
    G.nodes()[i]['weight']=[G.nodes()[i],pos[n]] 

TypeError: 'str' object does not support item assignment 

這裏有什麼問題?

回答

2

經過一番研究,我發現答案在nx.set_node_attributes()

當然,可以分配節點位置作爲屬性:

pos={'0':(1,0),'1':(1,1),'2':(2,3),'3':(3,2),'4':(0.76,1.80),'5':(0,2)}  
nx.set_node_attributes(G, 'coord', pos) 

這導致

In[1]: G.nodes(data=True) 
Out[1]: 
[('1', {'coord': (1, 1)}), #each node has its own position 
('0', {'coord': (1, 0)}), 
('3', {'coord': (3, 2)}), 
('2', {'coord': (2, 3)}), 
('5', {'coord': (0, 2)}), 
('4', {'coord': (0.76, 1.8)})] 

並且,也可以附加使用專用詞典(多個屬性在這種情況下(例如,可以存在節點而不具有屬性):

test={'0':55,'1':43,'2':17,'3':86,'4':2} #node '5' is missing 
nx.set_node_attributes(G, 'test', test) 

這導致

In[2]: G.nodes(data=True) 
Out[2]: 
[('1', {'coord': (1, 1), 'test': 43}), 
('0', {'coord': (1, 0), 'test': 55}), 
('3', {'coord': (3, 2), 'test': 86}), 
('2', {'coord': (2, 3), 'test': 17}), 
('5', {'coord': (0, 2)}), 
('4', {'coord': (0.76, 1.8), 'test': 2})] 

我推測相同是可能的圖形的邊緣,使用nx.set_edge_attributes()

+0

如何知道由其創建的節點座標並保存在稍後用於另一個圖形中? – Sigur

+0

@Sigur這個例子中的節點座標是組成的。這取決於您嘗試解決的問題,但您可以將節點分配給您想要的座標 - 您決定!這些可以存儲在字典中,然後可以保存爲[pickle](https://docs.python.org/3/library/pickle.html)。這可以讓你導入和解壓你的pickle,所以你可以稍後在另一個圖表中使用它。我希望這有幫助。如果你有更具體的問題,請提出一個新的問題,並提供所有的細節。 – FaCoffee

+0

讓我稍微搜索一下。或多或少,我想要的是一系列具有相同頂點設置但邊緣根據某些參數出現的圖形。但是頂點集合的位置首先是由一些佈局創建的,然後是其他圖形我想使用相同的佈局。但是每次運行代碼時,圖形都會改變! – Sigur