networkx draw tripartite graph 1

networkx draw tripartite graph

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,)

Here is what the above code is Doing:
1. Create a bipartite graph with 3 nodes in the first set and 5 nodes in the second set.
2. Create a list of edges between the first set and the second set.
3. Create a list of edges between the second set and the third set.
4. Add the edges to the graph.
5. Create a set of nodes for each of the three sets.
6. Create a dictionary of positions for each of the nodes.
7. Draw the graph.

Similar Posts