使用OSMNx绘制多条路线

时间:2018-07-10 05:51:23

标签: python python-3.x matplotlib osrm osmnx

我正在使用OSMNx绘制最短路径路线,但我找不到在同一地图上绘制多个路线的方法。 到目前为止,这是我的代码,

route_list = []
for i in range(len(pick_drop_outliers_ratio)):
coords = pick_drop_outliers_ratio["Pickup_Points"][i]
count = pick_drop_outliers_ratio["Count"][i]
print("i: ", i, " count: ", count)
if(count>9):
    coords = literal_eval(coords)
    pickup_lat = (coords[0][0])
    pickup_lon = (coords[0][1])
    dropoff_lat = (coords[1][0])
    dropoff_lon = (coords[1][1])
    orig_node = ox.get_nearest_node(G, (pickup_lat, pickup_lon))
    dest_node = ox.get_nearest_node(G, (dropoff_lat, dropoff_lon))
    route = nx.shortest_path(G, orig_node, dest_node, weight='length')
    route_list.append(route)
fig, ax = ox.plot_graph_route(G, route_list, node_size=0)

我希望在同一地图上的route_list中以不同的颜色绘制每条路线。由于OSMNx中没有内置功能,有没有办法做到这一点?

我发现解决方案是“绘制图形,然后使用matplotlib在顶部手动添加路由”。但是无法实现。

3 个答案:

答案 0 :(得分:1)

看看OSMNX pull request #152。它尚未被合并到OSMNX master中,但是我自己使用了该代码,并且效果很好-您可以将其复制到自己的脚本(或实用程序文件)中,修复任何预期的导入,并轻松地使用它

对于多种颜色,似乎很容易修改代码以接受route_color而不是单个route_color字符串的数组。

答案 1 :(得分:1)

值得注意的是,此功能自v0.8.2起已存在于OSMnx中。示例here绘制多条具有各自颜色的路线。

import networkx as nx
import osmnx as ox
ox.config(log_console=True, use_cache=True)

G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive')

# pick 4 random nodes as origins/destinations for the 2 routes
orig1 = list(G.nodes())[0]
dest1 = list(G.nodes())[-1]
orig2 = list(G.nodes())[50]
dest2 = list(G.nodes())[-50]

# calculate shortest paths for the 2 routes
route1 = nx.shortest_path(G, orig1, dest1, weight='length')
route2 = nx.shortest_path(G, orig2, dest2, weight='length')

# create route colors
rc1 = ['r'] * (len(route1) - 1)
rc2 = ['b'] * len(route2)
rc = rc1 + rc2
nc = ['r', 'r', 'b', 'b']

# plot the routes
fig, ax = ox.plot_graph_routes(G, [route1, route2], route_color=rc, orig_dest_node_color=nc, node_size=0)

OSMnx plot multiple street network routes each with own color

答案 2 :(得分:0)

可以这样做, 无花果,ax = ox.plot_graph_routes(G,route_list,route_color = color_list) 但实际上,输出的准确性不如预期。要获得完美的输出,请为一种边缘使用一种颜色。但是对于您的情况,这将完全正常... `

route_list = []
for i in range(len(pick_drop_outliers_ratio)):
coords = pick_drop_outliers_ratio["Pickup_Points"][i]
count = pick_drop_outliers_ratio["Count"][i]
print("i: ", i, " count: ", count)
if(count>9):
    coords = literal_eval(coords)
    pickup_lat = (coords[0][0])
    pickup_lon = (coords[0][1])
    dropoff_lat = (coords[1][0])
    dropoff_lon = (coords[1][1])
    orig_node = ox.get_nearest_node(G, (pickup_lat, pickup_lon))
    dest_node = ox.get_nearest_node(G, (dropoff_lat, dropoff_lon))
    route = nx.shortest_path(G, orig_node, dest_node, weight='length')
    route_list.append(route)
fig, ax = ox.plot_graph_routes(G, route_list, node_size=0)

`

My example