如何为NetworkX节点同时设置颜色与透明度?
解决NetworkX节点同时设置颜色和透明度的问题
错误原因
你之前的写法将颜色和透明度放在列表中传给node_color,但NetworkX的node_color参数不支持这种格式——它仅接受单一颜色值(如颜色名称字符串、RGB/RGBA元组)或用于颜色映射的数值序列,因此触发了ValueError。
解决方案
以下两种方法可以实现不同节点的颜色+差异化透明度设置:
方法1:使用RGBA颜色元组
将颜色转换为包含alpha通道的RGBA元组,直接传给node_color:
import matplotlib.colors as mcolors # 构建带透明度的颜色列表 color_map = [] for node_name in G.nodes: if node_name[:4] == "red_": # 把命名颜色转为RGB,添加alpha=0.5 rgb = mcolors.to_rgb("olive") color_map.append(rgb + (0.5,)) else: rgb = mcolors.to_rgb("yellow") color_map.append(rgb + (1.0,)) # 绘制图形 nx.draw( G, nx.get_node_attributes(G, "pos"), with_labels=True, node_size=160, font_size=6, width=0.2, node_color=color_map, edge_color=edge_color_map, )
方法2:分组绘制节点
将节点按条件分组,分别调用nx.draw_networkx_nodes设置不同的颜色和透明度,最后补充绘制边和标签:
# 按节点名称分组 red_nodes = [n for n in G.nodes if n[:4] == "red_"] other_nodes = [n for n in G.nodes if n[:4] != "red_"] # 绘制不透明的黄色节点 nx.draw_networkx_nodes( G, nx.get_node_attributes(G, "pos"), nodelist=other_nodes, node_color="yellow", node_size=160, alpha=1.0 ) # 绘制半透明的橄榄绿节点 nx.draw_networkx_nodes( G, nx.get_node_attributes(G, "pos"), nodelist=red_nodes, node_color="olive", node_size=160, alpha=0.5 ) # 补充绘制边和标签 nx.draw_networkx_edges(G, nx.get_node_attributes(G, "pos"), width=0.2, edge_color=edge_color_map) nx.draw_networkx_labels(G, nx.get_node_attributes(G, "pos"), font_size=6)
内容的提问来源于stack exchange,提问作者a.t.
相关产品推荐
相关产品推荐

