2016-11-23 80 views
0

添加节点元素JSON对象在Python我有使用networkx制成JSON对象:从NetworkX

json_data = json_graph.node_link_data(network_object) 

它的结构是这样的(我的输出的迷你版):

>>> json_data 

{'directed': False, 
'graph': {'name': 'compose(, )'}, 
'links': [{'source': 0, 'target': 7, 'weight': 1}, 
    {'source': 0, 'target': 2, 'weight': 1}, 
    {'source': 0, 'target': 12, 'weight': 1}, 
    {'source': 0, 'target': 9, 'weight': 1}, 
    {'source': 2, 'target': 18, 'weight': 25}, 
    {'source': 17, 'target': 25, 'weight': 1}, 
    {'source': 29, 'target': 18, 'weight': 1}, 
    {'source': 30, 'target': 18, 'weight': 1}], 
'multigraph': False, 
'nodes': [{'bipartite': 1, 'id': 'Icarus', 'node_type': 'Journal'}, 
    {'bipartite': 1, 
    'id': 'A Giant Step: from Milli- to Micro-arcsecond Astrometry', 
    'node_type': 'Journal'}, 
    {'bipartite': 1, 
    'id': 'The Astrophysical Journal Supplement Series', 
    'node_type': 'Journal'}, 
    {'bipartite': 1, 
    'id': 'Astronomy and Astrophysics Supplement Series', 
    'node_type': 'Journal'}, 
    {'bipartite': 1, 'id': 'Astronomy and Astrophysics', 'node_type': 'Journal'}, 
    {'bipartite': 1, 
    'id': 'Astronomy and Astrophysics Review', 
    'node_type': 'Journal'}]} 

我想要做的就是添加以下元素到每个节点的,所以我可以用这个数据作为输入sigma.js

“X”:0,
“Y”:0,
“大小”:3
“中心性”:0

我似乎无法找到一个有效的方式做到这一点,虽然使用add_node()。有没有一些明显的方式来补充我缺少的东西?

回答

2

将数据作为networkx图形使用时,可以使用set_node_attributes方法将属性(例如存储在Python字典中)添加到图形中的所有节点。

在我的例子,新属性被存储在字典中attr

import networkx as nx 
from networkx.readwrite import json_graph 

# example graph 
G = nx.Graph() 
G.add_nodes_from(["a", "b", "c", "d"]) 

# your data 
#G = json_graph.node_link_graph(json_data) 

# dictionary of new attributes 
attr = {"x": 0, 
     "y": 0, 
     "size": 3, 
     "centrality": 0} 

for name, value in attr.items(): 
    nx.set_node_attributes(G, name, value) 

# check new node attributes 
print(G.nodes(data=True)) 

然后,您可以导出JSON新的图形与node_link_data