使用 Python 字典设置 Networkx 节点的颜色

Setting the colour of Networkx nodes with Python dict

我想使用 Python 为 networkx 库中的特定节点设置颜色。 这些是我的节点:

node_list = ["A", "B", "C", "D", "E", "F"]

这些是我想要的颜色:

A->red
B->red
C->red
D->green
E->green
F->blue

我不知道该怎么做,因为有时我有 200 多个不同的节点,所以我正在寻找一些可以与 dict 一起使用的解决方案:

{"red":[A,B,C], "green": [D,E], "blue": [F]}

这是我的代码:

import networkx as nx

analysis_graph = nx.Graph()

node_list = ["A", "B", "C", "D", "E", "F"]

analysis_graph.add_nodes_from(node_list)
#print(analysis_graph.nodes())

nx.draw(analysis_graph, with_labels = True)
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))
nx.draw(analysis_graph, with_labels = True)

当然可以。根据 the docs nx.draw 支持 node_color 论点。您只需按正确的顺序明确列出节点:

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"],
]

colors = {"red": ["A", "B", "C"], "green": ["D", "E"], "blue": ["F"]}

analysis_graph = nx.from_edgelist(relation_list)


# Create a mapping of node -> color from `colors`:

node_color_map = {}
for color, nodes in colors.items():
    node_color_map.update(dict.fromkeys(nodes, color))

# Create a list of all the nodes to draw
node_list = sorted(nx.nodes(analysis_graph))
# ... and a list of colors in the proper order.
node_color_list = [node_color_map.get(node) for node in node_list]
# Draw the graph with the correct colors.
nx.draw(
    analysis_graph,
    with_labels=True,
    nodelist=node_list,
    node_color=node_color_list,
)

输出例如