4
votes

I'm using networkx to create a diGraph object, populate it with nodes and edges (including several characteristics), and then write a gefx file that I'm visualising with Gephi.

import networkx as nx
dg = nx.DiGraph()
dg.add_node(attribute1, 2, etc...)
dg.add_edge(attribute1, 2, etc...)
nx.write_gexf("output.gexf")

This process works perfectly. Now I need to assign locations to the nodes. I have seen that networkx can somehow do it (http://networkx.github.com/documentation/latest/examples/drawing/house_with_colors.html) and also I know there is a viz tag for gexf files (http://gexf.net/format/viz.html). I have a dictionary with the nodes names and their coordinates. Any idea to put all this together?

My option until now is to read the gexf file already generated, look for the nodes and create the viz:position tag.

However, it isn't very effective and I would like to somehow do it directly when adding the nodes.

1

1 Answers

7
votes

The node data is available as a Python dictionary for each node. Here is an example showing how the GEXF node viz data is stored and manipulated.

In [1]: import sys

In [2]: import urllib2

In [3]: import networkx as nx

In [4]: data = urllib2.urlopen('http://gexf.net/data/viz.gexf')

In [5]: G = nx.read_gexf(data)

In [6]: print G.node['a']
{'viz': {'color': {'a': 0.6, 'r': 239, 'b': 66, 'g': 173}, 'position': {'y': 40.109245, 'x': 15.783598, 'z': 0.0}, 'size': 2.0375757}, 'label': 'glossy'}

In [7]: G.node['a']['viz']['position']['x']=10

In [8]: G.node['a']['viz']['position']['y']=20

In [9]: print G.node['a']
{'viz': {'color': {'a': 0.6, 'r': 239, 'b': 66, 'g': 173}, 'position': {'y': 20, 'x': 10, 'z': 0.0}, 'size': 2.0375757}, 'label': 'glossy'}

In [10]: nx.write_gexf(G,sys.stdout)
<?xml version="1.0" encoding="utf-8"?><gexf xmlns:ns0="http://www.gexf.net/1.1draft/viz" version="1.1" xmlns="http://www.gexf.net/1.1draft" xmlns:viz="http://www.gexf.net/1.1draft/viz" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance">
  <graph defaultedgetype="undirected" mode="static">
    <nodes>
      <node id="a" label="glossy">
        <ns0:color b="66" g="173" r="239" />
        <ns0:size value="2.0375757" />
        <ns0:position x="10" y="20" z="0.0" />
      </node>
    </nodes>
    <edges />
  </graph>
</gexf>