Пример #1
0
def render_sub_graphs(og_graph, sub_graphs):

    node_colors_dict = dict.fromkeys(og_graph.nodes)
    edge_colors_dict = dict.fromkeys(og_graph.edges)

    colors = [
        'darkviolet', 'blue', 'deeppink', 'lime', 'indigo', 'deepskyblue',
        'green', 'maroon', 'teal', 'yellow', 'fuchsia', 'gold', 'orange',
        'aqua', 'red', 'mint'
    ]

    for i, g in enumerate(sub_graphs):
        color = colors[i % len(colors)]
        for node in g.nodes:
            node_colors_dict[node] = color
        for edge in g.edges:
            edge_colors_dict[edge] = color

    node_colors = [node_colors_dict.get(node, 0) for node in og_graph.nodes]
    edge_colors = [edge_colors_dict.get(edge, 0) for edge in og_graph.edges]

    edge_colors = [c if c is not None else 'white' for c in edge_colors]

    ox.plot_graph(og_graph,
                  node_size=0,
                  node_zorder=2,
                  node_color=node_colors,
                  edge_linewidth=0.1,
                  edge_color=edge_colors,
                  show=False,
                  close=True,
                  save=True,
                  filepath='zones.png')

    print('Zone rendering available at "zones.png"')
Пример #2
0
    def crop_and_save_graph(self, save=False):
        if save:
            fig, ax = ox.plot_graph(self.graph, save=True, show=False, filename='Ekb_graph', file_format='png',
                                    node_alpha=0, edge_color='b', edge_linewidth=0.6, dpi=200)
        ox.core.remove_isolated_nodes(self.graph)
        self.update_nodes_list()
        self.set_non_oriented_adj_list()

        removing_nodes = []
        distances, preds = distances_fwd(self.non_oriented_adj_list, [self.inf_objs[0]], self.nodes, self.weights)
        dists = distances[self.inf_objs[0]]
        for i in dists:
            if dists[i] == float('inf'):
                removing_nodes.append(i)
        self.graph.remove_nodes_from(removing_nodes)
        self.update_nodes_list()

        dists, _ = dijkstra(self.graph.adj, 175246547, self.weights)
        inf_arr = []
        for id_ in dists:
            if dists[id_] == float('inf'):
                inf_arr.append(id_)
        self.graph.remove_nodes_from(inf_arr)
        self.update_nodes_list()
        self.set_non_oriented_adj_list()

        inf_objs_set = set(self.inf_objs)
        self.objs = list(filter(lambda x: x not in inf_objs_set, self.nodes))

        if save:
            fig, ax = ox.plot_graph(self.graph, save=True, show=False, filename='Ekb_graph_cropped', dpi=200,
                                    file_format='png', node_alpha=0, edge_color='b', edge_linewidth=0.6)
Пример #3
0
def make_graph(lat, lng, distance):
    '''
	Make initial graph of accident area from lat, lng, return graph, plot, and bounding box of area plotted
	'''
    # get graph of accident area
    G = ox.graph_from_point((lat, lng),
                            dist=distance,
                            dist_type='bbox',
                            network_type='drive',
                            retain_all=True,
                            simplify=False)

    #create fig
    my_dpi = 192
    pixels = 400
    fig = plt.figure(figsize=(pixels / my_dpi, pixels / my_dpi),
                     dpi=my_dpi,
                     constrained_layout=True)
    ax = fig.add_subplot()

    #add graph to plot
    ox.plot_graph(G, node_size=0, edge_color='black', ax=ax, show=False)

    bbox = get_bbox(ax)

    return fig, ax, G, bbox
Пример #4
0
def plot(g, fig_height, node_size, point, text, color, save):
    # Don't show plot until point is added to graph
    if point:
        fig, ax = ox.plot_graph(g,
                                fig_height=fig_height,
                                node_size=node_size,
                                edge_color=color,
                                node_color=color,
                                show=False,
                                close=False)
        ax.scatter(x=point[1], y=point[0], c=[color])

        if save:
            ox.save_and_show(fig=fig,
                             ax=ax,
                             save=True,
                             show=False,
                             close=False,
                             filename=text,
                             file_format='jpg',
                             dpi=None,
                             axis_off=True)
        else:
            return plt
    else:
        fig, ax = ox.plot_graph(g,
                                fig_height=fig_height,
                                node_size=node_size,
                                edge_color=color,
                                node_color=color)
Пример #5
0
def get_network_info(city_str, verbose=False, draw=False, downloaded=False):
    if verbose == True:
        print("city:", city_str)
    start = datetime.now()
    #First we must get the graph from Open Street Maps. Either we already have
    # it on our system or we need to run getdata script:
    if downloaded == True:
        pass
    else:
        graph = getdata.get_graph(city_str)
    #Maybe there was a problem in finding the graph, in which case this city
    # is not good and we have to do something else with it.
    if graph == None:
        if verbose == True:
            print("We couldn't find a graph for this city.")
        return None, None, None, None, None
    if draw == True:
        ox.plot_graph(graph)
    if verbose == True:
        print("Took", datetime.now()-start, "seconds to get the graph")
    n = graph.order()
    m = graph.size()
    sl = nx.number_of_selfloops(graph)
    #Now we prepare the graph for our data through removing multiple edges
    # and self-loops:
    new_graph = nx.Graph(graph)
    new_graph.remove_edges_from(nx.selfloop_edges(new_graph))
    #We collect the new number of edges and the motif vector:
    m_simp = new_graph.size()
    motif_vector = mcount.get_motifvector(new_graph)
    if verbose == True:
        print("Took", datetime.now()-start, "seconds for everything")
    return n, m, m_simp, sl, motif_vector
Пример #6
0
def project_and_plot(g,
                     fig_height,
                     node_size,
                     point=None,
                     text='test',
                     color=None,
                     save=False):
    if point:  # Don't show plot until point is added to graph
        fig, ax = ox.plot_graph(g,
                                fig_height=fig_height,
                                node_size=node_size,
                                edge_color=color,
                                node_color=color,
                                show=False,
                                close=False)
        ax.scatter(x=point[1], y=point[0], c=['#00688B'])

        if save:
            ox.save_and_show(fig=fig,
                             ax=ax,
                             save=True,
                             show=True,
                             close=False,
                             filename=text,
                             file_format='svg',
                             dpi=None,
                             axis_off=True)
        else:
            plt.show()
    else:
        fig, ax = ox.plot_graph(g,
                                fig_height=fig_height,
                                node_size=node_size,
                                edge_color=color,
                                node_color=color)
Пример #7
0
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 test_line_to_nodes(self):
        """
        Do:
            - Make new TramLine object
            - Show it`s default route
            - Convert default_route to list of nodes and siplay as subgraph
        Expected:
            - Both LineString and subgraph are displayed
            - User manually verifies whether conversion is correct or not
        """
        # Load data
        dl = DataLoader()
        G = dl.graph
        lines_table = dl.load_all_lines()

        for line in lines_table:
            # Create TramLine object
            tram_line = TramLine(str(line[0]), line[1], dl)
            tram_line.show()
            # Convert line to nodes in order to verify graph before edges deletion
            nodes = GraphConverter.line_to_nodes_precise(G, tram_line)
            sub_graph = G.subgraph(nodes)
            ox.plot_graph(sub_graph)
            tram_line.current_route = GraphConverter.route_to_line_string(
                sub_graph)
            print(tram_line.current_route.contains(tram_line.stops[0]))
            tram_line.show()

        self.assertTrue(True)
Пример #9
0
def loadOSMnxMap(file=None, download=False, saveMap=False):
    point1 = (45.1904, 5.7607)  #todo load point from given gpx

    distance = 1000
    distance_type_var = 'network'
    network_type_var = 'walk'

    print("==============   Loading map   ==================")
    if (not file and not download):
        print('No map specified')
    elif (file):
        graph = osmnx.load_graphml(filename=file, folder=None)
        print("Map loaded")
        g, a = osmnx.plot_graph(graph, show=False, close=False)
        return g, a
    elif (download):
        graph = osmnx.graph_from_point(point1,
                                       distance,
                                       distance_type=distance_type_var,
                                       network_type=network_type_var)
        if (saveMap):
            osmnx.save_graphml(graph, filename='map.hraphml')
            print('Map saved')
        print("Map loaded")
        return osmnx.plot_graph(graph, show=False, close=False)
    return None, None
Пример #10
0
    def voronoi_plot(self, save=False, seed=None):
        voronoi_df = self.voronoi_cells_df()
        number_of_colors = self.size

        random.seed(seed)
        color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
                 for i in range(number_of_colors)]

        nc = ['gray'] * len(self.graph_nodes)
        for index, closest_station_data in voronoi_df.iterrows():
            nc[index] = color[int(closest_station_data['nearest station']) - 1]
        ox.plot_graph(
            G=self.location_graph,
            fig_height=50,
            node_size=100,
            node_color=nc,
            node_zorder=2,
            edge_alpha=0.5,
            save=save,
            filename='voronoi_cdmx',
            dpi=100,
            edge_color='white',
            bgcolor='black'
        )

        return None
Пример #11
0
    def plotG(self,G,colored=False, save=False, filepath=False):
        if colored:
            ec=[]
            for _,_,_, d in G.edges(keys=True, data=True):

                bi = False
                if "bicycle" in d:
                    if d['bicycle']=='designated' or d['bicycle']=='official' or d['bicycle']=='track' or d['bicycle']=='use_sidepath':
                        bi = True
                if "bicycle:lanes" in d:
                    if "designated" in d['bicycle:lanes']:
                        bi = True

                if d['highway']=='cycleway':
                    ec.append('#3366e6')
                elif 'cycleway' in d and d['cycleway'] != "no" and d['cycleway'] != "opposite":
                   ec.append('#3366e6')
                elif bi:
                    ec.append('#3366e6')
                elif 'cycleway:right' in d and d['cycleway:right'] != "no":
                    ec.append('#3366e6')
                elif 'cycleway:left' in d and d['cycleway:left'] != "no":
                    ec.append('#3366e6')
                elif 'bicycle_road' in d and d['bicycle_road'] == "yes":
                    ec.append('#3366e6')
                else:
                    ec.append('#d4d4d4')
            fig, ax = ox.plot_graph(G, edge_color=ec, save=save, show=True, filepath=filepath, node_color='#7d7d7d', edge_alpha=0.6, node_size=0, figsize=(37.5590551,18.7795276), dpi=1200, bgcolor="#FFFFFF", edge_linewidth=3)
        else:
            fig, ax = ox.plot_graph(G)
Пример #12
0
def plot_community_bus_routes(G):
    nodes, edges = ox.graph_to_gdfs(G)
    # get nodes that are on the routes
    # and create a graph containing only those
    route_nodes = nodes[(nodes["community_route"])]
    route_nodes_graph = ox.graph_from_gdfs(route_nodes, edges)

    # convert community labels to integers so that get_node_colors_by_attr
    # can use the community attribute
    for x, y in route_nodes_graph.nodes(data=True):
        if "community" in y:
            y["community"] = int(y["community"])

    node_colours = ox.plot.get_node_colors_by_attr(route_nodes_graph,
                                                   attr="community",
                                                   cmap="tab20")

    # graph_from_gdfs creates empty nodes so need
    # to update node_colours to include those so
    # that plot graph function will work correctly
    other_nodes = {
        x: (0, 0, 0, 0)
        for x, y in G.nodes(data=True) if x not in node_colours.index
    }
    series = pd.Series(other_nodes)
    node_colours = node_colours.append(series)

    ox.plot_graph(route_nodes_graph,
                  node_color=node_colours,
                  edge_color="w",
                  node_size=15)
Пример #13
0
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')
Пример #14
0
    def __init__(self, geopostion=None, name=None):
        if geopostion:
            self.geo = geopostion
        if name:
            self.nameFile = name

        try:
            self.settings = dict(bgcolor="white",
                                 equal_aspect=False,
                                 node_size=30,
                                 node_color='#1f78b4',
                                 node_edgecolor="none",
                                 node_zorder=2,
                                 axis_off=False,
                                 edge_color="#555555",
                                 edge_linewidth=1.5,
                                 edge_alpha=1,
                                 show=False,
                                 close=False,
                                 save=False)
            self.Graph = self.load_darmstadt(self.nameFile)
            self.sparse_adj = self.extract_adjencecacy()
            self.figCityMap, self.cityMap = ox.plot_graph(
                self.Graph, **self.settings)
        except FileNotFoundError:
            print("Could not find file ... redownload")
            self.Graph = self.download_darmstadt(self.geo,
                                                 self.nameFile,
                                                 self.locationFile,
                                                 show=False)
            self.sparse_adj = self.extract_adjencecacy()
            self.figCityMap, self.cityMap = ox.plot_graph(
                self.Graph, **self.settings)
Пример #15
0
    def download_darmstadt(self, geo, name, loc, show=True):
        """
        This functions downloads and save the network city map of darmstadt\n
        @param:\n
            geo {dict}: [Dictionary of latitude and longitude GPS coordinates]\n
            name {String}: [name of graphml file]\n
            loc {String}: [save location]\n
            show {bool}: [flag which plots the downloaded network city map] (default: {True})
        """

        if all(k in geo for k in ("north", "south", "west", "east")):
            print("Load Darmstadt from Openstreetmap ... ")
            G = ox.core.graph_from_bbox(north=geo["north"],
                                        south=geo["south"],
                                        west=geo["west"],
                                        east=geo["east"],
                                        network_type='drive')
            print("Save Darmstadt ... ")
            ox.save_load.save_graphml(G,
                                      filename="{}.graphml".format(name),
                                      folder=loc)
            print("Saved")
        else:
            print("Geoposition is missing an entity e.g. north,south, etc. ")
        if show:
            print("Plot Darmstadt ... ")
            ox.plot_graph(G, show=True, close=False)
        return G
Пример #16
0
def graph_with_edge_pollution(graph):
    ec = []
    pollutionPerEdge = []
    edgePolList = []
    for e in graph.edges():
        if 'pollution_amount' in graph.edge[e[0]][e[1]][0]:
            pollutionPerEdge.append(
                graph.edge[e[0]][e[1]][0]['pollution_amount'])
            edgePolList.append(e)

    norm = cm.colors.Normalize(vmin=0, vmax=max(pollutionPerEdge))
    cmap = cm.ScalarMappable(norm=norm, cmap=cm.GnBu)

    for e in graph.edges():
        if 'pollution_amount' in graph.edge[e[0]][e[1]][0]:
            ec.append(
                cmap.to_rgba(graph.edge[e[0]][e[1]][0]['pollution_amount'],
                             alpha=0))
        else:
            ec.append((
                1,
                0,
                0,
                0,
            ))

    ox.plot_graph(graph, edge_color=ec, edge_linewidth=2.5)
    return ec
Пример #17
0
def InitialSetup():

    custom_walk = ('["area"!~"yes"]["highway"="footway"]["foot"!~"no"]["service"!~"private"]{}').format(ox.settings.default_access)
    global factor, img,image_map_horizontal,image_map_vertical ,nodes,edges, fig,ax,G_projected,threshold,G
    G = ox.graph_from_bbox(top, bottom,right, left,custom_filter= custom_walk)#network_type="walk")#
    
##    G_projected = ox.core.graph_from_file("centralcampus.xml", network_type = 'walk',simplify=True,retain_all=False)
##Uncomment this for the original stuff
    G_projected = ox.project_graph(G)
    ox.plot_graph(G_projected,save = True,filename = "maps", show = False,
                  node_color='#999999',node_edgecolor='#999999',edge_color='#999999',bgcolor = "#000000",
                  node_zorder=3,dpi=200, edge_linewidth=8,use_geom=True)
    ox.simplify.clean_intersections(G,tolerance=100)
    
    nodes, edges = ox.graph_to_gdfs(G)
    fig,ax = pyplot.subplots()
    ax.axis ('OFF')
    img = Image.open('images/maps.png').convert('L').rotate(angle)
    img.save('lowered.png')

    height_compensation = 0
    width_compensation = 0
    w,h = img.size
    image_size_w,image_size_h=img.size
    image_map_horizontal = float(left-right)/image_size_w
    image_map_vertical = float(top-bottom)/image_size_h
    if img.width >= image_size and img.height >= image_size:
        if img.height < img.width:
            print "factor denom height is ",str(img.height)
            factor = float(image_size) / img.height
        else:
            print "factor denom width is ",str(img.width)
            factor = float(image_size) / img.width

    PrintImg(img)
def graph(place_country, distance, filter):  # filter
    # filter out some attributes
    # filter = ('["highway"!~"residential|unclassified|living_street|track|abandoned|path|footway|service|pedestrian|road|'
    #           'raceway|cycleway|steps|construction"]')
    # filter = (
    #     '["highway"!~"residential|unclassified|living_street|track|abandoned|path|footway|service|pedestrian|road|'
    #     'raceway|cycleway|steps|construction|primary|secondary|tertiary"]')

    # filter = filter

    # import grapho (graphml)
    G = ox.graph_from_address(str(place_country),
                              distance=distance,
                              network_type='drive', custom_filter=filter) # custom_filter=filter



    ## import shapefile
    # G_shp = ox.gdf_from_place(place_country)

    ## import shapefile with edges and nodes
    ## as the data is in WGS84 format, we might first want to reproject our data into metric system
    ## so that our map looks better with the projection of the graph data in UTM format
    # G_projected = ox.project_graph(G)

    ## save street network as ESRI shapefile (includes NODES and EDGES)
    name_place_country = re.sub('[/," ",:]', '_', place_country)
    # ox.save_graph_shapefile(G_projected, filename='network_' + name_place_country + '-shape')
    ox.save_graphml(G, filename = name_place_country + '.graphml')
    # ox.save_gdf_shapefile(G_shp)
    ox.plot_graph(G)
Пример #19
0
    def plot_map(self, fig_height: int = 10):
        """Helper function to the initial

        Args:
            fig_height (int, optional): Defaults to 10. [description]
        """
        ox.plot_graph(self.g_init, fig_height=fig_height)
Пример #20
0
    def map(self, c='r', s=100, save=False):
        """
        Plot containing the geographic area with the stations' locations contained in self.location_graph
        :param c: color code, optional
            Color for the stations
        :param s: int, optional
            Dot size for the stations
        :param save: bool, optional, default False
            Whether to save the graph to a file
        :return: None
        """

        # selects nodes belonging or not to the stations and colors and scales them differently
        nc = np.where(self.graph_nodes.isin(self.network_df['node']), c, 'g')
        ns = np.where(self.graph_nodes.isin(self.network_df['node']), s, 0)
        ox.plot_graph(
            self.location_graph,
            fig_height=50,
            node_size=ns,
            node_color=nc,
            node_zorder=2,
            edge_alpha=0.5,
            save=save,
            filename=self.name + '_map',
            dpi=100,
            edge_color='white',
            bgcolor='black')

        return None
Пример #21
0
def Save_OSM_G_proj(placename=placename, network_type= 'walk', suffix=suffix, folder=OSM_folder, to_crs=None):    
    """
    save a projected graphml from graphml file
    Parameters
    ----------
    network_type : string
        what type of street network to get. Default type is pedestrain network
    placename: string
        place name
    suffix: string
        output data date
    folder : string
        where to save the shapefile, specify local folder path for OSM resource
    Returns
    -------
    none

    """
    G = ox.load_graphml(filename='{studyregion}_{network_type}{suffix}.graphml'.format(
        studyregion = placename, network_type=network_type, suffix = suffix), folder=folder)
    #set up project projection, and save the projected graph (project to UTM so we can use metres as a unit when buffering)
    G_proj = ox.project_graph(G, to_crs=to_crs)
    ox.save_graphml(G_proj, filename='{studyregion}_proj_{network_type}{suffix}.graphml'.format(
        studyregion = placename, network_type=network_type, suffix = suffix), folder=folder)
    ox.plot_graph(G_proj)
Пример #22
0
def remove_deadends(g, plot_all=False):
    """
    Reduce the number of nodes and edges in g by iteratively removing
    every node with degree one, and the connected vertex.
    
    Args:
        g (networkx.classes.multidigraph): Street graph from osmnx.
    
    Returns:
        networkx.classes.multidigraph: The simplified street graph.
    """

    simpler = g.to_undirected().copy()
    while True:
        nc = [
            'r' if degree <= 1 else 'b'
            for node, degree in simpler.degree().items()
        ]
        n_nodes = len(simpler.nodes())
        n_removed = len(list(filter(lambda x: x == 'r', nc)))
        if plot_all:
            print(
                'number of nodes in graph: {}, and number of nodes that will be removed: {}'
                .format(n_nodes, n_removed))
            ox.plot_graph(simpler, node_color=nc, node_zorder=3)

        for node, degree in simpler.degree().items():
            if degree <= 1:
                simpler.remove_node(node)

        if len(simpler.nodes()) == n_nodes:
            break
    return simpler
Пример #23
0
def Save_OSM_G(polygon, network_type= 'walk', placename=placename, suffix=suffix, folder=OSM_folder):    
    """
    save a graphml from a single polygon.
    Parameters
    ----------
    polygon : shapely Polygon or MultiPolygon
        the shape to get network data within. coordinates should be in units of
        latitude-longitude degrees.
    network_type : string
        what type of street network to get. Default type is pedestrain network
    placename: string
        place name
    suffix: string
        output data date
    folder : string
        where to save the shapefile, specify local folder path for OSM resource
    Returns
    -------
    none

    """
    #The graph_from_polygon function requires a polygon in units of lat-long (epsg 4326)
    G = ox.graph_from_polygon(polygon, network_type=network_type, retain_all = True)
    #save network as graphml
    ox.save_graphml(G, filename='{studyregion}_{network_type}{suffix}.graphml'.format(
        studyregion = placename, network_type=network_type, suffix = suffix), folder=folder)
    ox.plot_graph(G)
Пример #24
0
def test_plots():
    G = ox.graph_from_point(location_point, dist=500, network_type="drive")

    # test getting colors
    co = ox.plot.get_colors(n=5, return_hex=True)
    nc = ox.plot.get_node_colors_by_attr(G, "x")
    ec = ox.plot.get_edge_colors_by_attr(G, "length", num_bins=5)

    # plot and save to disk
    filepath = Path(ox.settings.data_folder) / "test.svg"
    fig, ax = ox.plot_graph(G, show=False, save=True, close=True, filepath=filepath)
    fig, ax = ox.plot_graph(
        G,
        figsize=(5, 5),
        bgcolor="y",
        dpi=180,
        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,
        show=False,
        save=True,
        close=True,
    )

    # figure-ground plots
    fig, ax = ox.plot_figure_ground(G=G)
    fig, ax = ox.plot_figure_ground(point=location_point, dist=500, network_type="drive")
    fig, ax = ox.plot_figure_ground(address=address, dist=500, network_type="bike")
Пример #25
0
def getChangchunTreet():
    treet = ox.graph_from_place(
        ['南关区,长春,中国', '朝阳区,长春,中国', '二道区,长春,中国', '绿园区,长春,中国', '宽城区,长春,中国'],
        network_type='drive')
    treet = ox.project_graph(treet)
    ox.save_graph_shapefile(treet, filename='test2')
    ox.plot_graph(treet)
Пример #26
0
def main(data_prefix, ona_csv_path, ids, geometry_column, settlement_name_column, output_filename, network_search_buffer = 0.001, parcel_files=None, export_shapefile=False):
    # network_search_buffer: suggest 0.001 for single-settlement zoom-ins, 0.01 for graph construction

    print("reading data")
    ona = pd.read_csv(data_prefix/ona_csv_path)
    ona = ona.loc[ona["_id"].isin(ids)]
    ona = ona[["_id", settlement_name_column, geometry_column]]
    ona[geometry_column] = ona[geometry_column].apply(geometry_text_to_polygon)
    original_polygons = list(ona[geometry_column])
    multipolygon = cascaded_union(original_polygons)
    buffered_multipolygon = multipolygon.buffer(network_search_buffer)
    print("getting graph")
    road_network = ox.graph_from_polygon(buffered_multipolygon, network_type="all_private", retain_all=True)#, clean_periphery=False, simplify=True)
    
    print("parsing graph")
    linestrings = linestrings_from_network(road_network)
    polygons = diff_polygonize(buffered_multipolygon, linestrings)

    print("plotting")
    fig, ax = ox.plot_graph(road_network, close=False, show=False, node_color='black', node_size=1)#, edge_color="white")

    # for polygon in original_polygons:
    #     ax.add_patch(PolygonPatch(polygon, fc='#bb5a40', ec='k', linewidth=0, alpha=0.6, zorder=10))

    plt.autoscale()
    plt.savefig(output_filename.replace(".shp", "_network.png"), bbox_inches="tight", dpi=300, transparent=True)
    plt.show()

    fig, ax = ox.plot_graph(road_network, close=False, show=False, node_alpha=0, edge_alpha=0)
    mp_border = buffered_multipolygon.boundary
    filtered_polygons = []
    for (polygon, color) in zip(polygons, colors):
        # ax.add_patch(PolygonPatch(polygon, fc=color, ec='white', linewidth=0.5, zorder=10))
        if not mp_border.intersects(polygon):
            filtered_polygons.append(polygon)
            ax.add_patch(PolygonPatch(polygon, fc=color, ec='white', linewidth=0.5, zorder=10))
    
    if parcel_files is not None:
        for pf in parcel_files:
            with shapefile.Reader(pf) as shp:
                for sr in shp.shapeRecords():
                    # print(sr.record)
                    ax.add_patch(PolygonPatch(sr.shape, fc="white", ec='white', linewidth=0.5, alpha=0.2, zorder=10))
    plt.autoscale()
    ax.axis('off')
    ax.margins(0)
    ax.tick_params(which='both', direction='in')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.savefig(output_filename.replace(".shp", "_blocks.png"), bbox_inches="tight", dpi=300, transparent=True)
    plt.show()

    if export_shapefile:
        print("exporting shapefile")
        with shapefile.Writer(data_prefix/output_filename) as shp:
            shp.field("index", "N")
            for (index, polygon) in enumerate(filtered_polygons):
                shp.record(index)
                shp.shape(mapping(polygon))
Пример #27
0
    def plot_graph (self):
        """
        This method provides a representation of the map downloaded.
        Further packages by Geopython might be used to improve the representation,
        but, for the moment I kept it simple.

        :return: None
        """
        ox.plot_graph(self.graph)
Пример #28
0
 def plot_streetnumber(self, positions, City=None, settings=None):
     if City:
         if settings:
             fig, ax = ox.plot_graph(City.Graph, **settings)
         else:
             fig, ax = ox.plot_graph(City.Graph, **City.settings)
         nx.draw_networkx(City.Graph,
                          pos=positions,
                          node_size=0,
                          node_color="white",
                          with_labels=False,
                          edge_linewidth=1)
         nx.draw_networkx_nodes(City.Graph,
                                pos=positions,
                                nodelist=City.Graph.nodes(),
                                node_color="none",
                                node_edgecolor="black",
                                with_labels=False,
                                node_size=100,
                                ax=ax)
         nx.draw_networkx_labels(
             City.Graph,
             pos=positions,
             labels=dict(
                 zip(City.Graph.nodes(),
                     range(City.Graph.number_of_nodes()))),
             font_size=18)
         plt.tight_layout()
         plt.show()
     else:
         if settings:
             fig, ax = ox.plot_graph(self.Graph, **settings)
         else:
             fig, ax = ox.plot_graph(self.Graph, **self.settings)
         nx.draw_networkx(self.Graph,
                          pos=positions,
                          node_size=0,
                          node_color="white",
                          with_labels=False,
                          edge_linewidth=1)
         nx.draw_networkx_nodes(self.Graph,
                                pos=positions,
                                nodelist=self.Graph.nodes(),
                                node_color="none",
                                node_edgecolor="black",
                                with_labels=False,
                                node_size=100,
                                ax=ax)
         nx.draw_networkx_labels(
             self.Graph,
             pos=positions,
             labels=dict(
                 zip(self.Graph.nodes(),
                     range(self.Graph.number_of_nodes()))),
             font_size=18)
         plt.tight_layout()
         plt.show()
Пример #29
0
 def obtain_map(self, plot=False, **args):
     if plot:
         import matplotlib.pyplot as plt
         ox.plot_graph(self._map,
                       bgcolor='white',
                       edge_color='black',
                       edge_linewidth=1.0)
         plt.show()
     return self._map
Пример #30
0
def getGraphs(G, fileToSave):
    N = G.number_of_nodes()
    numToRemove = int(N * 0.05)

    order = createOrder(G)

    counter = 0

    for i in range(18):
        print(i)

        nodesList = list(G.nodes())

        conn = list(nx.connected_component_subgraphs(G))
        biconn = list(nx.biconnected_component_subgraphs(G))

        GC = max(conn, key=len)
        GBC = max(biconn, key=len)

        GCnodes = list(GC.nodes())
        GBCnodes = list(GBC.nodes())

        try:
            fig, ax = ox.plot_graph(G, fig_height=30, fig_width=30)
        except:
            break

        for n in GCnodes:
            dictInfo = G.node[n]
            ax.scatter(dictInfo['x'], dictInfo['y'], c='green')

        GCName = fileToSave + "_Deg_GCPlot_%d.png" % (i)
        GBCName = fileToSave + "_Deg_GBCPlot_%d.png" % (i)

        plt.savefig(GCName)
        plt.clf()

        try:
            fig, ax = ox.plot_graph(G, fig_height=30, fig_width=30)
        except:
            break

        for n in GBCnodes:
            dictInfo = G.node[n]
            ax.scatter(dictInfo['x'], dictInfo['y'], c='red')

        plt.savefig(GBCName)
        plt.clf()

        startIndex = counter * numToRemove
        endIndex = startIndex + numToRemove

        nodesToRemove = order[startIndex:endIndex]

        G.remove_nodes_from(nodesToRemove)

        counter = counter + 1
Пример #31
0
def wkt_to_graph(wkt_list, im_file, conf, out_graph_file):
    min_subgraph_length_pix = 300
    verbose = False
    super_verbose = False
    make_plots = False
    save_shapefiles = False
    pickle_protocol = 4

    if (len(wkt_list) == 0) or (wkt_list[0] == 'LINESTRING EMPTY'):
        return None

    try:
        G = wkt_to_G(wkt_list,
                     im_file=im_file,
                     min_subgraph_length_pix=min_subgraph_length_pix,
                     verbose=super_verbose)
        if len(G.nodes()) == 0:
            return None
    except Exception as e:
        print('Exception in wkt_to_G: {}, {}'.format(str(e), out_graph_file))
        return None

    node = list(G.nodes())[-1]
    if verbose:
        print(node, 'random node props:', G.nodes[node])

    # print an edge
    edge_tmp = list(G.edges())[-1]
    if verbose:
        print(edge_tmp, "random edge props:",
              G.edges([edge_tmp[0],
                       edge_tmp[1]]))  #G.edge[edge_tmp[0]][edge_tmp[1]])

    nx.write_gpickle(G, out_graph_file, protocol=pickle_protocol)

    # save shapefile as well?
    if save_shapefiles:
        ox.save_graph_shapefile(G,
                                filename=image_id.split('.')[0],
                                folder=graph_dir,
                                encoding='utf-8')

    # plot, if desired
    if make_plots:
        outfile_plot = 'debug_ox.png'
        if verbose:
            print("Plotting graph...")
            print("outfile_plot:", outfile_plot)
        ox.plot_graph(
            G,
            fig_height=9,
            fig_width=9,
            #save=True, filename=outfile_plot, margin=0.01)
        )
        #plt.tight_layout()
        plt.savefig(outfile_plot, dpi=400)
Пример #32
0
place_names = ['Ho Chi Minh City, Vietnam',
               #'Beijing, China', 
               #'Jakarta, Indonesia',
               'London, UK',
               'Los Angeles, California, USA',
               'Manila, Philippines',
               #'Mexico City, Mexico',
               'New Delhi, India',
               'Sao Paulo, Brazil',
               'New York, New York, USA',
               'Seoul',
               'Singapore',
               #'Tokyo, Japan',
               #'Nairobi, Kenya',
               #'Bangalore, India'
              ]
              
# In this for-loop, we save all the shapefiles for the valid cities.
for city in place_names:  
    city_admin_20kmbuff = ox.gdf_from_place(city, gdf_name = 'global_cities', buffer_dist = 20000)
    fig, ax = ox.plot_shape(city_admin_20kmbuff)
    ox.save_gdf_shapefile(city_admin_20kmbuff, filename = city)
    
# In this for-loop, we save all the street networks for the valid cities.
for city in place_names:
    grid = ox.graph_from_place(city, network_type = 'drive', retain_all = True)
    grid_projected = ox.project_graph(grid)
    ox.save_graph_shapefile(grid_projected, filename = city + '_grid')
    ox.plot_graph(grid_projected)