【问题标题】:Setting node locations with a dictionary使用字典设置节点位置
【发布时间】:2020-07-12 15:42:58
【问题描述】:

我有一本包含以下数据的字典:

pos = {0: (1,1), 1: (2,2), 2: (3,2), 3: (4,3)}

然后,我尝试了以下代码:

import networkx as nx
G = nx.Graph()
G.add_nodes_from(pos)
#also G.add_nodes_from(pos.keys())
print(G.nodes(True))

给出:

>>>> [(0, {}), (1, {}), (2, {}), (3, {})]

如您所见,职位是空的。

但是如果我写了

G = nx.random_geometric_graph(5, 0.50)
print(G.nodes(True))

返回

[(0, {'pos': [0.895101164279736, 0.43929155577155976]}), (1, {'pos': [0.006064168598946429, 0.6044775286563574]}), (2, {'pos': [0.021659978032451344, 0.47877598747213523]}), (3, {'pos': [0.05130150282000934, 0.1137451989310001]}), (4, {'pos': [0.8734509206210705, 0.9839817045923323]})]

它是一个带有位置的图表。 我还尝试将“pos”更改为“pos2”:

pos2 = {0:{'pos': [1,1]}, 1: {'pos':[2,2]}, 2: {'pos':[3,2]}, 3: {'pos':[4,3]}}

我也尝试了其他相关问题的代码:

1) answer1

for n, p in pos.iteritems():
    X.node[n]['pos'] = p

2) answer2

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)

我必须多次将超过 1500 个节点添加到带有标签的图中,所以我不想使用“for”循环,我正在寻找有效的分配,而不是:

G2.add_node(1,pos=(1,0))

谁能找到方法?

【问题讨论】:

    标签: python-3.x pandas numpy graph networkx


    【解决方案1】:

    您可以通过function.set_node_attributes 一次性设置所有节点的position 属性,values 参数可以是结构为{node0: {'attr1': 20, 'attr2': 'nothing'}, node1: {'attr2': 3}} 的字典。因此在这个例子中你可以直接做:

    G = nx.Graph()
    G.add_nodes_from(pos)
    G.nodes(True)
    # NodeDataView({0: {}, 1: {}, 2: {}, 3: {}})
    

    现在我们可以直接将function.set_node_attributes 输入字典为:

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

    现在通过打印 NodeDataView 你会得到:

    G.nodes(True)
    # NodeDataView({0: {'pos': (1, 1)}, 1: {'pos': (2, 2)}, 2: {'pos': (3, 2)}, 3: {'pos': (4, 3)}})
    

    所以如果你要绘制图形,你可以在nx.drawpos参数中设置位置:

    nx.draw(G, node_color='lightblue', with_labels=True, pos=pos, node_size=500)
    

    【讨论】:

    • 什么nx.draw(G),它返回一个圆形图,也许是设置的位置,它不应该和nx.draw(G,pos)一样吗?
    • nx.draw(G) 将随机设置位置。你需要给它提供字典。我已经更新了@luis
    猜你喜欢
    • 2019-04-14
    • 2018-12-18
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多