Skip to content

GeoPandas Workflow ​

Load a GeoDataFrame directly with GeoJSON.from_geopandas(), combine it with inline point data, and render a linked map and chart from Python.

Python Script ​

python
"""GeoPandas workflow — load polygons, filter points, spatial-join, then visualize the result.

Requires the optional ``geopandas`` and ``pandas`` dependencies.
"""
from __future__ import annotations

from pathlib import Path

import pyautark as ak

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

def _load_processed_data() -> tuple[object, object]:
    try:
        import geopandas as gpd
        import pandas as pd
    except ModuleNotFoundError as exc:
        raise RuntimeError(
            "This example requires pandas and geopandas."
        ) from exc

    neighborhoods = gpd.read_file(DATA_DIR / "neighborhoods.geojson")
    if neighborhoods.crs is None:
        neighborhoods = neighborhoods.set_crs("EPSG:4326")

    trees_df = pd.read_csv(DATA_DIR / "trees.csv")
    focus_species = {"oak", "maple", "elm"}
    trees_df = trees_df[trees_df["species"].isin(focus_species)].copy()
    trees_df["species_rank"] = trees_df["species"].map({"oak": 3, "maple": 2, "elm": 1}).astype(int)

    trees = gpd.GeoDataFrame(
        trees_df,
        geometry=gpd.points_from_xy(trees_df["longitude"], trees_df["latitude"]),
        crs="EPSG:4326",
    )

    joined = gpd.sjoin(
        trees[["id", "species", "species_rank", "geometry"]],
        neighborhoods[["name", "geometry"]],
        how="left",
        predicate="within",
    )
    counts = (
        joined.dropna(subset=["name"])
        .groupby("name")
        .agg(tree_count=("id", "count"), avg_species_rank=("species_rank", "mean"))
        .reset_index()
    )

    neighborhoods = neighborhoods.merge(counts, on="name", how="left")
    neighborhoods["tree_count"] = neighborhoods["tree_count"].fillna(0).astype(int)
    neighborhoods["avg_species_rank"] = neighborhoods["avg_species_rank"].fillna(0.0)
    neighborhoods = neighborhoods[neighborhoods["tree_count"] > 0].copy()

    return neighborhoods, trees

neighborhoods_gdf, trees_gdf = _load_processed_data()

neighborhoods = ak.GeoJSON.from_geopandas("neighborhoods", neighborhoods_gdf, layer_type="polygons")
trees = ak.GeoJSON.from_geopandas("trees", trees_gdf, layer_type="points")

spec = ak.Spec(
    metadata=ak.Metadata(
        title="GeoPandas Neighborhood Tree Counts",
        description=(
            "Load neighborhoods with GeoPandas, filter trees with pandas, "
            "compute per-neighborhood counts, and visualize the result."
        ),
    ),
    data=[neighborhoods, trees],
    views=[
        ak.Map(
            camera=ak.Camera(zoom=13),
            layers=[
                ak.Layer(neighborhoods, id="neighborhoods_layer")
                .encode(
                    color=ak.field(
                        "tree_count",
                        scale=ak.Scale(type="quantile", scheme="greens"),
                    )
                )
                .style(opacity=0.75, strokeColor="#243b53"),
                ak.Layer(trees, id="trees_layer").style(
                    color="#1f9d55", opacity=0.85
                ),
            ],
        ),
        ak.Histogram(
            source=neighborhoods,
            x="tree_count",
            bins=8,
        ),
    ],
    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.