简体   繁体   中英

How to create Networkx graph with randomly assigned node labels?

I have a graph with a single label variable which takes 2 values. Every node in the graph is labeled either 'red' or 'blue'. I would like to generate 100 new graphs where the structure (ie. node and edge placement) is left the same but the node labels are randomly assigned such that there is the same amount of 'red' and 'blue' nodes in each graph. I am aware the term 'random' isn't appropriate here but I'm not sure how else to describe it.

For "random" labeling here, you just need to assign the labels, which you are adding to the graph, randomly each time like this:

import random 
import networkx as nx

G=nx.Graph()
for x in range(6):
  G.add_node(x)

for x in range(6):
  for y in range(6):
    G.add_edge(x,y)

pos=nx.spring_layout(G) 

nx.draw_networkx_nodes(G,pos,
                       nodelist=[x for x in range(6)],
                       node_color='r',
                       node_size=500,
                   alpha=0.8)

nx.draw_networkx_edges(G,pos,
                       edgelist=[(x,y) for x in range(6) for y in range(6)],
                       width=4,alpha=0.5,edge_color='b')

labels={}
# Iterate through all nodes
for x in range(len(G.nodes())):
  # Label node as either B or R until half of the nodes are labeled as either
  if(list(labels.values()).count('R') == len(G.nodes())/2):
    labels[x] = 'B'
  if(list(labels.values()).count('B') == len(G.nodes())/2):
    labels[x] = 'R'
  else:
    labels[x] = random.choice(['B', 'R'])


nx.draw_networkx_labels(G,pos,labels,font_size=16)

In the code it is assumed that the Graph has an even number of nodes, so that "the same number of "Red" ('R') and "Blue" ('B') nodes can be there.

For the labeling, a loop iterates through all the nodes and then randomly chooses between red or blue, until half of the nodes are assigned to either red or blue. Then it just assigns all the others with the other color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM