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

如何在Plotly Express制作的分级统计图中添加静态州标签?

给Plotly Express分级统计图添加静态州标签的方法

Plotly Express的choropleth函数没有直接添加静态地理标签的参数,我们可以通过叠加Plotly Graph Objects的文本图层实现,且保证标签在动画切换时保持不变:

实现步骤

  • 获取美国各州的中心坐标数据,用于定位标签位置
  • 创建原始分级统计图后,添加静态文本图层
  • 调整标签样式确保可读性

完整代码示例

import plotly.express as px
import plotly.graph_objects as go

# 获取内置的美国各州中心坐标数据(包含州缩写、经纬度、州名)
state_centers = px.data.us_states().set_index("abbr")

# 你的原始分级统计图代码
fig = px.choropleth(
    choropleth,
    locations="USA-states",
    scope="usa",
    animation_frame="Year-month",
    animation_group="State",
    color="Bucket"
)

# 添加静态州标签
fig.add_trace(go.Scattergeo(
    lon=state_centers["lon"],
    lat=state_centers["lat"],
    text=state_centers.index,  # 显示州缩写,若要显示全名可替换为state_centers["name"]
    mode="text",
    hoverinfo="none",  # 关闭标签的hover提示,避免干扰主图
    textfont=dict(
        size=8,
        color="#333333"
    ),
    showlegend=False  # 不显示图例
))

fig.show()

注意事项

  • 确保你的数据中USA-states列的州缩写和state_centers的索引(abbr列)格式一致,否则需要先做数据匹配
  • 可以调整textfont的参数(如size、color、family)优化标签显示效果
  • 若需要自定义标签内容,可修改text参数为你需要显示的文本(如州名缩写、自定义标识等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:02:15