0

If I already have a graph of a city in a figure, can I draw one or more routes on it afterwards? Until now I have created a graph within some bounding box which I then display with plt.show():

north, west = 47.45711622150064, 8.347885652066624
south, east = 47.31625428324118, 8.69120840316829

G = ox.graph.graph_from_bbox(north, south, east, west, network_type='drive', simplify=True, retain_all=False)

fig, ax = ox.plot.plot_graph(G)

plt.show()

So now you can see the graph in the matplot figure:

figure of graph

Then I want the user to enter start and destination coordinates and display the calculated shortest route on this figure. However, I have no idea how to plot the route on the figure after the figure is opened. This doesn't work:

G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)

start_node = ox.distance.nearest_nodes(G, 8.435432953597548, 47.39719131318801)
end_node = ox.distance.nearest_nodes(G, 8.636963408494227, 47.3699935785241)

# Calculate the shortest path
route = nx.shortest_path(G, start_node, end_node, weight='travel_time')

# Plot the route and street networks
fig, ax = ox.plot_graph_route(G, route, route_linewidth=1, show=False, close=False)

plt.show()
Hey Hey
  • 11
  • 3
  • I'm not sure if it's possible to change the shown figure, while using `plt.show`. You probably want something like discussed [here](https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib) or want an interactive matplotlib session: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ion.html#matplotlib.pyplot.ion – Sparky05 Sep 09 '21 at 10:36

1 Answers1

0

See the documentation. Set the close and show arguments to False so you can continue to change the figure before showing it. If you're doing this in a Jupyter notebook make sure all the code is in a single cell.

gboeing
  • 5,691
  • 2
  • 15
  • 41