按地区分列的国家地图 | scatter_mapbox |巧妙地

Map of a country by regions | scatter_mapbox | plotly

感谢 Rob Raymond 之前的工作。目的是用scatter_mapbox表示一个国家的地区,我得到了地图的这种情况(以西班牙为例) :

import requests
import plotly.express as px
import pandas as pd

# get Spain municipal boundaries
res = requests.get(
    "https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/spain-provinces.geojson"
)

# get some cities in Spain
df = (
    pd.json_normalize(
        requests.get(
            "https://opendata.arcgis.com/datasets/6996f03a1b364dbab4008d99380370ed_0.geojson"
        ).json()["features"]
    )
    .loc[
        lambda d: d["properties.CNTRY_NAME"].eq("Spain"),
        ["properties.CITY_NAME", "geometry.coordinates"],
    ]
    .assign(
        lon=lambda d: d["geometry.coordinates"].apply(lambda v: v[0]),
        lat=lambda d: d["geometry.coordinates"].apply(lambda v: v[1]),
    )
)

# scatter the cities and add layer that shows municiple boundary
px.scatter_mapbox(df, lat="lat", lon="lon", hover_name="properties.CITY_NAME").update_layout(
    mapbox={
        "style": "carto-positron",
        "zoom": 3.5,
        "layers": [
            {
                "source": res.json(),
                "type": "line",
                "color": "green",
                "line": {"width": 1},
            }
        ],
    }
)

如何按地区切换城市?

import plotly.express as px
import numpy as np
import geopandas as gpd


gdf = gpd.read_file(
    "https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/spain-provinces.geojson",
    crs="epsg:4326",
)
# for choropleth...
gdf["measure"] = np.random.randint(1, 1000, len(gdf))

px.choropleth_mapbox(
    gdf, geojson=gdf["geometry"].__geo_interface__, locations=gdf.index, color="measure", hover_name="name"
).update_layout(
    mapbox={
        "style": "carto-positron",
        "center": {
            "lon": sum(gdf.total_bounds[[0, 2]]) / 2,
            "lat": sum(gdf.total_bounds[[1, 3]]) / 2,
        },
        "zoom":4
    },
    margin={"l":0,"r":0,"t":0,"b":0}
)