如何使用networkx删除子图的最后一条边

2024-03-28 14:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望你能帮我。我在下一个代码中使用邻接矩阵创建了一个图

graph = nx.from_numpy_array(adjacency_matrix, create using = nx.DiGraph)
mypos = nx.spring_layout(graph)
nx.draw_networkx(graph, pos = mypos)

然后我得到了最短的路径

path = nx.shortest_path(graph, 3, 2)
print(path)

这给了我下一条路

[3,1,2]

我正在用最短路径给出的节点绘制一个子图

subgraph = graph.subgraph(path)
nx.draw_networkx(H, pos = mypos, arrows = True)
nx.draw_networkx_nodes(H, pos = mypos, node_color = 'r')
nx.draw_networkx_edges(H, pos = mypos, edge_color = 'r')

我得到了下一个结果

Figura

问题是,即使它是绘制的,他们在节点2和3之间添加了一个我不想要的新的额外边,有没有办法改变这一点,使我没有额外的边?我知道networkx可以使用nx.remove_edge()删除边,但我不希望每次运行程序并选择其他路径时都手动删除边。 先谢谢你


Tags: path代码frompos路径networkx节点绘制
1条回答
网友
1楼 · 发布于 2024-03-28 14:34:42

对于你的问题,你不需要一个子图。您可以使用以下代码突出显示路径和节点,这是Highlighting certain nodes/edges in NetworkX - Issues with using zip()中接受答案的简化

import networkx as nx
import matplotlib.pylab as pl

# Set up graph
graph = nx.DiGraph(nx.karate_club_graph())

# Get position using spring layout
pos = nx.spring_layout(graph)

# Get shortest path
path = nx.shortest_path(graph, 0, 9)
# if you want to draw fewer edges, you can modify the following line by setting limits
path_edges = list(zip(path,path[1:]))

# Draw nodes and edges not included in path
nx.draw_networkx_nodes(graph, pos, node_color='k', nodelist=set(graph.nodes)-set(path))
nx.draw_networkx_edges(graph, pos, edgelist=set(graph.edges)-set(path_edges))

# Draw nodes and edges included in path
nx.draw_networkx_nodes(graph, pos, nodelist=path, node_color='r')
nx.draw_networkx_edges(graph,pos,edgelist=path_edges,edge_color='r')

pl.axis("off")
pl.show()

相关问题 更多 >