ahmad
ahmad

Reputation: 73

How to draw a bipartite graph

if i want to simulate my network like this picture but Bipartite = 4 and increase my nodes to 600 node (n=150 l =150 s=150 and m=150) and also have 685 edges randomly...how can write simulation coding to make this network? can anyone help me ? enter code herethank you so much for your attention

also this picture coding here

enter image description here

import networkx as nx
import matplotlib.pyplot as plt
import random
from networkx.algorithms import bipartite
B = nx.Graph()
n = [1,2,3,4]
l = [*'abc']
B.add_nodes_from(n, bipartite=0)
B.add_nodes_from(l, bipartite=1)
B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(n) ) 
pos.update( (n, (2, i)) for i, n in enumerate(l) ) 

nx.draw_networkx(B, pos=pos)
nx.draw_networkx_nodes(B, pos=pos, nodelist=n)

plt.axis('off')
plt.show()

Upvotes: 3

Views: 1318

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23101

You want to draw a 4-partite graph. You can generalize your code above to draw a k-partite graph, where k=4 here, as shown below, using the following code (you can change the node color, type and font color if you want).

B = nx.Graph()

nodes = {}
k = 4
n = 150
ne = 685
e = 229 # since you want total 685 edges, you can have ~229 edges in between two 
        # adjacent sets of nodes

for i in range(k):
    nodes[i] = list(range(n*i, n*(i+1)))

for i in range(k):
    B.add_nodes_from(nodes[i], bipartite=k)

edges = []
for j in range(k-1):
    for i in range(e):
        edges.append((random.choice(nodes[j]), random.choice(nodes[j+1])))

B.add_edges_from(edges[:ne])

pos = dict()
for j in range(k):
    pos.update( (n, (j, i)) for i, n in enumerate(nodes[j]) ) 

plt.figure(figsize=(20,40))
nx.draw_networkx(B, pos=pos)

plt.axis('off')
plt.show() 

enter image description here

Upvotes: 2

Related Questions