You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python字典设置Networkx库中指定节点的颜色

你可以通过将颜色配置字典转换为和图节点顺序匹配的颜色列表,再传入nx.draw的node_color参数实现需求,修改后的完整代码如下:

import networkx as nx
import matplotlib.pyplot as plt

relation_list = [['A', 'B'],
                 ['A', 'C'],
                 ['B', 'D'],
                 ['C', 'E'],
                 ['D', 'F'],
                 ['E', 'D'],
                 ['C', 'E'],
                 ['B', 'D'],                 
                 ['C', 'F'],
                 ['A', 'E'],
                 ['B', 'C'],                 
                 ['B', 'F'],
                 ['D', 'A']]
analysis_graph = nx.from_edgelist(relation_list)
print(nx.info(analysis_graph))

# 自定义颜色映射字典,新增节点/颜色只需修改此处
color_config = {
    "red": ["A", "B", "C"],
    "green": ["D", "E"],
    "blue": ["F"]
}

# 生成节点-颜色对应查询表
node2color = {}
for color, nodes in color_config.items():
    for node in nodes:
        node2color[node] = color

# 按图节点顺序生成对应颜色列表
node_colors = [node2color[node] for node in analysis_graph.nodes()]

# 绘图时传入颜色列表
nx.draw(analysis_graph, with_labels=True, node_color=node_colors)
plt.show()

补充说明

  • 该逻辑完全适配大量节点的场景,即使节点数超过200,也只需要维护color_config这一个字典即可,不需要修改其他代码。
  • 如果你有部分节点不需要特殊配色,可以加默认颜色避免报错,将颜色列表生成逻辑改为:
# 未配置的节点默认显示灰色
node_colors = [node2color.get(node, "gray") for node in analysis_graph.nodes()]

内容的提问来源于stack exchange,提问作者taga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:27:02