通过networkx为节点着色

Sak*_*shi 1 csv topology networkx python-3.x

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

网络.csv:

源、端口、目的地

s1,1,c3

s2,1,c1

s0,1,c2

s1,2,s2

s2,2,s0

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

zoh*_*kom 5

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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

结果应该是这样的:

在此输入图像描述