Skip to content

Instantly share code, notes, and snippets.

@napsternxg
Created December 7, 2016 03:46
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 napsternxg/c2370ae38e6e4209721ca4371e91adfd to your computer and use it in GitHub Desktop.
Save napsternxg/c2370ae38e6e4209721ca4371e91adfd to your computer and use it in GitHub Desktop.
Read edgelist with attributes as igraph Graph and plot it with nodes labeled
#!/usr/bin/python
# -*- coding: utf-8 -*-
from igraph import *
def parse_string(x, max_len=100):
out = 'NONE'
try:
out = str(x.encode('ascii'))[:max_len]
except:
pass
return out
def read_file(
filename,
directed=True,
etype_names=None,
header=False,
):
edgelist = []
etypes = []
names = UniqueIdGenerator()
header_info = []
with open(filename) as fp:
data = fp.readlines()[0].split('\r')
for line in data:
line = line.strip().split(',')
if header:
header_info = line
header = False
continue
n1 = names[line[0]]
n2 = names[line[1]]
edgelist.append((n1, n2))
if etype_names is not None and len(line) \
== len(etype_names) + 2:
etypes.append(tuple(line[2:]))
g = Graph(edgelist, directed=directed)
g.vs['name'] = [names.reverse_dict()[vid.index] for vid in g.vs]
g.vs['label'] = [parse_string(v) for v in g.vs['name']]
if etype_names is not None:
for (k, v) in zip(etype_names, zip(*etypes)):
g.es[k] = v
return g
etype_names = ['Edge Type', 'weight', 'directed']
g = read_file('test.csv', etype_names=etype_names, directed=False,
header=True)
print g.summary()
## Plot the graph
layout = g.layout('reingold_tilford')
plot(g, layout=layout)
Source Targe Edge Type weight directed
abc bca parent 1 True
abc cab parent 1 True
bca cab sibling 0.5 True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment