Reputation: 349
I was hoping that you can helped me with this. I created a graph using an adjacency matrix with the next code.
graph = nx.from_numpy_array(adjacency_matrix, create using = nx.DiGraph)
mypos = nx.spring_layout(graph)
nx.draw_networkx(graph, pos = mypos)
and then I get the shortest path...
path = nx.shortest_path(graph, 3, 2)
print(path)
Which give me the next path
[3,1,2]
I was triying to draw the path creating a subgraph using the nodes given by the shortest path.
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')
And I get the next result
The problem is, even though it was draw, they added a new extra edge between node 2 and 3 that I don't want, is there a way to change this so I don't have that extra edge? I know that networkx can remove an edge using nx.remove_edge() but I don't want to be removing edges manually every time I run the program and choosing another path. Thank you in advance
Upvotes: 2
Views: 328
Reputation: 4892
For your problem you don't need a subgraph. You can highlight the path and the node with the following code, which is a simplification of the accepted answer from 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()
Upvotes: 1