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

Plotly Choropleth地图仅保留散点图层悬停功能的实现方法

解决Plotly仅保留散点图层悬停效果的问题

问题场景

用Plotly Express开发包含两个图层的地图:

  • 按区域着色的choropleth底图
  • 覆盖指定国家的散点气泡层
    需要仅保留散点图层的悬停提示,关闭底图的悬停效果,之前设置hovermode=False会禁用所有图层的悬停,无法实现需求。

解决方案

核心思路是单独关闭choropleth图层的悬停信息,而非全局禁用悬停模式:

  1. 移除fig.update_layout()中的hovermode=False设置,改为hovermode="closest"(确保仅显示鼠标最近元素的悬停提示)
  2. 给choropleth图层添加hoverinfo='skip'属性,让它不响应悬停事件
  3. 散点图层保持默认的悬停设置即可

修改后的完整代码

fig = px.choropleth(df, locations="alpha-3",
                color="sub-region",
                color_discrete_map= {"Middle East and Africa":"#2a7bb0",
                                        "Europe":"#fc5e61",
                                        "Asia":"#00a19c",
                                        "Northern America":"#00134d",
                                        "Russia and Central Asia": "#febec0",
                                        "Latin America and the Caribbean":"#99a1b8"})

# 移除hovermode=False,改为closest,确保只显示最近元素的悬停
fig.update_layout(width=1500, height=1000, margin={"r":0,"t":0,"l":0,"b":0}, hovermode="closest")
fig.update_geos(projection_type="mercator", visible=False)
fig.update_traces(marker_line_width=0)

# 单独关闭choropleth图层的悬停信息
fig.update_traces(hoverinfo='skip', selector=dict(type='choropleth'))

fig2 = px.scatter_geo(dfa, locations="alpha-3", size="actors")
fig.add_trace(fig2.data[0])

aPlot = plotly.offline.plot(fig,
                        config={"displayModeBar": False},
                        show_link=False,
                        include_plotlyjs=False,
                        output_type='div')

关键说明

  • hovermode="closest":确保鼠标悬停时只触发距离最近的元素的悬停提示,避免多个图层同时触发
  • fig.update_traces(hoverinfo='skip', selector=dict(type='choropleth')):通过selector精准定位choropleth类型的图层,设置hoverinfo='skip'让它不显示任何悬停信息
  • 散点图层默认保留悬停效果,无需额外修改,如果需要自定义悬停内容,可以在px.scatter_geo()中通过hover_data参数配置

数据示例

choropleth数据片段

name alpha-3  country-code  region              sub-region
0                Zimbabwe     ZWE           716  Africa  Middle East and Africa
1                  Zambia     ZMB           894  Africa  Middle East and Africa
2            South Africa     ZAF           710  Africa  Middle East and Africa
3                   Yemen     YEM           887    Asia  Middle East and Africa
4                Viet Nam     VNM           704    Asia                    Asia

散点数据片段

name  ...                                Actors
0               South Africa  ...                                NameOfAnActor

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:25:53