Skip to content

Spatial Join ​

Count point events inside each neighborhood with ak.SpatialJoin, color neighborhoods by count, and link a histogram brush to the map.

Python Script ​

python
"""Spatial join — count trees per neighborhood, then link a histogram brush back to the map."""
from __future__ import annotations

import json
from pathlib import Path

import pyautark as ak

DATA_DIR = Path(__file__).resolve().parents[1] / "data"

with (DATA_DIR / "neighborhoods.geojson").open(encoding="utf-8") as f:
    neighborhoods_data = json.load(f)

neighborhoods = ak.GeoJSON(
    "neighborhoods",
    values=neighborhoods_data,
    layer_type="polygons",
    coordinate_format="EPSG:4326",
)
trees = ak.CSV(
    "trees",
    url=(DATA_DIR / "trees.csv").as_uri(),
    geometry=ak.latlng("latitude", "longitude", coordinate_format="EPSG:4326"),
)
brush = ak.interval("tree_count_brush")

spec = ak.Spec(
    metadata=ak.Metadata(title="Spatial Join — Trees per Neighborhood"),
    data=[neighborhoods, trees],
    transforms=[
        ak.SpatialJoin(
            root=neighborhoods,
            join=trees,
            group_by=[ak.count(), ak.collect("species")],
        )
    ],
    views=[
        ak.Map(
            camera=ak.Camera(zoom=12),
            layers=[
                ak.Layer("neighborhoods", id="neighborhoods_layer")
                .encode(
                    color=ak.field(
                        "properties.sjoin.count.trees",
                        scale=ak.Scale(type="quantile", scheme="greens", domain_strategy="minMax"),
                    )
                )
                .style(opacity=0.8, strokeColor="#333333"),
                ak.Layer(trees, id="trees_layer").style(
                    color="#228B22", opacity=0.6
                ),
            ],
        ),
        ak.Histogram(
            source=neighborhoods,
            x="sjoin.count.trees",
            bins=20,
            selection=brush,
        ),
    ],
    links=[ak.Link(brush, target="neighborhoods_layer", action="highlight")],
    layout=ak.Layout(type="vertical"),
)

if __name__ == "__main__":
    spec.window(height="760px")

Run in Jupyter or standalone HTML

Replace spec.window(...) with spec.widget() inside a Jupyter notebook (requires pip install "pyautark[widget]") or spec.save_html("out.html") to export a standalone web page.

This example comes from the pyautark repository.

Released under the MIT License.