这是我之前在此处发布的问题的后续内容,以可视化图表中的边缘攻击。
下面的代码已作为我之前帖子的答案发布
import matplotlib.pyplot as plt
import networkx as nx
H = nx.gnm_random_graph(n=8, m=9, seed=5) # generate a random graph
H.add_edges_from([('I', 1), (5, 'O')]) # adding input/output nodes
pos = nx.spring_layout(H, iterations=200) # find good positions for nodes
def attack(G, edge, color):
G.remove_edge(*edge) # first remove the edge
# check if another could be also impacted
if G.degree[edge[0]] == 1:
neighbor = [n for n in G.neighbors(edge[0])][0]
impacted_edge = (edge[0], neighbor)
elif G.degree[edge[1]] == 1:
neighbor = [n for n in G.neighbors(edge[1])][0]
impacted_edge = (edge[1], neighbor)
else:
impacted_edge = None
G.add_edge(*edge) # put back the edge to redraw it
# redraw the attacked edge (solid) and the possible impacted one (dashed)
if impacted_edge:
nx.draw_networkx_edges(
G,
edgelist=[impacted_edge],
pos=pos,
edge_color=color,
style='dashed',
width=4
)
nx.draw_networkx_edges(
G,
edgelist=[edge],
pos=pos,
edge_color=color,
label=f'attack {edge[0]}{edge[1]}',
style='solid',
width=4
)
# attack some edges
attack(H, (6, 4), color='red')
attack(H, (3, 6), color='blue')
attack(H, (1, 2), color='green')
nx.draw(H, pos, node_size=700, with_labels=True, node_color='gray')
plt.legend()
plt.show()
实线表示受到攻击的边缘,相同颜色的虚线表示由于特定攻击而受到影响的相邻边缘。
答案会有所帮助,但是当受影响的边缘重叠时会出现问题。
例子,
attack(H, (6, 4), color='red')
attack(H, (5, 4), color='yellow')
颜色重叠,很难想象。如果我们可以画出表示受影响/被攻击边缘的虚线彼此相邻,而不会像这张图片中显示的那样重叠,那将是很好的。
将不胜感激有关如何改进此可视化的建议!
编辑:下面发布的答案对 2D 网络非常有用,我仍在寻找方法来扩展它以pos在 pyvis 中可视化 3D 网络(即当 x、y、z 坐标可用作节点的属性时)。建议将不胜感激。


