Skip to content

Instantly share code, notes, and snippets.

Last active March 18, 2023 23:30
What would you like to do?
Convert from NodeXL (via GraphML-format) to D3-ready json for force layout while adding modularity groups (communities) as attribute to nodes. Useful for coloring nodes via modularitygroup attribute. Requires networkx and python-louvain. First export as GraphML file from your NodeXL-sheet. Then run: >>> python -i mygraph.graphml -o ou…
#!/usr/bin/env python
import sys
import argparse
import networkx as nx
import community
from networkx.readwrite import json_graph
def graphmltojson(graphfile, outfile):
Converts GraphML file to json while adding communities/modularity groups
using python-louvain. JSON output is usable with D3 force layout.
>>> python -i mygraph.graphml -o outfile.json
G = nx.read_graphml(graphfile)
#finds best community using louvain
partition = community.best_partition(G)
#adds partition/community number as attribute named 'modularitygroup'
for n,d in G.nodes_iter(data=True):
d['modularitygroup'] = partition[n]
node_link = json_graph.node_link_data(G)
json = json_graph.dumps(node_link)
# Write to file
fo = open(outfile, "w")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert from GraphML to json. ')
parser.add_argument('-i','--input', help='Input file name (graphml)',required=True)
parser.add_argument('-o','--output', help='Output file name/path',required=True)
args = parser.parse_args()
graphmltojson(args.input, args.output)
Copy link

j6k4m8 commented Jun 15, 2016

Forked it here, was having trouble with the JSON dumper.

@Iam-jegan, go into your graphml file and change the <graph> tag from <graph id="blah" edgedefault="directed"> to just <graph id="blah"> (obviously replace with your graph's ID). That should fix it!

Copy link

unvaiso commented Jul 2, 2017

I got the following error:

Traceback (most recent call last):
  File "", line 40, in <module>
    graphmltojson(args.input, args.output)
  File "", line 21, in graphmltojson
    partition = community.best_partition(G)
  File "/home/djeb/.local/lib/python2.7/site-packages/community/", line 214, in best_partition
  File "/home/djeb/.local/lib/python2.7/site-packages/community/", line 293, in generate_dendrogram
    status.init(current_graph, weight, part_init)
  File "/home/djeb/.local/lib/python2.7/site-packages/community/", line 57, in init
    self.loops[node] = float(edge_data.get(weight, 1))
AttributeError: 'NoneType' object has no attribute 'get'

Any idea ? Thanks!

Copy link

Line 28: output AttributeError: module 'networkx.readwrite.json_graph' has no attribute 'dumps'
Solution: import json and use otherName_json = json.dumps(node_link) . and don't forget to change the new name on line 32.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment