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

带滑块的Choropleth分级统计图仅显示首年数据 滑动后地图空白无报错

问题根因

核心错误有2处:

  • 链式赋值意外覆盖了原始数据集:dff = df_total = dff.rename(...) 这行代码会将全局的原始数据集df_total替换为当前年份的子集,后续遍历其他年份时,从已经被截断的df_total中无法筛选出其他年份的数据,导致滑块对应其他年份的图层都是空数据,切换后显示空白。
  • 滑块年份生成逻辑不严谨:直接用i+1990生成年份标签,如果数据集起始年份不是1990或者存在断档,会出现标签和实际数据不匹配的问题。
  • 冗余的列类型转换逻辑:你将所有列转为字符串后,又重新把Total Deaths转为浮点型,虽然不直接报错,但存在不必要的性能损耗。

修正后代码

import pandas as pd
import plotly.offline

df_total = pd.read_csv('../input/air-pollution/death-rates-total-air-pollution.csv')
# 提前统一重命名列,避免循环内重复操作
df_total = df_total.rename(columns={"Deaths - Air pollution - Sex: Both - Age: Age-standardized (Rate)":"Total Deaths"})

scl = [[0.0, '#ffffff'],[0.2, '#ff9999'],[0.4, '#ff4d4d'],
       [0.6, '#ff1a1a'],[0.8, '#cc0000'],[1.0, '#4d0000']]

data_slider = []
# 提前对年份排序,保证滑块顺序正确
sorted_years = sorted(df_total['Year'].unique())

for year in sorted_years:
    # 筛选当前年份数据,不再覆盖全局df_total
    dff = df_total[df_total['Year'] == year].copy()
    
    # 构造悬浮文本
    dff['text'] = dff['Entity'] + '<br>死亡数:' + dff['Total Deaths'].round(2).astype(str)

    data_one_year = dict(
        type='choropleth',
        locations = dff['Entity'],
        z = dff['Total Deaths'],
        locationmode = 'country names',
        colorscale = scl,
        text = dff['text'],
        colorbar = {'title': 'Total Deaths'}
    )
    data_slider.append(data_one_year)

steps = []
for i in range(len(data_slider)):
    step = dict(
        method='restyle',
        args=['visible', [False] * len(data_slider)],
        # 直接用预排序的年份作为标签,避免硬编码错误
        label=f'Year {sorted_years[i]}'
    )
    step['args'][1][i] = True
    steps.append(step)

sliders = [dict(active=0, pad={"t": 1}, steps=steps)]  

layout = dict(
    geo=dict(scope='world', projection={'type': 'equirectangular'}),
    sliders=sliders,
    title='全球空气污染致死人数年度分布'
)

fig = dict(data=data_slider, layout=layout) 
plotly.offline.iplot(fig)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:45:04