Snapping point to segments


In [ ]:
import os
last_modified = None
if os.name == "posix":
    last_modified = !stat -f\
                    "# This notebook was last updated: %Sm"\
                     Snapping_Demonstration.ipynb
elif os.name == "nt":
    last_modified = !for %a in (Snapping_Demonstration.ipynb)\
                    do echo # This notebook was last updated: %~ta
    
if last_modified:
    get_ipython().set_next_input(last_modified[-1])

In [ ]:
# This notebook was last updated: May 13 20:04:46 2019


In [ ]:
import numpy as np
from pysal.lib import examples
import geopandas as gpd
from pysal.explore import spaghetti as spgh
from shapely.geometry import Point

%matplotlib inline

__author__ = 'James Gaboardi <jgaboardi@gmail.com>'

Segments


In [ ]:
streets = examples.get_path("streets.shp")
streets = gpd.read_file(streets)

Points


In [ ]:
crimes = examples.get_path("crimes.shp")
crimes = gpd.read_file(crimes)
np.random.seed(1)
crimes['geometry'] = np.random.permutation(crimes['geometry'])

Initial plot


In [ ]:
base = streets.plot(figsize=(10,10), color='k', alpha=.35, linewidth=3)
crimes.plot(ax=base, cmap='tab20', markersize=75)

Network


In [ ]:
net = spgh.Network(in_data=streets)

Snap point onto nearest segments


In [ ]:
net.snapobservations(crimes, 'crimes')

Create geopandas.GeoDataFrame objects of snapped points


In [ ]:
snapped_gdf = spgh.element_as_gdf(net, pp_name='crimes', snapped=True)

Original point coordinates, snapped point coordinates


In [ ]:
original = net.pointpatterns['crimes'].points
print(original[0]['coordinates'], snapped_gdf.geometry[0].coords[:])

Snapped points plot


In [ ]:
base = streets.plot(figsize=(10,10), color='k', alpha=.35, linewidth=3)
crimes.plot(ax=base, cmap='tab20', markersize=75)
snapped_gdf.plot(ax=base, cmap='tab20', markersize=30)