Skip to content

Instantly share code, notes, and snippets.

@wellington-tinho
Forked from anderser/convert.py
Last active May 6, 2021 17:35
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 wellington-tinho/842638ae3373eb5ccac3da263695c891 to your computer and use it in GitHub Desktop.
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…
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