Plotly Dash实现带多选默认全选下拉框的散点图开发问题
代码修改方案
你只需要修改两处核心逻辑即可实现需求:
- 调整下拉框默认值为全部胶囊ID列表,实现默认全选效果
- 修改回调中的数据筛选规则,适配多选返回的列表格式数据
核心修改说明
- 下拉框的
value参数从单个数值2100015改为你提前提取好的全量胶囊ID列表capsuleID_names - 筛选数据时将
==判断替换为pandas的isin()方法,支持匹配列表内的多个ID - 额外补充空选判断:当用户清空所有选中项时默认展示全部数据,避免图表为空
修改后完整代码
import pandas as pd import plotly.express as px # (version 4.7.0) import plotly.graph_objects as go import dash # (version 1.12.0) pip install dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output app = dash.Dash(__name__) df = pd.read_csv("tcd vs rh.csv") print(df) capsuleID = df['Capsule_ID'].unique() print(capsuleID) capsuleID_names = list(capsuleID) print(capsuleID_names) app.layout = html.Div([ html.H1("Web Application Dashboards with Dash", style={'text-align': 'center'}), dcc.Dropdown(id="capsule_select", options=[{"label": cid, "value": cid} for cid in capsuleID_names], multi=True, value=capsuleID_names, # 此处修改为全量ID列表,默认全选 style={'width': "40%"} ), html.Div([ dcc.Graph(id="the_graph") ]), ]) # ----------------------------------------------------------- @app.callback( Output('the_graph', 'figure'), [Input('capsule_select', 'value')] ) def update_graph(capsule_chosen): # 空选处理+多选筛选逻辑 if not capsule_chosen: dff = df else: dff = df[df['Capsule_ID'].isin(capsule_chosen)] scatterplot = px.scatter( data_frame=dff, x="tcd", y="humidity", ) scatterplot.update_traces(textposition='top center') return scatterplot # ------------------------------------------------------------------------------ if __name__ == '__main__': app.run_server(debug=True)
内容的提问来源于stack exchange,提问作者haroldchoi
相关产品推荐
相关产品推荐

