Topological relationships, distance, spatial joins and aggregation
Emanuel Goulart — today
Prefer to run everything in a notebook instead of following along on the site? opens this notebook in Colab.
Spatial Analysis of Vector Data
This notebook explores the spatial operations used most often day to day, such as topological relationships, distance, spatial joins, aggregation, zoning and geometric transformations.
For our case study we will use the city of Sinop in Mato Grosso, combining two data sources:
geobr — schools (INEP) and health facilities (CNES): official, already geolocated data.
OpenStreetMap (via osmnx) — the road network, to explore intersections and connectivity.
We picked Sinop arbitrarily: it is a mid-sized city, far from the Rio–São Paulo axis that dominates most GIS examples out there. Feel free to swap the code_muni below for your own city and run everything again.
Code
code_muni =5107909# Sinop, MTCRS_PROJETADO ="EPSG:31981"# SIRGAS2000 / UTM zone 21S sinop = geobr.read_municipality(code_muni=code_muni, year=2020)schools = geobr.read_schools(year=2020, code_muni=code_muni)health = geobr.read_health_facilities(date=202304, code_muni=code_muni)# Let's project them right away to our UTM zone 21Scode_muni =5107909# Sinop, MTCRS_PROJETADO ="EPSG:31981"# SIRGAS2000 / UTM zone 21S sinop_proj = sinop.to_crs(CRS_PROJETADO)schools_proj = schools.to_crs(CRS_PROJETADO)health_proj = health.to_crs(CRS_PROJETADO)print(f"{len(schools)} schools, {len(health)} health facilities")
import foliumm = folium.Map( location=[sinop.iloc[0].geometry.centroid.y, sinop.iloc[0].geometry.centroid.x], zoom_start=12)folium.GeoJson( sinop, name="Municipal boundary", style_function=lambda _: {"fillOpacity": 0, "color": "#333333", "weight": 2},).add_to(m)rede_map = {1: "Federal", 2: "Estadual", 3: "Municipal", 4: "Privada"}cores_rede = {1: "#2a78d6", 2: "#e63946", 3: "#2a9d8f", 4: "#f4a261"}schools_map = schools.copy()schools_map["rede"] = schools_map["tp_dependencia"].map(rede_map)# here we add the schools to folium folium.GeoJson( schools_map, name="Schools (INEP data)", marker=folium.CircleMarker(radius=6, fill=True), style_function=lambda feat: {"fillColor": cores_rede.get(feat["properties"]["tp_dependencia"], "#999999"),"color": "white","weight": 0.6,"fillOpacity": 0.8, }, tooltip=folium.GeoJsonTooltip( fields=["name_school", "rede"], aliases=["School:", "Network:"], localize=True, ),).add_to(m)# CNES tp_unidade covers dozens of codes. We mapped (Claude mapped) the ones that appear in Sinop to their descriptionstipo_unidade_map = {2: "Centro de Saúde/UBS", 4: "Policlínica", 5: "Hospital Geral",22: "Consultório Isolado", 36: "Clínica/Centro de Especialidade",39: "SADT Isolado", 40: "Unidade Móvel Pré-Hospitalar", 43: "Farmácia",50: "Vigilância Epidemiológica", 68: "Central de Notificação/Regulação",69: "Central de Regulação Médica de Urgências", 70: "Central de Regulação do Acesso",72: "Centro de Atenção Psicossocial", 73: "Centro de Apoio à Saúde da Família",74: "Pronto Atendimento", 77: "Central de Regulação de Alta Complexidade",80: "Laboratório de Saúde Pública", 81: "Central de Gestão em Saúde",84: "Central de Abastecimento", 85: "Centro de Imunização",}# a map function to go from code to health facility type namehealth_map = health.copy()health_map["tipo"] = health_map["tp_unidade"].map(tipo_unidade_map).fillna("Outro")folium.GeoJson( health_map, name="Health (CNES)", marker=folium.CircleMarker(radius=4, fill=True), style_function=lambda _: {"fillColor": "#2a78d6","color": "white","weight": 0.6,"fillOpacity": 0.6, }, tooltip=folium.GeoJsonTooltip( fields=["no_fantasia", "tipo"], aliases=["Facility:", "Type:"], localize=True, ),).add_to(m)folium.LayerControl().add_to(m)m
Make this Notebook Trusted to load map: File -> Trust Notebook
Geometric Operations
Geometric operations are a set of methods used to analyze and process geometric features. They help answer how two or more geographic objects relate to each other: do they overlap? do they touch? do they intersect? how far apart are they?
Centroid
The centroid is the center of mass of a geometry, be it a line, a polygon or a geometry collection. Extracting the centroid is useful in many cases, for example to place labels on a figure, or as the basis for spatial operations with other polygons. If you compute the centroid in an unprojected CRS, GeoPandas still does it but warns you that the result may be wrong: a degree is not a uniform unit of distance, so a “center of mass” computed directly in lat/lon is slightly offset from the real geometric center. The data need to be in a projected coordinate system (UTM, for example) for this calculation to really make sense.
Code
centroide_sinop = sinop_proj.geometry.centroid.iloc[0]centro_escolas = schools_proj.geometry.union_all().centroid# back to the geographic CRS just to plot with everything elsecentroide_sinop_geo = gpd.GeoSeries([centroide_sinop], crs=CRS_PROJETADO).to_crs(sinop.crs).iloc[0]centro_escolas_geo = gpd.GeoSeries([centro_escolas], crs=CRS_PROJETADO).to_crs(sinop.crs).iloc[0]fig, ax = plt.subplots(figsize=(7, 7))sinop.plot(ax=ax, color="#f0f0f0", edgecolor="#898781", linewidth=0.8)schools.plot(ax=ax, markersize=6, color="#e63946", alpha=0.35, label="Schools (INEP)")ax.scatter(centroide_sinop_geo.x, centroide_sinop_geo.y, marker="*", s=280, color="#2a78d6", edgecolor="black", linewidth=0.5, zorder=5, label="Municipality centroid")ax.scatter(centro_escolas_geo.x, centro_escolas_geo.y, marker="^", s=140, color="#e63946", edgecolor="black", linewidth=0.5, zorder=5, label="Center of the schools")ax.legend(loc="lower left")ax.set_title("Centroid vs. geometric center of the distribution", fontsize=12, fontweight="bold")ax.set_axis_off()plt.show()
Figure 1: Centroid of the Sinop polygon (star) and geometric center of the school distribution (triangle) – both computed in a projected CRS.
Code
muni = geobr.read_municipality(year=2020)# projecting to SIRGAS 2000 UTM 23Smuni = muni.to_crs('EPSG:31983')muni_mt = muni.loc[muni['abbrev_state']=='MT']## project to UTM 22Smuni_mt['centroide'] = muni_mt.geometry.centroidfig, ax = plt.subplots(figsize=(7,7))muni_mt.plot(ax=ax)muni_mt.geometry.centroid.plot(ax=ax,color="#7c2b2b")ax.set_axis_off()ax.set_title('Municipalities of MT and their centroids')plt.show()
Figure 2: Centroids of the municipalities of Mato Grosso
Buffer
A buffer is a geometric operation that creates a zone around a given geometry, usually representing a distance (coverage radius, safety zone, area of influence). Combining buffers with intersection answers questions like “which areas are covered more than once?” — for example, is there any place in Sinop within 1 km of two schools at the same time?
Code
buffers = schools_proj[["code_school", "geometry"]].copy()buffers["geometry"] = buffers.buffer(1000) # 1 km radius# intersect the buffers with themselves; code_school_1 < code_school_2 avoids# counting a buffer's intersection with itself and duplicating each pair (A∩B == B∩A)pares = gpd.overlay(buffers, buffers, how="intersection")pares = pares[pares["code_school_1"] < pares["code_school_2"]]cobertura_dupla = pares.union_all()# zoom into the region where the overlaps happen, instead of the whole municipality (~60 km)# minx, miny, maxx, maxy = cobertura_dupla.bounds# folga = 1500fig, ax = plt.subplots(figsize=(7, 7))sinop_proj.plot(ax=ax, color="#f0f0f0", edgecolor="#898781", linewidth=0.8)buffers.plot(ax=ax, color="#2a78d6", alpha=0.15, edgecolor="#2a78d6", linewidth=0.4)gpd.GeoSeries([cobertura_dupla], crs=CRS_PROJETADO).plot(ax=ax, color="#e63946", alpha=0.6)schools_proj.plot(ax=ax, markersize=8, color="black")# ax.set_xlim(minx - folga, maxx + folga)# ax.set_ylim(miny - folga, maxy + folga)ax.set_title(f"{len(pares)} pairs of schools with overlapping buffers (1 km radius)", fontsize=11, fontweight="bold")ax.set_axis_off()plt.show()
Figure 3: 1 km buffer around each school in Sinop’s urban core. In red, the areas covered by two or more schools at the same time.
Code
schools_buffer_geo = buffers.to_crs("EPSG:4326")health_buffers = health_proj[["co_cnes", "no_fantasia", "geometry"]].copy()health_buffers["geometry"] = health_buffers.buffer(1000) # 1 km radiushealth_buffers_geo = health_buffers.to_crs("EPSG:4326")## create a new folium map m = folium.Map( location=[sinop.iloc[0].geometry.centroid.y, sinop.iloc[0].geometry.centroid.x], zoom_start=13,)buffers_geo = buffers.to_crs("EPSG:4326") # reprojecting to WGS84 - GEOGRAPHICfolium.GeoJson( buffers_geo, name="Buffers (1 km)", style_function=lambda _: {"fillColor": "#2a78d6", "color": "#2a78d6", "weight": 0.5, "fillOpacity": 0.15, },).add_to(m)# here we add the schools to folium folium.GeoJson( schools_map, name="Schools (INEP data)", marker=folium.CircleMarker(radius=6, fill=True), style_function=lambda feat: {"fillColor": cores_rede.get(feat["properties"]["tp_dependencia"], "#999999"),"color": "white","weight": 0.6,"fillOpacity": 0.8, }, tooltip=folium.GeoJsonTooltip( fields=["name_school", "rede"], aliases=["School:", "Network:"], localize=True, ),).add_to(m)folium.LayerControl().add_to(m)m
Make this Notebook Trusted to load map: File -> Trust Notebook
Union and Dissolve
Some operations merge geometries, or dissolve them to a level of aggregation to form new ones. You can dissolve city geometries to form a state or region, for example. Looking closely, union_all() merges all geometries into a single geometry, without looking at any attribute. dissolve(by=...) does the same merge under the hood, but first groups the rows by the given attribute. Both functions take a method parameter: "unary" (the default: robust, works even with overlapping geometries) or "coverage", which is much faster but only valid for polygons that already form a non-overlapping coverage, like neighboring administrative boundaries. If you use CAR (rural property) geometries here, you’ll be in trouble.
Code
dependencia_map = {1: "Federal", 2: "Estadual",3: "Municipal", 4: "Privada"}schools_proj["rede"] = schools_proj["tp_dependencia"].map(dependencia_map)influencia = schools_proj[["rede", "geometry"]].copy()influencia["geometry"] = influencia.buffer(400)uniao_total = influencia.union_all()# dissolving by school typedissolve_por_rede = influencia.dissolve(by="rede").reset_index()# the buffers (400 m) vanish in a figure of the whole municipality (~60 km) --# so we zoom into the largest blob from the union, in the city center (where most points are), which is exactly the dense# urban core (isolated rural schools become tiny separate circles)maior_blob =max(uniao_total.geoms, key=lambda g: g.area)minx, miny, maxx, maxy = maior_blob.boundsfolga =500fig, axes = plt.subplots(1, 2, figsize=(13, 6))for ax in axes: sinop_proj.plot(ax=ax, color="#f0f0f0", edgecolor="#898781", linewidth=0.6) ax.set_xlim(minx - folga, maxx + folga) ax.set_ylim(miny - folga, maxy + folga) ax.set_axis_off()gpd.GeoSeries([uniao_total], crs=CRS_PROJETADO).plot(ax=axes[0], color="#e63946", alpha=0.6)axes[0].set_title("Union All")dissolve_por_rede.plot(ax=axes[1], column="rede", categorical=True, cmap="Set2", alpha=0.75, legend=True, legend_kwds={"title": "Network", "loc": "lower left"})axes[1].set_title("Dissolve by School Type")plt.tight_layout()plt.show()
Figure 4: Area of influence (400 m buffer) of each school in Sinop’s urban core. Left: union_all() merges everything into a single geometry. Right: dissolve(by=‘rede’) groups before merging, preserving the school network (federal, state, municipal, private).
The convex hull is the smallest convex polygon that contains all the points of a set. Imagine stretching a rubber band around all the points and letting it shrink until it only touches the outermost ones. Let’s illustrate this with the school locations in Sinop.
Figure 5: Convex hull of Sinop’s schools: the smallest convex polygon that contains all the points.
Topological relationships
Topological relationships describe how two geometries relate in space: intersects (touches in any way), within (is completely inside), touches (only touches at the boundary, without overlapping), disjoint (no relationship at all). Note that intersects is symmetric (if X intersects Y, Y intersects X), but within/contains are not.
Let’s use this to classify Sinop’s schools as urban (within a radius of the center) and rural (outside it).
Code
# setting a point at the center of Sinopcentro = gpd.GeoSeries( [gpd.points_from_xy([-55.5089], [-11.8642])[0]], crs="EPSG:4326").to_crs(CRS_PROJETADO)area_urbana = centro.buffer(5000).iloc[0] # 5 km, already in meters## here is the topological analysis## if the school is within the urban area (our 5 km buffer) it is urban ("urbana"), otherwise rural schools_proj["zona"] = np.where(schools_proj.within(area_urbana), "urbana", "rural")# print the number of schools in each zone print(schools_proj["zona"].value_counts())
zona
urbana 66
rural 12
Name: count, dtype: int64
Code
## Now let's plot fig, ax = plt.subplots(figsize=(7, 7))# municipal boundary sinop.plot(ax=ax, color="#f0f0f0", edgecolor="#898781", linewidth=0.8)# area_urbana is a "plain" shapely Polygon, not a GeoDataFrame# so it has no .plot(); and it is in CRS_PROJETADO (meters), so we reproject it back# to the geographic CRS of sinop/schools/health before plotting, otherwise the scales won't matcharea_urbana_geo = gpd.GeoSeries([area_urbana], crs=CRS_PROJETADO).to_crs(sinop.crs).iloc[0]# the trick for when it is not GeoPandas (or convert it to GeoPandas)ax.fill(*area_urbana_geo.exterior.xy, color="#cdea0eb9", edgecolor="#d4caa7", linewidth=0.6)health.plot(ax=ax, markersize=6, color="#2a78d6", alpha=0.5, label="Health (CNES)")schools.plot(ax=ax, markersize=10, color="#e63946", alpha=0.8, label="Schools (INEP)")ax.legend(loc="lower left")ax.set_title("Sinop, MT", fontsize=12, fontweight="bold")ax.set_axis_off()plt.show()
Don’t fall behind!
If you’re not comfortable with topological relationships yet, take a look at our Python+GIS classes, where we go through these relationships much more slowly and in depth: Class 1 and Class 2. Python+GIS
Affine transformations
Rotation, scaling, translation and shearing: operations that distort a geometry without recomputing anything from the original data, just by applying a matrix to the existing geometry. Useful for adjusting misaligned geometries, or simply for understanding what each operation does:
Figure 6: The same geometry (Sinop’s boundary): original, rotated 45° and scaled by half, always around its own center.
Distance relationships
Unlike topological relationships, which are boolean by nature (true/false), distance relationships are continuous. There are also some nuances to consider depending on the type of vector we are analyzing. The distance between two points is, of course, the famous Euclidean distance, well-trodden ground in linear algebra.
Source:Wikipedia - Euclidean Distance
However, when we look at the distance between two lines, or between a point and a polygon, the nuance kicks in. We take the distance between a point and a polygon to be the distance between their closest parts.
Source:Arcgis - Arcmap Documentation
Hands on:
what is the distance from each school to the nearest health facility?
Code
## Important: note the reduction using the minimumdist_para_saude = schools_proj.geometry.apply(lambda pt: health_proj.distance(pt).min())print(f"Mean distance to the nearest health facility: {dist_para_saude.mean():.0f} m")print(f"Most isolated school: {dist_para_saude.max():.0f} m")print(f"Closest school: {dist_para_saude.min():.0f} m")
Distância média até a saúde mais próxima: 732 m
Escola mais isolada: 16743 m
Escola mais proxima: 2 m
# gpd.sjoin joins attributes based on a spatial relationship (the within predicate here),saude_buffers = health_proj[["no_fantasia", "geometry"]].copy()saude_buffers["geometry"] = saude_buffers.buffer(1000) # 1 km coverage radiusescolas_cobertas = gpd.sjoin(schools_proj, saude_buffers, predicate="within")print(f"{escolas_cobertas['code_school'].nunique()} of {len(schools_proj)} schools are "f"within the coverage radius of at least one health facility")escolas_cobertas[["name_school", "no_fantasia"]].head()
74 de 78 escolas estão dentro do raio de cobertura de pelo menos um estabelecimento de saúde
name_school
no_fantasia
0
ESCOLA CENECISTA SANTA ELISABETE
SINOP MED
0
ESCOLA CENECISTA SANTA ELISABETE
CARRERA
0
ESCOLA CENECISTA SANTA ELISABETE
SOMA PSICOLOGIA
0
ESCOLA CENECISTA SANTA ELISABETE
G S SERVICOS MEDICOS
0
ESCOLA CENECISTA SANTA ELISABETE
AGENCIA TRANSFUSIONAL HEMOSAN SINOP
Spatial joins by distance
A spatial join works like an attribute join (familiar ground if you know relational tables), except that the join criterion is a spatial relationship instead of a shared key. sjoin_nearest answers the question from the previous section, but returns a GeoDataFrame, with the option of limiting it to a maximum radius (max_distance), which is useful to avoid joining points that are too far apart to make sense:
Spatial aggregation summarizes values of one object (the “target”) by grouping them by the geometry of another (the “source”). The source geometry defines the groups, and the result inherits its geometry, not the target’s. Let’s aggregate by the simplest grouping we already have: urban vs. rural.
Code
resumo_zona = ( schools_com_saude .groupby("zona") .agg( n_escolas=("code_school", "count"), dist_media_saude=("dist_saude_mais_proxima", "mean"), dist_max_saude=("dist_saude_mais_proxima", "max"),# add the minimum distance here ) .round(0))resumo_zona
n_escolas
dist_media_saude
dist_max_saude
zona
rural
10
979.0
4790.0
urbana
98
185.0
774.0
Nearest Neighbors
Nearest neighbors start to address an important point of spatial data analysis: how a point relates to its neighbors.
This comes from the idea behind Tobler’s First Law of Geography.
The First Law of Geography
“Everything is related to everything else, but near things are more related than distant things.” — Waldo Tobler, 1970
This sentence, now known as Tobler’s First Law of Geography, is basically the reason why “proximity” is one of the most basic (and most useful) questions you can ask about spatial data. “Which point is closest?” seems trivial, but it underpins things like: which school serves this neighborhood, where is the bus stop closest to home, how well distributed is a public service across the city.
Sinop has few bus stops mapped in OpenStreetMap, which is common in smaller/newer cities where collaborative mapping of public transport is still sparse. For this nearest neighbor analysis we need a denser set of bus stops, so we switch to Maceió, Alagoas, keeping the schools from geobr.
Code
CRS_PROJETADO ="EPSG:31985"# SIRGAS2000 / UTM zone 25S - Maceió, ALcode_muni =2704302# Maceió, ALmaceio = geobr.read_municipality(code_muni=code_muni, year=2020)escolas = geobr.read_schools(year=2020, code_muni=code_muni)# bus stops, straight from OSM, inside the municipality polygonpontos_onibus = ox.features_from_polygon(maceio.iloc[0].geometry, tags={"highway": "bus_stop"})pontos_onibus = pontos_onibus[pontos_onibus.geom_type =="Point"].reset_index(drop=True)print(f"{len(pontos_onibus)} bus stops, {len(escolas)} schools")
Figure 7: Maceió, AL: bus stops (OSM) and schools (INEP/geobr).
The nearest neighbor
Before using any ready-made function, it’s worth understanding what “nearest neighbor” really means: for one bus stop, compute the distance to all schools and take the smallest.
Code
onibus_proj = pontos_onibus.to_crs(CRS_PROJETADO)escolas_proj = escolas.to_crs(CRS_PROJETADO)# take only the first pointum_ponto = onibus_proj.geometry.iloc[0]# compute the distance from every school to this pointdistancias = escolas_proj.geometry.distance(um_ponto)print(f"Closest school to this bus stop: {distancias.min():.0f} m")print(f"Farthest school from this same stop: {distancias.max():.0f} m")
Escola mais próxima desse ponto de ônibus: 201 m
Escola mais distante desse mesmo ponto: 17994 m
For one point it’s easy. Now how do we do this for all bus stops, one at a time against every school? Sounds like brute force, right?
Code
t0 = time.time()resultado_forca_bruta = [ escolas_proj.geometry.distance(pt).min() for pt in onibus_proj.geometry]tempo_forca_bruta = time.time() - t0print(f"Brute force: {tempo_forca_bruta:.3f} s for {len(onibus_proj)}×{len(escolas_proj)} comparisons")print(f"\nMean distance to the nearest school: {round(np.mean(resultado_forca_bruta))}")
Força bruta: 0.022 s para 239×556 comparações
Distância média até a escola mais próxima: 282
At this size it’s still fast, but notice that doubling the bus stops and doubling the schools quadruples the work. For whole cities, with hundreds of thousands of features, this becomes a real problem.
So let’s compute the same result more efficiently with sjoin_nearest, which uses a spatial index.
GeoPandas handles this spatial index structure (an R-tree, called STRtree under the hood): instead of comparing against everyone, it organizes the geometries in a way that lets it discard whole regions of space at once, without even computing the distance to them.
sjoin_nearest: 0.011 s
Distância média até a escola mais próxima: 282 m
Same result as the brute-force search, in half the time. Here we only did it for 500 points; imagine 1 million bus stops.
NoteTies and duplicates
When two schools are at exactly the same distance from a bus stop, sjoin_nearest returns both, so the result can have more rows than the original onibus_proj. It’s always worth checking:
Code
duplicatas = onibus_com_escola.index.duplicated().sum()print(f"Bus stops with more than one school tied as 'nearest': {duplicatas}")
Pontos de ônibus com mais de uma escola empatada como 'mais próxima': 0
Visualizing these nearest neighbors
A direct way to visually check whether the result makes sense is to draw a line from each bus stop to its nearest school. sjoin_nearest only returns the index of the matched school (index_right), so to draw the line to it we need to fetch its geometry back with a merge.
Code
escolas_proj[["geometry"]]
geometry
0
POINT (199543.637 8932250.319)
1
POINT (199427.746 8936482.908)
2
POINT (201121.503 8930934.686)
3
POINT (199307.603 8932927.969)
4
POINT (201341.767 8933549.947)
...
...
551
POINT (201503.821 8944178.511)
552
POINT (198951.231 8931750.787)
553
POINT (196048.017 8944279.171)
554
POINT (198324.469 8942956.51)
555
POINT (199848.114 8944129.299)
556 rows × 1 columns
Code
# sjoin_nearest only returns the index of the school; # we fetch its geometry back with a merge, which creates geometry_x (bus stop) and geometry_y (school)onibus_com_geom_escola = onibus_com_escola.merge( escolas_proj[["geometry"]], left_on="index_right", right_index=True, suffixes=("_x", "_y"))# here we use a shapely function that creates a line between two geometries from shapely import shortest_lineconectores = onibus_com_geom_escola.apply(lambda row: shortest_line(row["geometry_x"], row["geometry_y"]), axis=1)# finally we build a GeoDataFrame with the connectors, using the same projection conectores = gpd.GeoDataFrame({"geometry": conectores}, crs=onibus_proj.crs)conectores["distancia"] = conectores.lengthconectores.head()
geometry
distancia
0
LINESTRING (199446.742 8934817.855, 199295.492...
201.005749
1
LINESTRING (200672.189 8930874.292, 200615.906...
126.463200
2
LINESTRING (202608.369 8936565.816, 201839.145...
921.848474
3
LINESTRING (193240.989 8944733.572, 193756.381...
728.890882
4
LINESTRING (200881.882 8933047.242, 200764.686...
366.099030
Code
fig, ax = plt.subplots(figsize=(8, 8))maceio.to_crs(CRS_PROJETADO).plot(ax=ax, color="#f7f7f5", edgecolor="#898781", linewidth=1)conectores.plot(ax=ax, color="#457b9d", linewidth=0.5, alpha=0.6)onibus_proj.plot(ax=ax, markersize=4, color="#2a78d6")escolas_proj.plot(ax=ax, markersize=8, color="#e63946")ax.set_title("Nearest bus stops to each school", fontsize=12, fontweight="bold")#ax.set_axis_off()ax.set_xlim(190000,210000)ax.set_ylim(8.925e6,8.950e6)plt.show()
Clustered or dispersed? The Nearest Neighbor Index
We can go beyond “which is the nearest neighbor” and ask: are the bus stops spread evenly across the area, or concentrated in a few places? The ESRI - Average Nearest Neighbor index (Clark & Evans, 1954) compares the observed mean distance between nearest neighbors with the mean distance we would expect if the points were scattered randomly (same density, random positions):
Where: - \(d_{expected}\) is the expected distance - \(d_{observed}\) is the observed distance - \(R < 1\) → the points are more clustered than expected by chance - \(R \approx 1\) → random pattern - \(R > 1\) → the points are more dispersed/uniform than expected by chance
We will compute this index only for our bus stop data; the schools are not involved. Our goal is to find out whether the bus stops are clustered, dispersed or random.
# Our observed distance is to the nearest neighbor of each bus stop # exclusive=True prevents each point from "matching" itself (distance 0) # without it, the nearest neighbor of any point would always be itself.dist_onibus_onibus = gpd.sjoin_nearest( onibus_proj, onibus_proj, distance_col="dist_vizinho", exclusive=True,)d_observado = dist_onibus_onibus["dist_vizinho"].mean()area_m2 = maceio.to_crs(CRS_PROJETADO).area.iloc[0]densidade =len(onibus_proj) / area_m2d_esperado =1/ (2* np.sqrt(densidade))R = d_observado / d_esperadoprint(f"Observed mean distance: {d_observado:.1f} m")print(f"Expected mean distance (random): {d_esperado:.1f} m")print(f"R index = {R:.2f} ")
Distância média observada: 204.4 m
Distância média esperada (aleatório): 730.9 m
Índice R = 0.28
K-Nearest Neighbors (KNN)
So far we have only looked for the nearest neighbor. But we often need more than that, for example “which are the 3 bus stops closest to this school?”.
Since each of them may offer different connections across the city, this search for the K nearest neighbors is called a KNN search (K-Nearest Neighbors).
GeoPandas’ sjoin_nearest uses an R-tree under the hood, and that structure only returns the nearest neighbor, not the K nearest. For that we use another spatial index structure, the KD-tree (K-dimensional tree), which is organized a bit differently from the R-tree and allows exactly this kind of search.
Code
from scipy.spatial import cKDTree# here we use numpy and arrays# first we stack the coordinatescoords_onibus = np.column_stack([onibus_proj.geometry.x, onibus_proj.geometry.y])coords_escolas = np.column_stack([escolas_proj.geometry.x, escolas_proj.geometry.y])# now we build the k-dimensional tree for the bus stops arvore = cKDTree(coords_onibus)# query the three nearest neighborsdistancias_k, indices_k = arvore.query(coords_escolas, k=3)print(f"3 bus stops closest to the first school: {distancias_k[0].round(0)} m")# question: what is the mean distance from a school to its 3 nearest bus stops?
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[4], line 5 1from scipy.spatial import cKDTree
2 3# aqui vamos usar numpy e definições de arrays 4# primeiro criamos uma stack----> 5 coords_onibus = np.column_stack([onibus_proj.geometry.x, onibus_proj.geometry.y])
6 coords_escolas = np.column_stack([escolas_proj.geometry.x, escolas_proj.geometry.y])
7 8# agora criamos a k-dimensional tree para os pontos de onibusNameError: name 'onibus_proj' is not defined
Code
# the school whose 3rd nearest neighbor is farthest away (just to zoom into a clearly visible case)i = distancias_k[:, -1].argmax()escola_exemplo = escolas_proj.geometry.iloc[i]vizinhos_exemplo = onibus_proj.geometry.iloc[indices_k[i]]fig, ax = plt.subplots(figsize=(7, 7))maceio.to_crs(CRS_PROJETADO).plot(ax=ax, color="#f7f7f5", edgecolor="#898781", linewidth=0.8)onibus_proj.plot(ax=ax, markersize=4, color="#2a78d6", alpha=0.3)vizinhos_exemplo.plot(ax=ax, markersize=60, color="#2a78d6", edgecolor="black", zorder=5)gpd.GeoSeries([escola_exemplo], crs=CRS_PROJETADO).plot(ax=ax, markersize=120, color="#e63946", marker="*", zorder=5)for p in vizinhos_exemplo: ax.plot([escola_exemplo.x, p.x], [escola_exemplo.y, p.y], color="#457b9d", linewidth=1)combinado = gpd.GeoSeries(list(vizinhos_exemplo) + [escola_exemplo])minx, miny, maxx, maxy = combinado.total_boundsfolga =300ax.set_xlim(minx - folga, maxx + folga)ax.set_ylim(miny - folga, maxy + folga)ax.set_title("The 3 bus stops closest to a school", fontsize=11, fontweight="bold")ax.set_axis_off()plt.show()
Heat Map
We have already seen two ways to describe “proximity”: the nearest neighbor (one value per point) and the R index (one number summarizing the whole pattern). The heat map (KDE) completes this progression by showing where, specifically, the concentration happens.
The heat map is a spatial distribution over the points: regions with more clustered points are denser than sparse regions.
For the formulation we use a Gaussian distribution, through SciPy’s gaussian_kde function (scipy.stats module).
This function uses a kernel to estimate the probability density function (PDF).
Imagine a bunch of points scattered over a plane. We can visually infer things about them, such as relative proximity, some sense of density, and a spatial sense of how they are distributed over the plane. Now imagine placing a smooth “hill” over each observed point. The KDE (Kernel Density Estimation) is the sum of all these hills: high where the observations concentrate, flat where they are sparse.
Where \(K\) is the kernel (the shape of the hill) and \(h\) is the bandwidth, how wide it spreads.
Code
import numpy as npimport matplotlib.pyplot as pltimport seaborn as sns# X coordinatesarr_x = escolas_proj.geometry.x.valuesplt.figure(figsize=(8, 5))sns.histplot( arr_x, bins=30, stat="density", kde=True, color="steelblue", alpha=0.4)plt.xlabel("X coordinate")plt.ylabel("Density")plt.title("Distribution with KDE of coordinates X")plt.show()# Y coordinatesarr_y = escolas_proj.geometry.y.valuesplt.figure(figsize=(8, 5))sns.histplot( arr_y, bins=30, stat="density", kde=True, color="darkorange", alpha=0.4)plt.xlabel("Y coordinate")plt.ylabel("Density")plt.title("Distribution with KDE of coordinates Y")plt.show()
The marginal distributions of the X and Y coordinates show how the schools are distributed along each spatial dimension individually. However, looking at these coordinates separately doesn’t tell us where the points concentrate in space, since the location of each facility depends on its X and Y coordinates at the same time.
To represent this spatial concentration we use Kernel Density Estimation (KDE) in two dimensions. Here, each school or bus stop is a pair of coordinates (X, Y), and the KDE estimates a continuous density surface from these points. Regions with a higher concentration of facilities have higher density values and show up as the hottest areas on the map.
So the one-dimensional distributions of X and Y serve as an introduction to the spatial structure of the data, while the two-dimensional KDE lets us visualize that structure considering both coordinates at once.
Figure 8: Density of schools and bus stops in Maceió (KDE) – hotter where the concentration is higher.
Code
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.neighbors import KernelDensityfig, axes = plt.subplots(1, 2, figsize=(13, 6))for ax, pontos, titulo inzip( axes, [escolas_proj, onibus_proj], ["Schools", "Bus stops"]):# Get X and Y coordinates: shape (N, 2) coords = np.column_stack([ pontos.geometry.x.values, pontos.geometry.y.values ])# Fit 2D Gaussian KDE kde = KernelDensity( bandwidth=500, kernel="gaussian", metric="euclidean" ) kde.fit(coords)# Spatial extent xmin, ymin, xmax, ymax = pontos.total_bounds# Create evaluation grid grid_x, grid_y = np.meshgrid( np.linspace(xmin, xmax, 200), np.linspace(ymin, ymax, 200) ) grid_coords = np.column_stack([ grid_x.ravel(), grid_y.ravel() ])# Estimate density log_density = kde.score_samples(grid_coords)# Convert log-density to density densidade_grid = np.exp(log_density).reshape(grid_x.shape)# Plot KDE ax.imshow( densidade_grid, cmap="inferno", alpha=0.85, extent=[xmin, xmax, ymin, ymax], origin="lower" )# Maceió boundary maceio.to_crs(CRS_PROJETADO).boundary.plot( ax=ax, color="white", linewidth=1 )# Original points pontos.plot( ax=ax, markersize=3, color="white", alpha=0.4 ) ax.set_title(f"Density of {titulo.lower()} (KDE)", fontsize=12, fontweight="bold" ) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_axis_off()plt.tight_layout()plt.show()
But is scipy the only way to build a heat map? Of course not. Let’s welcome our companion library, sklearn. Unlike the other function, sklearn uses a kernel density estimator that lets you try different kinds of kernels, giving us more flexibility than fitting only a Gaussian. On top of that, KernelDensity has a parameter called bandwidth that is essential for us: it defines how much influence neighboring points have on the density estimate.
Code
from sklearn.neighbors import KernelDensity# coords = np.column_stack([ escolas_proj.geometry.x.values, escolas_proj.geometry.y.values])# Spatial extentxmin, ymin, xmax, ymax = escolas_proj.total_bounds# first create a 2-dimensional grid (remember this KDE function works on a surface, not a 1D vector)grid_x, grid_y = np.meshgrid( np.linspace(xmin, xmax, 200), np.linspace(ymin, ymax, 200))# reshape the grid to match the input the function expectsgrid_coords = np.column_stack([ grid_x.ravel(), grid_y.ravel()])# bandwidths to comparebandwidths = [100, 500, 1000, 2000]fig, axes = plt.subplots(2, 2, figsize=(12, 10))for ax, bandwidth inzip(axes.ravel(), bandwidths):# create the estimator kde = KernelDensity( bandwidth=bandwidth, kernel="gaussian", metric="euclidean" )# fit kde.fit(coords)# Estimate density log_density = kde.score_samples(grid_coords) densidade_grid = np.exp(log_density).reshape(grid_x.shape)# Plot KDE ax.imshow( densidade_grid, cmap="inferno", alpha=0.85, extent=[xmin, xmax, ymin, ymax], origin="lower" )# Maceió boundary maceio.to_crs(CRS_PROJETADO).boundary.plot( ax=ax, color="white", linewidth=1 )# School locations escolas_proj.plot( ax=ax, markersize=3, color="white", alpha=0.4 ) ax.set_title(f"Bandwidth = {bandwidth} m", fontsize=12, fontweight="bold" ) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_title(f"Bandwidth = {bandwidth} m", fontsize=12, fontweight="bold") ax.set_axis_off()plt.tight_layout()plt.show()
The choice of bandwidth is an important part of KDE, since it sets the spatial scale at which the points are smoothed. Smaller bandwidths produce surfaces that are more sensitive to local concentrations, while larger values produce smoother surfaces that highlight larger-scale spatial patterns. To illustrate this effect, we estimated density surfaces for the schools with different bandwidth values. As the bandwidth increases, local concentrations are progressively smoothed out and nearby clusters merge into broader high-density regions.
So a heat map should be interpreted keeping in mind that the areas of highest concentration depend not only on the distribution of the facilities, but also on the spatial smoothing scale used to estimate the density.
The same idea can be done interactively with folium’s HeatMap plugin
Code
from folium.plugins import HeatMapm_calor = folium.Map( location=[maceio.iloc[0].geometry.centroid.y, maceio.iloc[0].geometry.centroid.x], zoom_start=12, tiles="OpenStreetMap",)HeatMap( [[pt.y, pt.x] for pt in escolas.geometry], name="Heat: schools", radius=12,).add_to(m_calor)HeatMap( [[pt.y, pt.x] for pt in pontos_onibus.geometry], name="Heat: bus stops", radius=12, gradient={0.2: "#2a78d6", 0.5: "#f4a261", 1: "#e63946"},).add_to(m_calor)folium.LayerControl().add_to(m_calor)m_calor
Make this Notebook Trusted to load map: File -> Trust Notebook
Road networks and graphs from OSM
Here is a brief demonstration of how to access OSM road network data.
OSM data
Let’s run some analyses related to Tobler’s idea using OpenStreetMap data. We will pull the real road network from OpenStreetMap around the center of Sinop with osmnx, which downloads it and returns a graph (networkx) ready for network analysis.
Before that, we need to define what a graph is.
“a Graph is a collection of nodes (vertices) along with identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can be any hashable object e.g., a text string, an image, an XML object, another Graph, a customized node object, etc.” Networkx package
Graphs also have attributes, just like GeoPandas’ geospatial tables.
Code
G = ox.graph_from_point((-11.8642, -55.5089), dist=2500, network_type="drive")# a function that converts these graphs into our old friend, the GeoDataFramenodes, edges = ox.graph_to_gdfs(G)print(f"{len(nodes)} nodes, {len(edges)} road segments")
Each node already comes with a street_count of how many streets meet there. That gives us intersections (street_count >= 3) and dead ends (street_count == 1) for free, without computing anything by hand:
Figure 9: Road network of central Sinop: real intersections (3+ roads) in orange, dead ends in blue.
Notice how the nearest neighbor R index and the heat map tell the same story in two different ways: one summarizes everything in a single number, the other shows where specifically the concentration happens.
From our spatial analysis, we conclude that in the municipality of Sinop, rural schools are, on average, much farther from the nearest health facility. On average, if an accident happens at school, rural schools are at least 700 meters farther from a health unit than schools in the urban area. This kind of analysis is possible when we bring together our knowledge of spatial data handling: topology, GeoPandas, transformations, projections, buffers, distance analysis and spatial aggregation.
Some questions remain: how can we analyze spatial densities and understand demand? Proximity?
The geospatial ecosystem lets us go much further, and we will look at this more closely in our next class.