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

如何为Plotly Choropleth结合Slider与Drop Down组件?

解决Plotly Choropleth中日期Slider与房产类型Drop Down联动异常问题

问题根源

原代码核心问题是未按房产类型分组管理轨迹,导致Slider和Drop Down的操作无法对应到正确数据集:

  • 初始data_slider3混合了所有日期、所有房产类型的数据,没有做类型区分
  • Drop Down按钮的args直接传递整个房产类型的全量数据,未与当前选中日期匹配,造成数据显示混乱

修正后完整代码

1. 按房产类型+日期重新组织轨迹数据

import plotly.graph_objects as go

# 假设sorted_dates3是已排序的日期列表,color_scale是自定义颜色刻度
property_list = df_state3['property_type'].unique().tolist()
data = []

# 为每个房产类型生成对应所有日期的轨迹
for prop_type in property_list:
    df_prop = df_state3[df_state3['property_type'] == prop_type].copy()
    for date in sorted_dates3:
        df_segmented = df_prop[df_prop['period_end'] == date]
        df_segmented['median_sale_price'] = df_segmented['median_sale_price'].astype(float)
        
        trace = dict(
            type='choropleth',
            showlegend=False,
            locations=df_segmented['state_code'],
            z=df_segmented['median_sale_price'],
            locationmode='USA-states',
            colorscale=color_scale,
            colorbar={'title': 'Median Sale Prices'},
            # 初始仅显示第一个房产类型的第一个日期轨迹
            visible=(prop_type == property_list[0] and date == sorted_dates3[0])
        )
        data.append(trace)

2. 生成关联房产类型的Slider

traces_per_prop = len(sorted_dates3)
slider_steps = []

for date_idx, date in enumerate(sorted_dates3):
    visible = [False] * len(data)
    # 初始默认选中第一个房产类型,仅显示该类型下当前日期的轨迹
    for prop_idx in range(len(property_list)):
        if prop_idx == 0:
            trace_idx = prop_idx * traces_per_prop + date_idx
            visible[trace_idx] = True
    step = dict(
        method='restyle',
        args=['visible', visible],
        label=str(date)
    )
    slider_steps.append(step)

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

3. 生成联动Slider的Drop Down按钮

buttons = []
for prop_idx, prop_type in enumerate(property_list):
    visible = [False] * len(data)
    active_date_idx = sliders[0]['active']
    # 切换房产类型时,保持当前Slider选中的日期可见
    for date_idx in range(traces_per_prop):
        trace_idx = prop_idx * traces_per_prop + date_idx
        visible[trace_idx] = (date_idx == active_date_idx)
    
    button = dict(
        method='restyle',
        args=['visible', visible],
        label=prop_type
    )
    buttons.append(button)

4. 组装布局并渲染图表

layout = dict(
    title='Median Sale Prices in US (2012 - 2022)',
    geo=dict(scope='usa', projection={'type': 'albers usa'}),
    sliders=sliders,
    updatemenus=[dict(
        y=1.1,
        x=0.275,
        xanchor='right',
        yanchor='top',
        active=0,
        buttons=buttons
    )],
    width=700,
    coloraxis_colorbar_thickness=23
)

fig = go.Figure(data=data, layout=layout)
fig.show()

关键修正逻辑

  • 轨迹分组:每个房产类型对应一组日期轨迹,通过索引范围明确区分,避免数据混合
  • 精确控制可见性:Slider和Drop Down均通过修改visible列表来切换显示,确保操作对应正确的数据集
  • 状态联动:切换Drop Down时自动匹配当前Slider选中的日期,保持界面状态一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:15:31