在下面的代码中,我根据顶点着色规则为节点分配了颜色(作为数字值,而不是颜色名称)。随后,我绘制图表并显示颜色。最后,我将相关的数字颜色打印到节点。然而,我想要实际打印的颜色的“名称”,是显示在情节中。如何将颜色编号转换为颜色名称?
为节点分配颜色
%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对顶点进行着色
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)输出:

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)
发布于 2020-11-30 20:05:54
首先,你解决了这个问题,只是修改了一行,在你声明颜色的时候。
colors = set(range(num_colors))改到这一行
colors = {'red', 'blue', 'green'}我想这不是你想要的,因为你可能想要得到颜色的“人”(用某种方式来说)表示,或者这种颜色的RGB。但是我发现的问题是,当我们使用nx.draw来表示节点并传递给它nodes_color参数时,内部它使用matplotlib.scatter。请阅读文档中的以下内容:
node_color (颜色或颜色数组(默认值=‘1f78b4’)-节点颜色。可以是单一颜色,也可以是与节点列表长度相同的一系列颜色。颜色可以是字符串,或者rgb (或rgba)从0到1浮动的元组.如果指定了数值,则将使用cmap和vmin、vmax参数将它们映射到颜色。有关更多细节,请参见matplotlib.scatter .
因此,以我所知的一种方式,networkx使用将数字值转换为颜色。
所以我只看到两个选项,一个是像我前面说的那样显式地声明颜色,另一个是matplotlib.scatter是如何进行转换的。
https://stackoverflow.com/questions/65040140
复制相似问题