#!/usr/bin/env python # coding: utf-8 # -------------------------- # ### If any part of this notebook is used in your research, please cite with the reference found in [`README.md`](https://github.com/pysal/spaghetti#bibtex-citation). # --------------------- # # Snapping point to segments # In[1]: import os last_modified = None if os.name == "posix": last_modified = get_ipython().getoutput('stat -f "# This notebook was last updated: %Sm" Snapping_Demonstration.ipynb') elif os.name == "nt": last_modified = get_ipython().getoutput('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: Nov 12 12:30:17 2019 # ------------------------------- # In[2]: import numpy as np from libpysal import examples import geopandas as gpd import spaghetti as spgh from shapely.geometry import Point get_ipython().run_line_magic('matplotlib', 'inline') __author__ = 'James Gaboardi ' # ----------------------------------------- # ## Segments # In[3]: streets = examples.get_path("streets.shp") streets = gpd.read_file(streets) # ## Points # In[4]: 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[5]: base = streets.plot(figsize=(10,10), color='k', alpha=.35, linewidth=3) crimes.plot(ax=base, cmap='tab20', markersize=75) # # Network # In[6]: net = spgh.Network(in_data=streets) # ## Snap point onto nearest segments # In[7]: net.snapobservations(crimes, 'crimes') # ## Create `geopandas.GeoDataFrame` objects of snapped points # In[8]: snapped_gdf = spgh.element_as_gdf(net, pp_name='crimes', snapped=True) # ## Original point coordinates, snapped point coordinates # In[9]: original = net.pointpatterns['crimes'].points print(original[0]['coordinates'], snapped_gdf.geometry[0].coords[:]) # ## Snapped points plot # In[10]: 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) # ---------------------------------------------