打印指定的图形颜色名称 - Networkx

Print Assigned Graph Color Name - Networkx

在下面的代码中,我根据顶点着色规则为节点分配了一种颜色(作为数值,而不是颜色名称)。随后,我绘制图形并显示颜色。最后,我将相关的数字颜色打印到节点。但是,我想实际打印图中显示的颜色的“名称”。如何将颜色编号转换为颜色名称?

  1. 根据顶点着色规则为节点分配颜色
%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# get the maximum vertex degree
max_deg = max(G.degree())
max_deg = max_deg[1]
print('maximum degree = {}'.format(max_deg))

# Create the set of possible colors.
num_colors = max_deg+1
colors = set(range(num_colors))

# We'll store the color of each node as an integer property called 'color'.  Start by initializing
# all the colors to -1 (meaning not yet colored)
for v in complete_graph.nodes():
    complete_graph.nodes[v]['color'] = -1
    
# loop over all nodes
for v in complete_graph.nodes():
    
    print('processing node {}'.format(v))
    
    # copy the possible colors
    possible = colors.copy()
    
    # find colors of neighbors
    nbrs = set([complete_graph.nodes[w]['color'] for w in complete_graph.neighbors(v) if complete_graph.nodes[w]['color']!= -1])
    
    # remove neighbor colors from the set of possible colors
    possible -= nbrs
    
    # pick a color for the current node
    c = next(iter(possible))
    
    print('  neighbor colors: ', nbrs)
    print('  possible colors: ', possible)
    print('  selected color:  ', c)
    
    #update the color
    complete_graph.nodes[v]['color'] = c

具有 9 个节点的完整图的示例输出(下面仅打印节点 0):

  processing node 0
  neighbor colors:  set()
  possible colors:  {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  selected color:   0
  1. 绘制完整的图形并根据分配的颜色编号为顶点着色
plt.figure(figsize=(5,5))
nx.draw(complete_graph,pos,node_color=[d['color'] for v,d in complete_graph.nodes(data=True)],width=2,cmap=plt.cm.Set3)

输出:

  1. 打印节点和相关颜色编号
print(complete_graph.nodes(data=True))
[(0, {'color': 0}), (1, {'color': 1}), (2, {'color': 2}), (3, {'color': 3}), (4, {'color': 4}), (5, {'color': 5}), (6, {'color': 6}), (7, {'color': 7}), (8, {'color': 8}), (9, {'color': 9})]

我希望它是:{'color': Green)

首先,您只需修改一行即可解决该问题,您可以在其中声明颜色。

colors = set(range(num_colors))

改为此行

colors = {'red', 'blue', 'green'}

我想这不是你想要的,因为你可能想要获得颜色的“人”(以某种方式说)表示或者可能是这种颜色的 RGB。但这是我发现的问题,当我们使用 nx.draw 表示节点,并向其传递 nodes_color 参数时,它在内部使用 matplotlib.scatter。从文档中阅读:

node_color (color or array of colors (default=’#1f78b4’)) – Node color. Can be a single color or a sequence of colors with the same length as nodelist. Color can be string, or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

因此,以我所不知道的方式,networkx 使用 matplotlib.scatter 将数值转换为颜色。

所以我只看到两个选项,一个你像我之前说的那样明确声明颜色,或者第二个你找出如何 matplotlib.scatter 进行转换。