这是一种将节点颜色存储为节点属性并将它们保存在 GraphML 格式文件中的方法。然后您可以读取该文件并将节点和属性解压缩到列表中以传递给 nx.draw()(或 nx.draw_networkx_nodes())
import matplotlib.pyplot as plt
import networkx as nx
# create graph
G=nx.Graph()
# with nodes that have attribute "color"
G.add_nodes_from('abc',color='r')
G.add_nodes_from('de',color='b')
G.add_edges_from([('a','b'),('b','d'),('c','e'),('b','e')])
# save/load in graphml format
nx.write_graphml(G,'color_test.graphml')
H=nx.read_graphml('color_test.graphml')
# get nodes and colors as lists from graph attributes
nodes,colors=zip(*nx.get_node_attributes(H,'color').items())
nx.draw(H,nodelist=nodes,node_color=colors)
plt.show()