Skip to content

Instantly share code, notes, and snippets.

@j6k4m8
Forked from anderser/convert.py
Last active October 26, 2016 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j6k4m8/7349fc36476f0b486b489b5a14a03052 to your computer and use it in GitHub Desktop.
Save j6k4m8/7349fc36476f0b486b489b5a14a03052 to your computer and use it in GitHub Desktop.
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 convert.py -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.
Usage:
>>> python convert.py -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")
fo.write(json);
fo.close()
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)
@charan223
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