Question

I am trying to export a graph file with some visualization specifications . I could not figure out how to add multi-level attributes .

Import networkx as nx
#Create the Graph 
g = nx.Graph()
g.add_edge('Andre',   'Beverly')
g.add_edge('Andre',   'Diane')
g.add_edge('Andre',   'Carol')
g.add_edge('Andre',   'Fernando')
g.add_edge('Beverly', 'Diane')
nx.draw(g)

Add attributes to the nodes

what I would like to do is to add position but using a specific attribute (names and structure)

# compute position 
pos = nx.spring_layout(g)

# add attribute 
g.node["Andre"]["viz"]["position"]["x"]= pos["Andre"][0]
g.node["Andre"]["viz"]["position"]["y"]= pos["Andre"][1]

this does not work

I have in fact two questions :

  1. how can I add a multi-level attributes
  2. Is there a way to do this in iterations (I could still write a function but I wonder if there is a way to do from networkx that I have not seen)

For Info : What I am really after, is a way to export network graph into a gexf file which I could open with gexf-js without passing by gephi.

P.S: I have this question and other related to this, but to my knowledge they do not address what I am after.

Was it helpful?

Solution

After you calculate the positions in spring_layout():

for node in g.nodes():
    g.node[node]["viz"] = {'position': {'x': pos[node][0],
                                        'y': pos[node][1]
                                        }
                           }

print g.nodes(data=True)

Results in:

[('Beverly',
  {'viz': {'position': {'x': 0.00089466691490215525,
     'y': 0.69872879243427066}}}),
 ('Andre',
  {'viz': {'position': {'x': 0.55837798068966304, 'y': 0.47862178288009244}}}),
 ('Carol', {'viz': {'position': {'x': 1.0, 'y': 0.95632397309056527}}}),
 ('Diane', {'viz': {'position': {'x': 0.0, 'y': 0.25644757276893704}}}),
 ('Fernando', {'viz': {'position': {'x': 0.9957995595107102, 'y': 0.0}}})]

And then you can work on getting nx.write_gexf(g, 'somefile.gexf') to work :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top