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

Folium TimeSliderChoropleth滑块显示异常问题求助

解决Folium TimeSliderChoropleth滑块异常与数据关联错误问题

常见错误原因及修复方案

1. 时间戳格式不规范

TimeSliderChoropleth要求时间戳为毫秒级整数,如果使用秒级时间戳或字符串格式,会导致滑块识别异常:

  • 修正代码:将datetime转为毫秒级时间戳
    df['timestamp'] = df['date_column'].apply(lambda x: int(x.timestamp() * 1000))
    
  • 验证:确保所有时间戳均存在于数据中,无空值或无效值。

2. 样式字典结构不匹配

样式字典必须严格遵循 {时间戳: {区域ID: 样式配置}} 的层级结构,且区域ID需与GeoJSON中的id字段完全一致(大小写、格式均需匹配):

  • 正确示例:
    style_dict = {
        1609459200000: {  # 2021-01-01的毫秒时间戳
            "BJ": {'fillColor': '#ff0000', 'fillOpacity': 0.7},
            "SH": {'fillColor': '#00ff00', 'fillOpacity': 0.7}
        }
    }
    
  • 排查点:检查是否有区域ID在GeoJSON中不存在,或样式字典遗漏部分区域。

3. GeoJSON的ID字段未正确关联

若GeoJSON的ID字段不是默认的id,需通过key_on参数指定字段路径:

folium.plugins.TimeSliderChoropleth(
    data=geojson_data,
    styledict=style_dict,
    key_on='feature.properties.region_code'  # 替换为你的GeoJSON中ID字段的路径
).add_to(m)

4. 数据分组聚合错误

若同一时间戳+区域ID存在多条数据,会导致样式字典被覆盖,引发数据关联错误:

  • 修正:通过分组聚合确保每个组合唯一
    grouped_df = df.groupby(['timestamp', 'region_id'])['sales_count'].sum().reset_index()
    

修正后的完整代码框架

import folium
from folium.plugins import TimeSliderChoropleth
import pandas as pd
import json

# 1. 数据预处理
df = pd.read_csv('housing_sales.csv')
df['date'] = pd.to_datetime(df['date'])
df['timestamp'] = df['date'].apply(lambda x: int(x.timestamp() * 1000))

# 2. 构建颜色映射与样式字典
min_sales = df['sales_count'].min()
max_sales = df['sales_count'].max()

def get_fill_color(sales_val):
    ratio = (sales_val - min_sales) / (max_sales - min_sales)
    r = int(255 * ratio)
    b = int(255 * (1 - ratio))
    return f'#{r:02x}00{b:02x}'

style_dict = {}
for ts in df['timestamp'].unique():
    ts_records = df[df['timestamp'] == ts]
    style_dict[ts] = {
        row['region_id']: {
            'fillColor': get_fill_color(row['sales_count']),
            'fillOpacity': 0.7,
            'color': '#333',
            'weight': 1
        } for _, row in ts_records.iterrows()
    }

# 3. 加载GeoJSON数据
with open('regions.geojson') as f:
    geojson_data = json.load(f)

# 4. 生成地图
m = folium.Map(location=[30.65, 104.06], zoom_start=8)  # 替换为你的地图中心坐标
TimeSliderChoropleth(
    data=geojson_data,
    styledict=style_dict,
    key_on='feature.properties.region_id'  # 匹配GeoJSON中的ID字段
).add_to(m)

m.save('housing_sales_time_map.html')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:32:04