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

Folium Choropleth启用GeoJsonTooltip时hover高亮失效问题

问题描述

这是我首次提交技术问题,若提问格式或表述存在不规范之处,欢迎各位指正。
我希望使用folium.Choropleth的highlight参数实现鼠标悬停时的区域高亮交互效果,预期效果如下图所示:
Choropleth预期高亮效果

但实际开发中该高亮功能无法正常生效,排查过程中发现明确异常现象:

  • 当代码中添加folium.features.GeoJsonTooltip提示组件时,悬停高亮完全失效
  • 若禁用/移除该Tooltip组件,高亮功能即可正常工作

启用GeoJsonTooltip时代码运行无任何报错,其余地图渲染、交互功能均符合预期,仅国家面要素的悬停高亮效果无法触发。

相关代码

Choropleth核心配置代码

folium.Choropleth(
geo_data=df1,
name="choropleth",
data=df3,
columns=["Country", "Estimate_UN"],
key_on="feature.properties.name",
fill_color="YlGnBu",
fill_opacity=0.8,
line_opacity=0.5,
legend_name="GDP Per Capita (in EUR)",
bins=bins,
highlight=True
).add_to(my_map)

完整可复现代码

import folium
import pandas
import geopandas

pandas.set_option('display.max_columns',25)
pandas.set_option('display.width',2000)
pandas.set_option('display.max_rows',300)

url = 'http://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)_per_capita'
tables1 = pandas.read_html(url, match='Country/Territory')
df1 = tables1[0]  # 数据格式从列表转为DataFrame

# 设置单层索引
df1.columns = ['Country', 'Region', 'Estimate_IMF', 'Year1', 'Estimate_UN', 'Year2', 'Estimate_WB', 'Year3']
# 仅保留国家、联合国估算值两列
df1 = df1.drop(columns=['Region', 'Year1', 'Year2', 'Year3', 'Estimate_IMF', 'Estimate_WB'])

df1['Country'] = df1['Country'].map(lambda x: x.rstrip('*'))
df1['Country'] = df1['Country'].map(lambda x: x.strip())
df1['Country'] = df1['Country'].str.replace('United States', 'United States of America')
df1['Country'] = df1['Country'].str.replace('DR Congo', 'Dem. Rep. Congo')
df1['Country'] = df1['Country'].str.replace('Central African Republic', 'Central African Rep.')
df1['Country'] = df1['Country'].str.replace('South Sudan', 'S. Sudan')
df1['Country'] = df1['Country'].str.replace('Czech Republic', 'Czechia')
df1['Country'] = df1['Country'].str.replace('Bosnia and Herzegovina', 'Bosnia and Herz.')
df1['Country'] = df1['Country'].str.replace('Ivory Coast', """Côte d'Ivoire""")
df1['Country'] = df1['Country'].str.replace('Dominican Republic', 'Dominican Rep.')
df1['Country'] = df1['Country'].str.replace('Eswatini', 'eSwatini')
df1['Country'] = df1['Country'].str.replace('Equatorial Guinea', 'Eq. Guinea')
df1.drop(df1[df1['Estimate_UN'] == '—'].index, inplace = True)
df1['Estimate_UN'] = df1['Estimate_UN'].apply(lambda g:int(str(g)))

### --- 调整GeoJsonToolTip中人均GDP显示格式,从12345.0(美元)转为€11,604格式 --- ###

df2 = df1.copy()
df2['Estimate_UN'] = df2['Estimate_UN'].apply(lambda g:g*0.94) # 美元转欧元

df3 = df2.copy()

df2['Estimate_UN'] = df2['Estimate_UN'].apply(lambda g:str(int(g)))
df2['Estimate_UN'] = '€' + df2['Estimate_UN'].astype(str)

length = (df2['Estimate_UN'].str.len())

df2.loc[length == 7, 'Estimate_UN'] = df2[['Estimate_UN']].astype(str).replace(r"(\d{3})(\d+)", r"\1,\2", regex=True)
df2.loc[length == 6, 'Estimate_UN'] = df2[['Estimate_UN']].astype(str).replace(r"(\d{2})(\d+)", r"\1,\2", regex=True)
df2.loc[length == 5, 'Estimate_UN'] = df2[['Estimate_UN']].astype(str).replace(r"(\d{1})(\d+)", r"\1,\2", regex=True)

### --- 创建地图 --- ###

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
df1 = world.merge(df1, how='left', left_on=['name'], right_on=['Country'])
df1 = df1.dropna(subset=['Estimate_UN'])

df2 = world.merge(df2, how='left', left_on=['name'], right_on=['Country'])
df2 = df2.dropna(subset=['Estimate_UN'])

df3 = world.merge(df3, how='left', left_on=['name'], right_on=['Country'])
df3 = df3.dropna(subset=['Estimate_UN'])

my_map = folium.Map(location=(39.22753573470106, -3.650093262568073),
    zoom_start=2, 
    tiles = 'https://server.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', 
    attr = 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye,Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
    min_zoom=2, 
    min_lot=-179, 
    max_lot=179, 
    min_lat=-65, 
    max_lat=179, 
    max_bounds=True)

### --- 添加提示框 --- ###

gdp = folium.FeatureGroup(name="GDP")

gdp.add_child(folium.GeoJson(data=df2, tooltip = folium.features.GeoJsonTooltip(
    fields=['Country','Estimate_UN'], 
    aliases=['Country:','GDP Per Capita:'],
    style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;"),
    localize = True),
    style_function= lambda y:{
    'stroke':'false',
    'opacity':'0',
    }))

### --- 国家区域着色 --- ###

bins = [100,1000,5000,10000,20000,35000,50000,112000]

folium.Choropleth(
    geo_data=df1,
    name="choropleth",
    data=df3,
    columns=["Country", "Estimate_UN"],
    key_on="feature.properties.name",
    fill_color="YlGnBu",
    fill_opacity=0.8,
    line_opacity=0.5,
    legend_name="GDP Per Capita (in EUR)",
    bins=bins,
    highlight=True
    ).add_to(my_map)

my_map.add_child(gdp)
my_map.save('index.html')
求助诉求

请帮忙排查GeoJsonTooltip导致highlight参数失效的具体原因,并给出可行的解决方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:36:27