{"spec_id":"hexbin-map-geographic","library":"altair","language":"python","code":"\"\"\" anyplot.ai\nhexbin-map-geographic: Hexagonal Binning Map\nLibrary: altair 6.3.0 | Python 3.14.10\nQuality: 86/100 | Updated: 2026-11-27\n\"\"\"\n\nimport os\nimport sys\nfrom collections import Counter\n\n\n# Work around filename shadowing the altair library: drop this directory from the import path\n_here = os.path.dirname(os.path.abspath(__file__))\nsys.path[:] = [p for p in sys.path if os.path.abspath(p or os.getcwd()) != _here]\n\nimport altair as alt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nLAND_FILL = \"#E8E4DC\" if THEME == \"light\" else \"#2C2C28\"\nLAND_STROKE = \"#B0AFA8\" if THEME == \"light\" else \"#4A4A44\"\n\n# Imprint sequential ramp for colored fields (hexagon cells fill the map), as (position, hex) stops\nSEQ_FIELDS = (\n    [(0.0, \"#66E2B2\"), (0.369, \"#009E73\"), (0.803, \"#024582\"), (1.0, \"#351E45\")]\n    if THEME == \"light\"\n    else [(0.0, \"#404C02\"), (0.487, \"#009E73\"), (1.0, \"#CDD9FF\")]\n)\n\n# Columns\nLAT = \"lat\"  # role: lat\nLON = \"lon\"  # role: lon\nSIGHTINGS = \"Sightings\"  # statistic drawn per cell (count of points)\n\n# Data: bird species sightings — deliberately wide density spread to showcase log-scale range\nnp.random.seed(42)\n# (lat, lon, n_obs, spread_deg) — from sparse (150) to heavy (2500)\nclusters = [\n    (47.6, -122.3, 2000, 0.45),  # Seattle / Pacific flyway (dense hub)\n    (37.8, -122.4, 800, 0.40),  # San Francisco Bay (moderate)\n    (29.8, -95.4, 350, 0.40),  # Houston / Gulf Coast (lighter)\n    (41.9, -87.6, 1500, 0.45),  # Chicago / Great Lakes (dense hub)\n    (40.7, -74.0, 2500, 0.40),  # New York metro (densest hub)\n    (38.9, -77.0, 500, 0.38),  # Washington DC (moderate)\n    (25.8, -80.2, 150, 0.38),  # Miami / Atlantic flyway (sparse)\n    (44.9, -93.2, 250, 0.42),  # Minneapolis / Mississippi corridor (sparse)\n]\n\nlats_all, lons_all = [], []\nfor clat, clon, n, spread in clusters:\n    lats_all.extend(np.random.normal(clat, spread, n))\n    lons_all.extend(np.random.normal(clon, spread, n))\n\ndf = pd.DataFrame({LAT: np.clip(np.array(lats_all), 24.0, 50.0), LON: np.clip(np.array(lons_all), -126.0, -65.0)})\n\n# Plot\nlats = df[LAT].to_numpy()\nlons = df[LON].to_numpy()\n\n# Flat-top hexagonal binning in lat/lon space\nHEX_R = 0.65  # degrees (~65 km at mid-latitudes)\nCOL_STEP = 1.5 * HEX_R\nROW_STEP = HEX_R * np.sqrt(3)\n\ncols = np.round(lons / COL_STEP).astype(int)\nrow_off = (np.abs(cols) % 2) * 0.5\nrows = np.round(lats / ROW_STEP - row_off).astype(int)\nhex_counts = Counter(zip(cols.tolist(), rows.tolist(), strict=False))\n\nfeatures = []\nfor (c, r), count in hex_counts.items():\n    lon_c = c * COL_STEP\n    lat_c = (r + (abs(c) % 2) * 0.5) * ROW_STEP\n    # Clockwise winding in geographic coords → renders as filled interior\n    # (vl-convert flips y-axis; CW geo = CCW screen = D3 interior fill)\n    verts = [\n        [lon_c + HEX_R * np.cos(np.radians(-60 * i)), lat_c + HEX_R * np.sin(np.radians(-60 * i))] for i in range(6)\n    ]\n    verts.append(verts[0])\n    features.append(\n        {\n            \"type\": \"Feature\",\n            \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [verts]},\n            \"properties\": {SIGHTINGS: int(count), \"lon_c\": round(lon_c, 2), \"lat_c\": round(lat_c, 2)},\n        }\n    )\n\n# Base map — vega CDN, no local package required\nWORLD_URL = \"https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/world-110m.json\"\n# Mercator projection centred on continental US, tuned to fit inner 620×320 view\nproj_params = {\"type\": \"mercator\", \"scale\": 600, \"center\": [-97.5, 37]}\n\nbasemap = (\n    alt.Chart(alt.topo_feature(WORLD_URL, \"land\"))\n    .mark_geoshape(fill=LAND_FILL, stroke=LAND_STROKE, strokeWidth=0.5)\n    .project(**proj_params)\n)\n\ncounts = [f[\"properties\"][SIGHTINGS] for f in features]\nc_lo, c_hi = min(counts), max(counts)\n\n# Hexbin layer — inline GeoJSON features, sequential colormap brand-green → blue\nhexbin = (\n    alt.Chart(alt.InlineData(values=features, format=alt.DataFormat(type=\"json\")))\n    .mark_geoshape(stroke=PAGE_BG, strokeWidth=0.3, opacity=0.85)\n    .encode(\n        color=alt.Color(\n            f\"properties.{SIGHTINGS}\",\n            type=\"quantitative\",\n            title=SIGHTINGS,\n            # Log scale; the stops sit at their ramp positions in log space\n            scale=alt.Scale(\n                type=\"log\",\n                domain=[c_lo * (c_hi / c_lo) ** p for p, _ in SEQ_FIELDS],\n                range=[c for _, c in SEQ_FIELDS],\n                interpolate=\"rgb\",\n            ),\n            legend=alt.Legend(\n                title=SIGHTINGS,\n                gradientLength=220,\n                gradientThickness=16,\n                labelFontSize=12,\n                titleFontSize=12,\n                padding=14,\n            ),\n        ),\n        tooltip=[\n            alt.Tooltip(f\"properties.{SIGHTINGS}\", type=\"quantitative\", title=SIGHTINGS),\n            alt.Tooltip(\"properties.lon_c\", type=\"quantitative\", title=\"Cell centre lon (°)\"),\n            alt.Tooltip(\"properties.lat_c\", type=\"quantitative\", title=\"Cell centre lat (°)\"),\n        ],\n    )\n    .project(**proj_params)\n)\n\nchart = (\n    alt.layer(basemap, hexbin)\n    .properties(\n        width=800,\n        height=450,\n        autosize=alt.AutoSizeParams(type=\"fit\", contains=\"padding\"),\n        padding=10,\n        background=PAGE_BG,\n        title=alt.Title(\"US Bird Migration Hotspots · hexbin-map-geographic · python · altair · anyplot.ai\"),\n    )\n    .configure_title(color=INK, fontSize=16, fontWeight=\"bold\")\n    .configure_view(fill=PAGE_BG, stroke=None)\n    .configure_legend(\n        fillColor=ELEVATED_BG,\n        strokeColor=INK_SOFT,\n        labelColor=INK_SOFT,\n        titleColor=INK,\n        labelFontSize=12,\n        titleFontSize=13,\n    )\n)\n\nchart.save(f\"plot-{THEME}.png\", scale_factor=4.0)\n\nTW, TH = 3200, 1800\n_img = Image.open(f\"plot-{THEME}.png\").convert(\"RGB\")\nif _img.size != (TW, TH):\n    _scale = min(1.0, TW / _img.width, TH / _img.height)\n    _img = _img.resize((round(_img.width * _scale), round(_img.height * _scale)), Image.LANCZOS)\n    _canvas = Image.new(\"RGB\", (TW, TH), PAGE_BG)\n    _canvas.paste(_img, ((TW - _img.width) // 2, (TH - _img.height) // 2))\n    _canvas.save(f\"plot-{THEME}.png\")\n\nchart.save(f\"plot-{THEME}.html\")\n"}