Dash可视化图表无法更新,请求技术排查
问题诊断与解决方案
核心问题:函数参数不匹配
你的Graph_Throughput函数定义中第三个参数为Unit_type,但回调调用时误用了未定义的关键字参数Unit=Unit_type,这会触发TypeError,导致回调无法正常生成并返回图表对象。
修复代码:
修改回调中的函数调用语句,将参数名修正为匹配的Unit_type:
fig = Graph_Throughput(df=dict_df_filter['bench'], test_data=test_data, Unit_type=Unit_type, graph_type=graph_type, fig=fig)
回调触发逻辑优化
当前回调仅在按钮点击时返回图表,初始加载时返回None导致图表区域空白;同时ctx.triggered_id的判断逻辑可能存在误判。建议调整如下:
- 初始加载返回带提示的空图表,避免空白状态
- 保留按钮触发逻辑的同时,确保判断逻辑严谨
优化后的回调代码:
@callback( Output(component_id='FPY-df', component_property='figure'), [Input('FPY-DatePicker', 'value'), Input('Unit-Type-radio','value'), Input('tr_radio_btn','value'), Input('FPY-Graph-Type','value'), Input('update-button','n_clicks')] ) def update_text(date, Unit_type, test_data, graph_type, n_clicks): # 非按钮触发时返回提示性空图表 if not ctx.triggered or ctx.triggered_id != 'update-button': return go.Figure(layout=go.Layout(title="请点击「Update Graph」生成图表")) start_date, end_date = date fig = go.Figure() # 日期格式转换,确保与MySQL datetime类型兼容 start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S') end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S') df_sys = pd.read_sql( 'SELECT * FROM schema.TABLE WHERE START_DATETIME >= %s and START_DATETIME <= %s', con=connection, params=(start_date_str, end_date_str) ) dict_df_filter = ThroughPut(df_sys, start_date=start_date, end_date=end_date, UnitType=Unit_type) fig = Graph_Throughput(df=dict_df_filter['bench'], test_data=test_data, Unit_type=Unit_type, graph_type=graph_type, fig=fig) # 添加基础布局,确保图表显示完整 fig.update_layout( xaxis_title="日期", yaxis_title=test_data, title=f"{Unit_type} - {test_data} {graph_type}图" ) return fig
Graph_Throughput函数健壮性优化
添加列存在性检查与日期类型校验,避免因数据格式问题导致图表无数据:
def Graph_Throughput(df: pd.DataFrame, test_data: str, Unit_type: str, graph_type: str, fig: go.Figure): # 检查必要数据列是否存在 if 'Date' not in df.columns or test_data not in df.columns: fig.update_layout(title="数据列缺失,请检查DataFrame结构") return fig # 确保日期列为datetime类型 df['Date'] = pd.to_datetime(df['Date']) trace_name = 'All Units' if Unit_type == '*' else f'{Unit_type} {test_data}' if graph_type == 'Trend': trace = go.Scatter(x=df['Date'], y=df[test_data], mode='lines', name=trace_name) elif graph_type == 'Bar': trace = go.Bar(x=df['Date'], y=df[test_data], name=trace_name) else: fig.update_layout(title="不支持的图表类型") return fig fig.add_trace(trace) return fig
内容的提问来源于stack exchange,提问作者Cory Hoffer
相关产品推荐
相关产品推荐

