本文介绍了如何修复Plotly Dash中的“下拉菜单读取"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试重新创建以下示例,以显示网络上显示的面向数据科学示例"

I have tried to re-create the following example Towards Data Science Example shown on the web

我编写了以下代码,对此进行了修改:

I have written the following code which I modified to this:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import pandas as pd
import plotly.graph_objs as go

# Step 1. Launch the application
app = dash.Dash()

# Step 2. Import the dataset
filepath = 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
st = pd.read_csv(filepath)


# range slider options
st['Date'] = pd.to_datetime(st.Date)
dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17',
         '2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']

features = st.columns[1:-1]
opts = [{'label' : i, 'value' : i} for i in features]

# Step 3. Create a plotly figure
trace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'],
                    name = 'AAPL HIGH',
                    line = dict(width = 2,
                                color = 'rgb(229, 151, 50)'))
layout = go.Layout(title = 'Time Series Plot',
                   hovermode = 'closest')
fig = go.Figure(data = [trace_1], layout = layout)


# Step 4. Create a Dash layout
app.layout = html.Div([
                # a header and a paragraph
                html.Div([
                    html.H1("This is my first dashboard"),
                    html.P("Dash is so interesting!!")
                         ],
                     style = {'padding' : '50px' ,
                              'backgroundColor' : '#3aaab2'}),
                # adding a plot
                dcc.Graph(id = 'plot', figure = fig),
                # dropdown
                html.P([
                    html.Label("Choose a feature"),
                        dcc.Dropdown(
                                id='opt',
                                options=opts,
                                value=features[0],
                                multi=True

                                ),
                # range slider
                html.P([
                    html.Label("Time Period"),
                    dcc.RangeSlider(id = 'slider',
                                    marks = {i : dates[i] for i in range(0, 9)},
                                    min = 0,
                                    max = 8,
                                    value = [1, 7])
                        ], style = {'width' : '80%',
                                    'fontSize' : '20px',
                                    'padding-left' : '100px',
                                    'display': 'inline-block'})
                      ])
                        ])


# Step 5. Add callback functions
@app.callback(Output('plot', 'figure'),
             [Input('opt', 'value'),
             Input('slider', 'value')])
def update_figure(input1, input2):
    # filtering the data
    st2 = st[(st.Date > dates[input2[0]]) & (st.Date < dates[input2[1]])]
    # updating the plot
    trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'],
                        name = 'AAPL HIGH',
                        line = dict(width = 2,
                                    color = 'rgb(229, 151, 50)'))
    trace_2 = go.Scatter(x = st2.Date, y = st2[input1],
                        name = str(input1),
                        line = dict(width = 2,
                                    color = 'rgb(106, 181, 135)'))
    fig = go.Figure(data = [trace_1, trace_2], layout = layout)
    return fig

# Step 6. Add the server clause
if __name__ == '__main__':
    app.run_server(debug = True)

当我更改要素输入时,它不会正确更新绘图,并且不会在绘图中显示选定的要素.

When I change the feature input, it does not update the plot correctly and does not show the selected features in the plot.

回调函数有问题,或者带有第二条轨迹的图形初始化有问题.但我不知道问题出在哪里.

Either there is something wrong with the callback function or the initialization of the graph with the second trace. But I cant figure out where the issue is.

推荐答案

由于您仅在回调中提供两个分散跟踪.从这两者来看,'AAPL.High'是静态的.因此,您需要将下拉列表值限制为Multi=False.

As you are only providing two scatter traces within your callback. From both, one is static for 'AAPL.High'. So you need to limit the dropdown values to Multi=False.

仅生成用于选择诸如'AAPL.LOW'之类的选项的有效图,而诸如dic之类的其他选项将不显示第二条迹线.如果您始终保持multi=True,则回调不会终止,如果始终只选择一个选项的话.选择两个或多个选项后,脚本将失败,因为它将尝试在此处为数据返回块查找错误的数据:

Valid plots are only generated for choosing options like 'AAPL.LOW' and others like dic won't display a second trace. The callback wouldn't terminate if you would keepmulti=True the callback would stil work, if always only one option is selected. The moment you select two or more options the script will fail as it would try to find faulty data for the data return block here:

trace_2 = go.Scatter(x = st2.Date, y = st2[**MULTIINPUT**],
                        name = str(input1),
                        line = dict(width = 2,
                                    color = 'rgb(106, 181, 135)'))

MULTIINPUT处只能传递一个列ID.如果要引入更多跟踪,请使用for循环.

Only one column id is allowed to be passed at MULTIINPUT. If you want to introduce more traces please use a for loop.

将代码更改为以下内容:

Change the code to the following:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import pandas as pd
import plotly.graph_objs as go

# Step 1. Launch the application
app = dash.Dash()

# Step 2. Import the dataset
filepath = 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
st = pd.read_csv(filepath)


# range slider options
st['Date'] = pd.to_datetime(st.Date)
dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17',
         '2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']

features = st.columns

opts = [{'label' : i, 'value' : i} for i in features]

# Step 3. Create a plotly figure
trace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'],
                    name = 'AAPL HIGH',
                    line = dict(width = 2,
                                color = 'rgb(229, 151, 50)'))
layout = go.Layout(title = 'Time Series Plot',
                   hovermode = 'closest')
fig = go.Figure(data = [trace_1], layout = layout)


# Step 4. Create a Dash layout
app.layout = html.Div([
                # a header and a paragraph
                html.Div([
                    html.H1("This is a Test Dashboard"),
                    html.P("Dash is great!!")
                         ],
                     style = {'padding' : '50px' ,
                              'backgroundColor' : '#3aaab2'}),
                # adding a plot
                dcc.Graph(id = 'plot', figure = fig),
                # dropdown
                html.P([
                    html.Label("Choose a feature"),
                        dcc.Dropdown(
                                id='opt',
                                options=opts,
                                value=features[0],
                                multi=False

                                ),
                # range slider
                html.P([
                    html.Label("Time Period"),
                    dcc.RangeSlider(id = 'slider',
                                    marks = {i : dates[i] for i in range(0, 9)},
                                    min = 0,
                                    max = 8,
                                    value = [1, 7])
                        ], style = {'width' : '80%',
                                    'fontSize' : '20px',
                                    'padding-left' : '100px',
                                    'display': 'inline-block'})
                      ])
                        ])


# Step 5. Add callback functions
@app.callback(Output('plot', 'figure'),
             [Input('opt', 'value'),
             Input('slider', 'value')])
def update_figure(input1, input2):
    # filtering the data
    st2 = st#[(st.Date > dates[input2[0]]) & (st.Date < dates[input2[1]])]
    # updating the plot
    trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'],
                        name = 'AAPL HIGH',
                        line = dict(width = 2,
                                    color = 'rgb(229, 151, 50)'))
    trace_2 = go.Scatter(x = st2.Date, y = st2[input1],
                        name = str(input1),
                        line = dict(width = 2,
                                    color = 'rgb(106, 181, 135)'))
    fig = go.Figure(data = [trace_1, trace_2], layout = layout)
    return fig

# Step 6. Add the server clause
if __name__ == '__main__':
    app.run_server(debug = True)

我希望这可以解决问题并解决您的问题. :)

I hope this cleared things up and solved your issues. :)

这篇关于如何修复Plotly Dash中的“下拉菜单读取"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:00