Dash技术问题:回调触发时如何保留直方图的选中图例
解决Dash直方图更新时图例选中状态重置的问题
核心问题是每次回调都会重新生成完整的Figure对象,丢失了之前的图例选中状态(每个trace的visible属性)。要解决这个问题,需要在回调中获取当前图的状态,再把状态应用到新生成的图上。
步骤1:修改回调,传入当前图作为状态
把当前的figure作为State添加到回调参数中,读取每个trace的可见性状态:
from dash import Input, Output, State @callback( Output('change-log-histogram', 'figure'), Input('xbin-type', 'value'), State('change-log-histogram', 'figure') # 获取当前图的状态 ) def update_xbin(xbin_type, current_fig): visible_states = None # 初始加载时current_fig为None,需要判断 if current_fig is not None: # 提取每个trace的visible状态 visible_states = [trace['visible'] for trace in current_fig['data']] if xbin_type == 'W1': return make_histogram(df, 604_800_000, visible_states) return make_histogram(df, xbin_type, visible_states)
步骤2:修改make_histogram函数,应用可见性状态
更新函数,接受visible_states参数,在生成每个trace时复用之前的可见性设置:
def make_histogram(df, xbin_type, visible_states=None): now = datetime.now() tmr = now + timedelta(days=1) fig = go.Figure() field_names = df['field'].unique() for idx, name in enumerate(field_names): df_of_table = df.loc[df['field'] == name] # 默认显示,若有传入状态则复用对应值 visible = visible_states[idx] if (visible_states and idx < len(visible_states)) else True fig.add_trace(go.Histogram( name=name, x=df_of_table['timestamp'], xbins=dict( start='2022-01-01', end=tmr.strftime("%Y-%m-%d"), size=xbin_type ), visible=visible # 设置图例选中状态 )) fig.update_layout( xaxis_title_text='Date', yaxis_title_text='Count', bargap=0.2, barmode='stack' ) return fig
原理说明
- Plotly的每个trace都有
visible属性,True对应图例选中显示,False对应图例取消选中隐藏。 - 通过State获取当前图的
visible状态集合,在重新生成直方图时把状态逐个赋值给新的trace,就能保留用户之前的图例选择。
内容的提问来源于stack exchange,提问作者Bosco Chan
相关产品推荐
相关产品推荐

