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

如何在Python Plotly Choropleth地图中显示常驻区域数值

在Plotly Express地图中添加静态区域数值标签

要让地图上的地区数值无需悬停直接显示,你需要在 choropleth 地图基础上添加文本标签图层,以下是修正后的完整代码:

import json
import pandas as pd
import numpy as np
import plotly.express as px

# 加载GeoJSON数据
x = json.load(open("./odisha_disticts.geojson","r"))

# 构造数据
user_data = []
for i in range(len(x['features'])):
    d = x['features'][i]['properties']
    d['Females'] = np.random.randint(0,100,1)[0]
    user_data.append(d)
df = pd.DataFrame(user_data)

# 创建 choropleth 地图
fig = px.choropleth(
    df,
    locations="ID_2",
    featureidkey="properties.ID_2",
    geojson=x,
    color="Females"
)
fig.update_geos(fitbounds="locations", visible=False)

# 创建文本标签图层
text_fig = px.scatter_geo(
    df,
    geojson=x,
    featureidkey="properties.NAME_2",
    locations="NAME_2",  # 匹配DataFrame中的地区名列
    text=df.apply(lambda row: f"{row['NAME_2']}\n{row['Females']}", axis=1),  # 显示地区名+对应数值
    mode="text"  # 仅显示文本,隐藏标记点
)

# 将文本图层合并到主地图
for trace in text_fig.data:
    fig.add_trace(trace)

# 调整文本样式(可选)
fig.update_traces(textfont=dict(color="black", size=10))

fig.show()

关键修改说明:

  1. 修正数据匹配:原代码中scatter_geo的locations参数写的是"District",但你的DataFrame中地区名列是NAME_2,需对应修改才能正确定位文本位置。
  2. 文本内容优化:通过apply生成包含地区名和数值的组合文本,让显示信息更直观;设置mode="text"避免显示多余的标记点。
  3. 图层合并:单独创建的scatter_geo不会自动合并到主地图,需要通过add_trace将文本图层的轨迹添加到 choropleth 地图中。
  4. 样式调整:通过update_traces修改文本的颜色和大小,确保在地图背景上清晰可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:32:21