networkx 的颜色节点

Color nodes by networkx

我正在通过 csv 文件中的数据生成网络拓扑图,其中 s0..s2 和 c1..c3 是图的节点。

network.csv:

source,port,destination

s1,1,c3

s2,1,c1

s0,1,c2

s1,2,s2

s2,2,s0

我需要将所有源设为蓝色,将目标设为绿色。 如何在不覆盖源节点的情况下做到这一点?

以下是一个可行的解决方案:

import csv
import networkx as nx
from matplotlib import pyplot as plt

with open('../resources/network.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    edges = {(row['source'], row['destination']) for row in reader }
print(edges) # {('s1', 'c3'), ('s1', 's2'), ('s0', 'c2'), ('s2', 's0'), ('s2', 'c1')}

G = nx.DiGraph()
source_nodes = set([edge[0] for edge in edges])
G.add_edges_from(edges)
for n in G.nodes():
    G.nodes[n]['color'] = 'b' if n in source_nodes else 'g'

pos = nx.spring_layout(G)
colors = [node[1]['color'] for node in G.nodes(data=True)]
nx.draw_networkx(G, pos, with_labels=True, node_color=colors)
plt.show()

我们首先将 csv 读取到边列表,稍后用于 G 的构造。为了很好地定义颜色,我们将每个源节点设置为蓝色,其余的节点为绿色(即,也不是源节点的所有目标节点)。

我们还使用 nx.draw_networkx 来获得更紧凑的图形绘制实现。

结果应该是这样的: