networkx,他们是将字典用作 color_map for node_color 的方法吗?

networkx, is their a way to use a dictionary as color_map for node_color?

我的目标是改变我字典中每个节点的个性化颜色。

到目前为止我的代码是:

import matplotlib.pyplot as plt
import networkx as nx

def view_graph(graph, node_labels, edge_labels):
    '''
        Plots the graph
    '''
    pos = nx.spring_layout(graph)
    nx.draw(graph, pos, node_color=color_map)
    nx.draw_networkx_labels(graph, pos, labels=node_labels)
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
    plt.axis('off')
    plt.show()

index_to_name = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}
color_map2 = {1: "blue", 2: "green", 3: "blue", 4: "lightgreen", 5: "lightgreen", 6: "lightblue", 7: "lightblue"}
color_map = ["blue", "green", "blue", "lightgreen", "lightgreen", "lightblue", "lightblue"]

relation = {}
relation[(1, 4)] = "dad"
relation[(2, 4)] = "mom"
relation[(1, 5)] = "dad"
relation[(2, 5)] = "mom"
relation[(3, 6)] = "dad"
relation[(4, 6)] = "mom"
relation[(3, 7)] = "dad"
relation[(4, 7)] = "mom"

g = nx.from_edgelist(relation, nx.DiGraph())

view_graph(g, index_to_name, relation)

我的问题是,我不想使用 color_map 作为参数,因为它是一个列表,所以它不能让我对节点本身有太多的控制。我的目标是使用字典 color_map2 在颜色和节点本身之间建立唯一关系。

他们有办法做到这一点吗?

正如您所注意到的,networkx 本身不支持通过字典(而不是列表)指定参数。如果您愿意使用其他库,我编写并维护了 netgraph,这是一个仅用于网络可视化的库。 该项目最初是 networkx 绘图实用程序的一个分支,因此大多数参数都是相同的。然而,在 netgraph 中,几乎所有参数都可以通过字典(而不是列表)指定。 Netgraph 支持绘制 networkx Graph 对象,因此这两个包可以无缝地协同工作。

import matplotlib.pyplot as plt
import networkx as nx
from netgraph import Graph # pip install netgraph

node_labels = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}
node_color = {1: "blue", 2: "green", 3: "blue", 4: "lightgreen", 5: "lightgreen", 6: "lightblue", 7: "lightblue"}

relation = {}
relation[(1, 4)] = "dad"
relation[(2, 4)] = "mom"
relation[(1, 5)] = "dad"
relation[(2, 5)] = "mom"
relation[(3, 6)] = "dad"
relation[(4, 6)] = "mom"
relation[(3, 7)] = "dad"
relation[(4, 7)] = "mom"

g = nx.from_edgelist(relation, nx.DiGraph())
Graph(g, node_labels=node_labels, edge_labels=relation,
      node_color=node_color, node_edge_color=node_color, arrows=True)

plt.show()