簡體   English   中英

NetworkX:如何將節點坐標分配為屬性?

[英]NetworkX: how to assign the node coordinates as attribute?

在像這樣的簡單圖形中:

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

這里有什么問題?

經過一番研究,我發現答案在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, pos, 'coord')

這導致

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 )附加多個屬性,這些字典不必與G的節點具有相同數量的元素(例如,可以有沒有屬性的節點):

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()對圖形邊緣也有可能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM