Search code examples
xmljsond3.jsgraphmlforce-layout

using a graphml file for d3.js force-directed layout


How do I use a graphml file with d3.js ? [i would like to draw a force-directed graph]

  • is it simpler to convert the file to .json ? How ? I haven't been able to find a converter (I have found a python converter, but I'm not a python user)

  • is it possible to directly use the graphml file ? may be with d3.xml ?

Note : The graphml looks like this

<graph id="G" edgedefault="directed">
<node id="n0">
  <data key="v_name">JohnMaynardKe...</data>
  <data key="v_label">John Maynard Ke...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<node id="n1">
  <data key="v_name">JosephA.Schum...</data>
  <data key="v_label">Joseph A. Schum...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<edge source="n0" target="n1">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>
<edge source="n0" target="n7">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>

....


Solution

  • I will recommend that you convert your graphml file in a json file. I ran into the same issue and here's how I convert a graphml file in json using python and the networkx library:

    import networkx as nx
    import json
    from networkx.readwrite import json_graph
    import re
    
    G=nx.read_graphml('YourFile.graphml', unicode)
    data = json_graph.node_link_data(G)
    
    for node in data['nodes']:
      str=node['id']
      node['id']=[int(s) for s in str.split("n") if s.isdigit()][0]
    
    with open('YourFile.json', 'w') as f:
      json.dump(data, f, indent=4)
    

    The for loop in the code converts your node ids into numbers. This is very important since the sources and target in the json final file are already numbers (not characters).