networkx draw tripartite graph

35

import networkx as nx
import numpy as np

BG = nx.Graph()
source = ['s']
first = np.arange(3)
second = np.arange(3, 8)

BG.add_nodes_from(source, bipartite=0)
BG.add_nodes_from(first, bipartite=1)
BG.add_nodes_from(second, bipartite=2)
source_first_edges = []
first_second_edges = []

for f in first:
    source_first_edges.append(('s', f))
for s in second:
    for f in first:
        first_second_edges.append((f, s))

BG.add_edges_from(source_first_edges)
BG.add_edges_from(first_second_edges)

nodes = BG.nodes()
# for each of the parts create a set 
nodes_0  = set([n for n in nodes if  BG.nodes[n]['bipartite']==0])
nodes_1  = set([n for n in nodes if  BG.nodes[n]['bipartite']==1])
nodes_2  = set([n for n in nodes if  BG.nodes[n]['bipartite']==2])

# set the location of the nodes for each set
pos = dict()
pos.update( (n, (1, y)) for y, n in enumerate(nodes_0) ) # put nodes from X at x=1
pos.update( (n, (2, y)) for y, n in enumerate(nodes_1) ) # put nodes from Y at x=2
pos.update( (n, (3, y)) for y, n in enumerate(nodes_2) ) # put nodes from X at x=1
pos.update( (n, (4, y)) for y, n in enumerate(nodes_3) )

nx.draw_networkx(BG, pos=pos,)

Comments

Submit
0 Comments