tony9099
tony9099

Reputation: 4717

Create different disconnected graphs from a set of fixed nodes in NetworkX

I have the following set of nodes:

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Using networkx package, I want to create 4 random connected graphs where each contain 5 nodes from the above list in such a way that the label of the node should appear in the newly formed graph.

For example:

subgraph_1 = [1, 5, 9, 13, 17]

subgraph_2 = [2, 6, 10, 14, 18]

subgraph_3 = [3, 7, 11, 15, 19]

subgraph_4 = [4, 8, 12, 16, 20]

Is there a way to accomplish this using the built in packages functions of networkx? I could not locate anything in the documentation.

Another way that this could work is that, I can create a random graph with 20 nodes using: G=nx.erdos_renyi_graph(n=20,p=0.1) but then I would be needing to divide this into random 4 subgraphs with each one having 5 nodes. The edges can be regenerated randomly and do not have to be linked or similar to the edges of the main graph G.

Upvotes: 1

Views: 167

Answers (1)

jylls
jylls

Reputation: 4695

A way to do that that is by creating 4 random networks of size 5 using the nx.erdos_renyi_graph function. For each network, you can randomly pick without replacement 5 nodes from your vector n and relabel the nodes of the network with the random nodes.

See code below:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

N=20
n=np.arange(N)+1

#randomly permuting nodes
random_n=np.random.permutation(n)

N_graphs=4
N_nodes=5
#assign the random modes to each graph
random_graphs_nodes=[random_n[N_nodes*i:N_nodes*(i+1)] for i in range(N_graphs)]

#create random graphs
r_g=[nx.erdos_renyi_graph(n=N_nodes,p=0.5) for _ in range(N_graphs)]

#relabel the nodes in each graph according to random_graphs_nodes
mappings=[]
for i in range(N_graphs):
  mappings.append({j:str(random_graphs_nodes[i][j]) for j in range(N_nodes)})
  r_g[i]=nx.relabel_nodes(r_g[i], mappings[i]) 

#plot result
fig=plt.figure(figsize=(15,6))
colors=['tab:blue','tab:orange','tab:green','tab:pink']
for i in range(N_graphs):
  plt.subplot(1,4,i+1)
  plt.title('Graph '+str(i+1))
  pos=nx.circular_layout(r_g[i])
  nx.draw(r_g[i],pos=pos,with_labels=True,node_color=colors[i])

And the output gives:

enter image description here

Upvotes: 1

Related Questions