You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly中能否为Choroplethmapbox设置经纬度双变量作为位置参数?

解决方法

根据你的需求,分两种场景给出实现方案:


场景1:展示经纬度点对应的数值(点数据可视化)

Choroplethmapbox是针对地理区域的着色地图,不支持直接传入经纬度对作为位置。如果你的数据是每个经纬度点对应一个数值,建议改用Scattermapbox实现,它支持直接使用经纬度坐标,同时可以通过标记颜色映射数值:

import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv('datafile.csv')

fig = go.Figure(
    go.Scattermapbox(
        lat=df["lat"],
        lon=df["lng"],
        mode='markers',
        marker=dict(
            size=10,
            color=df["data"],  # 用数据值控制颜色
            colorscale="Viridis",
            showscale=True,
            colorbar=dict(title="数据值")
        ),
        text=df["data"],  # 鼠标悬停显示的数据
    )
)

fig.update_layout(
    mapbox_style="carto-positron",
    mapbox_zoom=10,
    mapbox_center={"lat": df["lat"].mean(), "lon": df["lng"].mean()}  # 地图中心设为数据点中心
)

fig.show()

场景2:基于经纬度匹配到地理区域,实现区域着色

如果你确实需要用Choroplethmapbox展示区域着色,但数据是和经纬度绑定的,需要先把经纬度点匹配到GeoJSON中的对应区域(比如城市、ZIP编码区),再用匹配后的区域ID关联数据:

步骤1:用GeoPandas匹配经纬度到区域

先安装geopandas和shapely,然后加载GeoJSON和你的数据,把经纬度转为点对象,再匹配到对应的区域:

import pandas as pd
import geopandas as gpd
from shapely.geometry import Point

# 加载GeoJSON
gdf = gpd.read_file("city.geojson")
# 加载你的数据
df = pd.read_csv('datafile.csv')

# 将经纬度转为Shapely点对象,注意GeoDataFrame的坐标顺序是(lon, lat)
geometry = [Point(xy) for xy in zip(df["lng"], df["lat"])]
df_gdf = gpd.GeoDataFrame(df, geometry=geometry, crs=gdf.crs)

# 空间连接:找到每个点所在的区域,获取区域ID(比如properties.city)
matched_df = gpd.sjoin(df_gdf, gdf, how="left", predicate="within")

步骤2:用匹配后的区域ID绘制Choroplethmapbox

把匹配得到的区域ID(比如matched_df["city"])传入locations参数,和featureidkey对应:

import plotly.graph_objects as go

fig = go.Figure(
    go.Choroplethmapbox(
        geojson=gdf.__geo_interface__,  # 将GeoDataFrame转为Plotly支持的格式
        featureidkey="properties.city",
        locations=matched_df["city"],  # 匹配后的区域ID
        z=matched_df["data"],
        zauto=True,
        colorscale="Viridis",
        showscale=True,
    )
)

fig.update_layout(
    mapbox_style="carto-positron",
    mapbox_zoom=10,
    mapbox_center={"lat": df["lat"].mean(), "lon": df["lng"].mean()}
)

fig.show()

内容的提问来源于stack exchange,提问作者Luke Wolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:05:38