NetworkX:如何将节点坐标分配为属性? [英] NetworkX: how to assign the node coordinates as attribute?

查看:617
本文介绍了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)坐标的属性列表,如下所示:

if I try to assign each node a list of attributes containing the node ID and its (x,y) coordinates like this:

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()中.

After a bit of research I've figured out that the answer is in nx.set_node_attributes().

当然可以将节点位置分配为属性:

It is of course possible to assign the node positions as 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中的节点相同数量的元素(例如,可以有节点没有属性):

and it is also possible to attach multiple attributes using dedicated dictionaries (in this case test) that don't have to have the same number of elements as the nodes in G (e.g., there can be nodes without attributes):

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})]

我推测使用

I am speculating that the same is possible with the graph edges, using nx.set_edge_attributes().

这篇关于NetworkX:如何将节点坐标分配为属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆