2 回答
TA贡献1875条经验 获得超3个赞
问题是下拉列表返回多个变量的列表(如您设置的那样multi=True),而您的回调旨在仅绘制一个变量。
为了绘制多个变量,您需要遍历选定的变量列表(即通过selectedVariable2您的代码)并将相应的轨迹添加到图中。
您还应该确保下拉列表是用列表而不是字符串初始化的(即您应该value="RECORD"用value=["RECORD"].
我在下面包括了一个例子。
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
# Load external stylesheets
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# Create a sample ataset
df = pd.DataFrame({"TIMESTAMP": ["2019-09-30 11:15:00", "2019-09-30 11:30:00", "2019-09-30 11:45:00", "2019-09-30 12:00:00", "2019-09-30 12:15:00"],
"RECORD": [0, 1, 2, 3, 4],
"SensorRel_Min(2)": [12.68219, 12.68466, 12.69364, 12.69078, 12.6914],
"SensorRel_Min(3)": [14.74209, 13.73777, 10.74584, 9.74522, 16.74376]})
# Define dropdown options
opts = [{'label': k, 'value': k} for k in list(df.columns.values)[1:]]
# Create a Dash layout
app.layout = html.Div(children=[
html.H1(children='Testing dashboard v01'),
html.Div(children='''
Select variable to plot below.
'''),
html.Div(children='''
Select variables to add to plot below.
'''),
dcc.Dropdown(
id='multiVariableDropdown',
options=opts,
value=['RECORD'],
multi=True
),
dcc.Graph(
id='plot2'
)
])
# Add callback functions
## For plot 2
@app.callback(Output('plot2', 'figure'),
[Input('multiVariableDropdown', 'value')])
def update_graph(selectedVariable2):
traces = []
for var in selectedVariable2:
traces.append(go.Scatter(x=df['TIMESTAMP'],
y=df[var],
name=var))
fig2 = go.Figure(data=traces)
return fig2
if __name__ == '__main__':
app.run_server(debug=True)
TA贡献1943条经验 获得超7个赞
尝试使用print()对其进行调试。如下所示,这样您就可以在每次从下拉列表中添加/删除内容时看到发送到输出组件的内容。希望能帮助到你!
def update_graph(selectedVariable2):
trace_finalPlot2 = go.Scatter(
x=df['TIMESTAMP'],
y=df[selectedVariable2],
name=str(selectedVariable2))
fig2 = go.Figure(data=trace_finalPlot2)
print(df[selectedVariable2])
return fig2
添加回答
举报