You need to enable JavaScript to run this app. Python Folium Choropleth地图鼠标悬浮显示CSV数据问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python Folium Choropleth地图鼠标悬浮显示CSV数据问题咨询

问题解决方法

错误原因

你触发报错是因为 folium.GeoJson() 的data参数要求传入带地理几何坐标的GeoJSON数据/文件路径,你直接传入了只有国家、引用量两列的纯表格country_count,缺少几何信息自然无法渲染。

正确实现逻辑

Folium的Choropleth对象本身已经加载了GeoJSON地理数据,我们只需要把你的CSV数据匹配注入到Choropleth内置的GeoJSON属性中,再绑定tooltip即可,不需要额外叠加新的GeoJSON层。

修改后可运行代码

import pandas as pd
import os
import folium
import branca

# 加载业务数据
country_count = pd.read_csv('citations_countries.csv')
# 转成字典方便后续匹配注入,格式为 {国家名: 引用量}
cite_dict = country_count.set_index('Country')['Citations'].to_dict()
# 加载地理数据
country_geo = os.path.join('world-countries.json')

# 初始化底图
m = folium.Map(location=[0, 0], tiles="OpenStreetMap", zoom_start=1)

# 构建Choropleth图层
choropleth = folium.Choropleth(
    geo_data=country_geo,
    name='choropleth',
    data=country_count,
    columns=['Country', 'Citations'],
    key_on='feature.properties.name',
    fill_color='Greens',
    fill_opacity=1,
    line_opacity=0.7,
    legend_name="Citations Count",
    nan_fill_color="white",
    nan_fill_opacity=1,
    highlight=True,
    bins=[1, 15, 25, 50, 75, 150, 200, 400, 1200]
).add_to(m)

# 核心改动:把CSV的引用量数据注入到Choropleth的GeoJSON属性中
for feature in choropleth.geojson.data['features']:
    country_name = feature['properties']['name']
    # 匹配到数据就加进去,匹配不到就填0或自定义提示
    feature['properties']['Citations'] = cite_dict.get(country_name, 0)

# 给Choropleth内置的GeoJSON绑定tooltip
choropleth.geojson.add_child(
    folium.features.GeoJsonTooltip(
        fields=['name', 'Citations'],
        aliases=['国家名称', '引用量'],
        localize=True
    )
)

# 添加图层控制
folium.LayerControl().add_to(m) 

m

注意事项

  • 需确保country_count.csv里的Country字段名称和world-countries.json里的properties.name完全一致,比如美国在GeoJSON里可能叫United States of America,如果你的CSV里写的是USA会匹配失败,对应数据会显示为0。
  • 如果需要匹配不上时显示自定义提示(比如无数据),把cite_dict.get(country_name, 0)里的0改为'无数据'即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 05:54:01