Skip to content

Instantly share code, notes, and snippets.

Forked from anderser/
Last active October 26, 2016 14:11
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
import json
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

charan223 commented Oct 26, 2016

It is not supporting for my graphml file
still same error

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