I have a graph G (made from a road network shapefile), and a source node S, and a destination node D. I have calculated the length of shortest path using single_source_dijkstra_path_length, but now I need to save the actual path in a shapefile. This will not help, because it returns the graph representation of my network, which looks nothing like my original network. Is there a way to save this path separately as a shapefile?


When you read a shapefile in networkx with read_shp networkx simplifies the line to a start and end, though it keeps all the attributes, and a WKT and WKB representation of the feature for when you export the data again.

To get the subset of the graph g based on the shortest path you can simply get the subraph:

result_graph = g.subgraph(nx.shortest_path(g, 'from', 'to'))

And then you can export the result using write_shp. This will write a node shapefile and an edge shapefile to the specified directory.

nx.write_shp(result_graph, 'output_directory')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.