2016-11-23 3 views
0

Ich habe Hinzufügen ein JSON-Objekt, das ich mit NetworkX gemacht:Knotenelemente zu JSON-Objekt in Python von NetworkX

json_data = json_graph.node_link_data(network_object) 

Es ist wie folgt (Mini-Version meiner Ausgabe) strukturiert:

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

Was ich tun möchte, ist folgende Elemente zu jedem der Knoten hinzuzufügen, so dass ich diese Daten als Eingang für sigma.js verwenden können:

„x“: 0,
"y": 0,
"Größe": 3
"Zentralität": 0

Ich kann nicht scheinen, um eine effiziente Art und Weise zu finden, diese add_node() allerdings mit zu tun. Gibt es eine offensichtliche Möglichkeit, das hinzuzufügen, was ich vermisse?

Antwort

2

Während Sie Ihre Daten als Netzwerkx-Diagramm haben, können Sie die set_node_attributes-Methode verwenden, um allen Knoten im Diagramm die Attribute hinzuzufügen (z. B. in einem Python-Wörterbuch gespeichert).

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

Sie können dann mit node_link_data die neue Grafik in JSON exportieren:

In meinem Beispiel werden die neuen Attribute im Wörterbuch attr gespeichert.

Verwandte Themen