def _get_edge_colors_by_attr(self, G, attr, num_bins=5, cmap='viridis', start=0, stop=1, na_color='none', bins=None): # todo: send to osmnx with option qcut oder cut """ Get a list of edge colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the continuous-variable attribute num_bins : int how many quantiles cmap : string name of a colormap start : float where to start in the colorspace stop : float where to end in the colorspace na_color : string what color to assign nodes with null attribute values Returns ------- list """ if bins is None: bin_labels = range(num_bins) colors = osmnx.get_colors(num_bins, cmap, start, stop) else: num_bins = bins bin_labels = range(len(num_bins) - 1) colors = osmnx.get_colors(len(num_bins) - 1, cmap, start, stop) attr_values = pd.Series( [data[attr] for u, v, key, data in G.edges(keys=True, data=True)]) cats, bins = pd.cut(x=attr_values, bins=num_bins, labels=bin_labels, retbins=True) edge_colors = [ colors[int(cat)] if pd.notnull(cat) else na_color for cat in cats ] return edge_colors, bins
def test_plots(): G = ox.graph_from_place('Piedmont, California, USA', network_type='drive', simplify=False) G2 = ox.simplify_graph(G, strict=False) # test getting colors co = ox.get_colors(n=5, return_hex=True) nc = ox.get_node_colors_by_attr(G2, 'osmid') ec = ox.get_edge_colors_by_attr(G2, 'length') # save a plot to disk as png fig, ax = ox.plot_graph(G, save=True, file_format='png') # save a plot to disk as svg G_simplified = ox.simplify_graph(G) fig, ax = ox.plot_graph(G_simplified, show=False, save=True, close=True, file_format='svg') G_projected = ox.project_graph(G_simplified) fig, ax = ox.plot_graph(G_projected) fig, ax = ox.plot_graph(G_projected, fig_height=5, fig_width=5, margin=0.05, axis_off=False, bgcolor='y', file_format='png', filename='x', dpi=180, annotate=True, node_color='k', node_size=5, node_alpha=0.1, node_edgecolor='b', node_zorder=5, edge_color='r', edge_linewidth=2, edge_alpha=0.1, use_geom=False, show=False, save=True, close=True) fig, ax = ox.plot_figure_ground(G=G_simplified, file_format='png') fig, ax = ox.plot_figure_ground(point=(33.694981, -117.841375), file_format='png') fig, ax = ox.plot_figure_ground(address='Denver, Colorado, USA', file_format='png')
def generateIsochrone(point): network_type = 'walk' trip_times = [5, 10, 15, 20, 25] #in minutes travel_speed = 4.5 #walking speed in km/hour G = ox.core.graph_from_point(point, distance = 1000, network_type='walk') gdf_nodes = ox.graph_to_gdfs(G, edges=False) x, y = gdf_nodes['geometry'].unary_union.centroid.xy center_node = ox.get_nearest_node(G, (y[0], x[0])) meters_per_minute = travel_speed * 1000 / 60 #km per hour to m per minute for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute iso_colors = ox.get_colors(n=len(trip_times), cmap='YlOrRd_r', start=0.3, return_hex=True) # color the nodes node_colors = {} for trip_time, color in zip(sorted(trip_times, reverse=True), iso_colors): subgraph = nx.ego_graph(G, center_node, radius=trip_time, distance='time') for node in subgraph.nodes(): node_colors[node] = color nc = [node_colors[node] if node in node_colors else 'none' for node in G.nodes()] ns = [20 if node in node_colors else 0 for node in G.nodes()] fig, ax = ox.plot_graph(G, fig_height=8, node_color=nc, node_size=ns, node_alpha=0.8, node_zorder=2, show = False) GJp = mplleaflet.fig_to_geojson(fig=ax.figure) return GJp
def plot_map_with_cesna_communities(graph): graph = nx.MultiGraph(graph) # Need MultiGraph to plot attr_values = pd.Series([data['cesna'] for u, v, key, data in graph.edges(keys=True, data=True)]) values = sorted(attr_values.drop_duplicates()) color_map = ox.get_colors(len(values), cmap='jet') # Try to reduce likelihood of neighboring communities having similar color. random.shuffle(color_map) cv_map = {v:color_map[k] for k, v in enumerate(values)} edge_colors = attr_values.map(lambda x: cv_map[x]) ox.plot_graph(graph, edge_color=edge_colors, fig_height=12)
def find_area(): request = flask.request.args lat = float(request.get('lat')) lng = float(request.get('lng')) type = 'drive' trip_times = request.get('trip_times').split(',') ox.config(log_console=True, use_cache=True) G = ox.load_graphml('network.graphml') f = open("network_type.yml", "r") network_type = f.read() f.close() travel_speed = 60.0 if network_type == 'drive' else 4.5 center_node = ox.get_nearest_node(G, (lat, lng)) G = ox.load_graphml('project.graphml') meters_per_minute = travel_speed * 1000 / 60 for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute iso_colors = ox.get_colors(n=len(trip_times), cmap='Reds', start=0.3, return_hex=True) isochrone_polys = [] for trip_time in sorted(trip_times, reverse=True): subgraph = nx.ego_graph(G, center_node, radius=float(trip_time), distance='time') node_points = [ Point((float(data['lat']), float(data['lon']))) for node, data in subgraph.nodes(data=True) ] bounding_poly = gpd.GeoSeries(node_points).unary_union.convex_hull isochrone_polys.append(bounding_poly) polygons_array = [] for polygon, fc in zip(isochrone_polys, iso_colors): patch = PolygonPatch(polygon, fc=fc, ec='none', alpha=0.6, zorder=-1) geojson = { "type": "Feature", "properties": { "timeline": trip_time }, "geometry": { "type": "Polygon", "coordinates": [ list(([list(x)[0], list(x)[1]] for x in list(patch._path.vertices))) ] } } polygons_array.append(geojson) return flask.jsonify(polygons_array)
def plot_map_with_gmmc_communities(data): print('Got %d communities' % len(data.gmmc)) graph = nx.MultiGraph(data.graph) # Need MultiGraph to plot color_map = ox.get_colors(len(data.gmmc), cmap='jet') # Try to reduce likelihood of neighboring communities having similar color. random.shuffle(color_map) n2c = {} for c, ns in enumerate(data.gmmc): col = color_map[c] for n in ns: n2c[n] = col node_colors = [n2c[n] for n in graph.nodes()] ox.plot_graph(graph, node_color=node_colors, fig_height=12)
# take the portal to different edges #for every center node - put magia in list and pass to nx ego graph G.add_edge('magia', center_node, length=0) G.add_edge('magia', center_node2, length=0) #create one #nx.ego_graph(G, 'magia', radius=5, distance='length').edges() # add an edge attribute for time in minutes required to traverse each edge meters_per_minute = travel_speed * 1000 / 60 #km per hour to m per minute for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute # get one color for each isochrone iso_colors = ox.get_colors(n=len(trip_times), cmap='Reds', start=0.3, return_hex=True) # color the nodes according to isochrone then plot the street network node_colors = {} for trip_time, color in zip(sorted(trip_times, reverse=True), iso_colors): subgraph = nx.ego_graph( G, 'magia', radius=trip_time, distance='time' ) # Returns subgraph of neighbors centered at node n within a given radius., ie Berkeley, CA, USA_UTM for node in subgraph.nodes( ): # Return a copy of the graph nodes in a list. node_colors[node] = color # make the isochrone polygons isochrone_polys = [] for trip_time in sorted(trip_times, reverse=True):
west_bbox = coords_data.loc[0, "min"] print(city) print(north_bbox, south_bbox, east_bbox, west_bbox) G = ox.graph_from_bbox(north_bbox, south_bbox, east_bbox, west_bbox, network_type='walk') approx = ox.basic_stats(G)["n"] / 20 node_centrality = nx.degree_centrality(G) df = pd.DataFrame(data=pd.Series(node_centrality).sort_values(), columns=['cc']) df['colors'] = ox.get_colors(n=len(df), cmap='inferno', start=0.2) df = df.reindex(G.nodes()) nc = df['colors'].tolist() fig, ax = ox.plot_graph(G, bgcolor='k', node_size=4, node_color=nc, node_edgecolor='none', node_zorder=2, edge_color="#46454b", edge_linewidth=1.5, edge_alpha=1, show=False, close=False) ax.set_title(city) fig.set_size_inches(4, 4)
def get_waypoints_by_lat_long(lat, long, network_type='walk', maxtime=15, vagas_df=None, plot=False): G = ox.graph_from_point((lat, long), network_type=network_type) dest_node = ox.get_nearest_node(G, (lat, long)) ################################################## # Compute `time` and `vagastime` edge attributes # time = length / speed # vagastime = time / vagas ################################################## travel_speed = 3.5 #walking speed in km/hour meters_per_minute = travel_speed * 1000 / 60 #km per hour to m per minute for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute data['vagastime'] = data['length'] / meters_per_minute edge_in_list = vagas_df[vagas_df.ID == "%d-%d" % (u, v)] if len(edge_in_list.index): # nonempty vaga = edge_in_list.iloc[0].TemVaga if vaga == 0: G.remove_edge(u, v) else: data['vagastime'] /= vaga edge_in_list = vagas_df[vagas_df.ID == "%d-%d" % (v, u)] if len(edge_in_list.index): # nonempty vaga = edge_in_list.iloc[0].TemVaga if vaga == 0: G.remove_edge(u, v) else: data['vagastime'] /= vaga ################################################## # Compute `isochrones`. Ensures we are within # walking distance ################################################## trip_times = np.linspace(2, maxtime, num=10) #in minutes iso_colors = ox.get_colors(n=len(trip_times), cmap='Reds', start=0.3, return_hex=True) node_colors = {} for trip_time, color in zip(sorted(trip_times, reverse=True), iso_colors): subgraph = nx.ego_graph(G, dest_node, radius=trip_time, distance='vagastime') for node in subgraph.nodes(): node_colors[node] = color nc = [ node_colors[node] if node in node_colors else 'none' for node in G.nodes() ] if plot: nc = [ 'k' if node == dest_node else nc[i] for (i, node) in enumerate(G.nodes()) ] # Make dest node black ns = [30 if node in node_colors else 0 for node in G.nodes()] ns = [ 500 if node == dest_node else ns[i] for (i, node) in enumerate(G.nodes()) ] # Make dest node large #ox.plot_graph(G, fig_height=8, node_color=nc, node_size=ns, node_alpha=0.8, node_zorder=2) ################################################## # Compute all routes to every place, get line segments ################################################## routes = [] for color, node in zip(nc, G.nodes()): if color != 'none': routes.append(nx.shortest_path(G, dest_node, node, weight='length')) lines = [] for i, route in enumerate(routes): lines_route = [] edge_nodes = list(zip(route[:-1], route[1:])) for u, v in edge_nodes: # if there are parallel edges, select the shortest in length data = min(G.get_edge_data(u, v).values(), key=lambda x: x['length']) # if it has a geometry attribute (ie, a list of line segments) if 'geometry' in data: # add them to the list of lines to plot xs, ys = data['geometry'].xy #print(i) #print("geom") #print(list(zip(xs, ys))) lines_route += list(zip(xs, ys)) else: # if it doesn't have a geometry attribute, the edge is a straight # line from node to node x1 = G.nodes[u]['x'] y1 = G.nodes[u]['y'] x2 = G.nodes[v]['x'] y2 = G.nodes[v]['y'] line = [(x1, y1), (x2, y2)] #print(i) #print("line") #print(line) lines_route += line lines_route = remove_adjacent(lines_route) for prev_rout in lines: if is_subline(lines_route, prev_rout): continue lines = [item for item in lines if not is_subline(item, lines_route)] lines.append(lines_route) return lines
def isochrone(G, isPlot=False): """calculate the isocrone from a graph""" # from descartes import PolygonPatch ox.config(log_console=True, use_cache=True) trip_times = [5, 10, 15, 20, 25] # in minutes travel_speed = 4.5 # walking speed in km/hour gdf_nodes = ox.graph_to_gdfs(G, edges=False) x, y = gdf_nodes['geometry'].unary_union.centroid.xy center_node = ox.get_nearest_node(G, (y[0], x[0])) G = ox.project_graph(G) meters_per_minute = travel_speed * 1000 / 60 # km per hour to m per minute for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute data['time'] = data['length'] / data['speed'] # * 0.06 # m / km/h iso_colors = ox.get_colors(n=len(trip_times), cmap='Reds', start=0.3, return_hex=True) node_colors = {} isochrone_polys = [] for trip_time, color in zip(sorted(trip_times, reverse=True), iso_colors): subgraph = nx.ego_graph(G, center_node, radius=trip_time, distance='time') for node in subgraph.nodes(): node_colors[node] = color node_points = [ Point((data['x'], data['y'])) for node, data in subgraph.nodes(data=True) ] bounding_poly = gpd.GeoSeries(node_points).unary_union.convex_hull isochrone_polys.append(bounding_poly) nc = [ node_colors[node] if node in node_colors else 'none' for node in G.nodes() ] ns = [20 if node in node_colors else 0 for node in G.nodes()] if isPlot: fig, ax1 = ox.plot_graph(G, fig_height=8, node_color=nc, node_size=ns, node_alpha=0.8, node_zorder=2, show=False, close=False) fig, ax = ox.plot_graph(G, fig_height=8, show=False, close=False, edge_color='k', edge_alpha=0.2, node_color='none') for polygon, fc in zip(isochrone_polys, iso_colors): patch = PolygonPatch(polygon, fc=fc, ec='none', alpha=0.6, zorder=-1) ax.add_patch(patch) plt.show() return isochrone_polys
def __get_color_list(self, df): return osmnx.get_colors(n=len(df), cmap='inferno', start=0.2)