简体   繁体   English

如何使用随机分配的节点标签创建 Networkx 图?

[英]How to create Networkx graph with randomly assigned node labels?

I have a graph with a single label variable which takes 2 values.我有一个带有 2 个值的单个标签变量的图。 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.我想生成 100 个新图,其中结构(即节点和边缘位置)保持不变,但节点标签是随机分配的,因此每个图中的“红色”和“蓝色”节点数量相同。 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.在代码中,假设 Graph 具有偶数个节点,因此可以存在“相同数量的“红色”('R')和“蓝色”('B')节点。

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.然后它只是将其他颜色分配给所有其他颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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