-
-
Save wellington-tinho/842638ae3373eb5ccac3da263695c891 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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import argparse | |
import json | |
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. | |
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(data=True): | |
d['modularitygroup'] = partition[n] | |
node_link = json_graph.node_link_data(G) | |
arq_json = json.dumps(node_link) | |
# Write to file | |
fo = open(outfile, "w") | |
fo.write(arq_json) | |
fo.close() | |
graphmltojson('YouArchive.graphml', 'YouArchiveName.json') #Modification this line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment