【问题标题】:plotting an interactive graph for a pandas dataframe using plotly-dash is throwing callback error updating output使用 plotly-dash 为 pandas 数据框绘制交互式图形会引发回调错误更新输出
【发布时间】:2021-03-14 13:52:13
【问题描述】:

我正在尝试为我拥有的时间序列数据框创建一个基本的交互式绘图。我已将数据读入数据框df。它有datetime 作为索引和另外两个列category(有3 个唯一值),count。 现在,我正在尝试使用具有以下功能的 plotly-dash 绘制交互式图表

  1. 它将有一个输入框,用户应在其中输入他们想要查看其绘图的category
  2. 如果他们输入的值在df['category'].unique() 中,它将返回对应于该特定类别的时间序列图。否则会报错

这是我为它编写的代码

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px

app = dash.Dash()
app.layout = html.Div(children = [
    html.H1(children='Dash trail'),
    html.Br(),
    html.Br(),
    dcc.Input(id='input_id',value='',type='text'),
    dcc.Graph(id='inflow_graph')
])

@app.callback(
[Output(component_id='inflow_graph',component_property='figure')],
    [Input(component_id='input_id',component_property='value')])
def update_graph(input_text):
    if input_text in df['category'].unique():
        dff = df[df['category']==input_text]
        fig = px.line(dff, x=dff.index, y=dff['count'],title='count for selected category')
        return fig
    else:
        return 'Enter the correct category value'
if __name__=='__main__':
    app.run_server(debug=True,use_reloader=False)

抛出以下错误

dash.exceptions.InvalidCallbackReturnValue: The callback ..inflow_graph.figure.. is a multi-output.
Expected the output type to be a list or tuple but got:
Figure({
    'data': [{'hovertemplate': 'ds=%{x}<br>ticket_count=%{y}<extra></extra>',
              'legendgroup': '',
              'line': {'color': '#636efa', 'dash': 'solid'},
              'mode': 'lines',
              'name': '',
              'showlegend': False,
              'type': 'scattergl',
              'x': array([datetime.datetime(2020, 1, 3, 0, 0), ....(and so on my full dataframe)

我不明白我在哪里回调多个输出。如何解决此错误?

编辑:在此处添加示例数据

            Category Count
date(index) 
2020-01-03    A       30
2020-01-03    B       50
2020-01-04    C       14
2020-01-04    A       16
2020-01-04    B       40

【问题讨论】:

  • 请分享您的数据样本,以使您的代码可重现。
  • 在编辑中添加了示例数据

标签: python pandas callback plotly plotly-dash


【解决方案1】:

@app.callback() 中放置一个输出列表,其中包含一个元素。如果你这样做,你还需要返回一个列表,所以return [fig]而不是return fig

但是,您根本不需要列表,因此您的回调装饰器可以简单地看起来像这样:

@app.callback(
    Output('inflow_graph', 'figure'),
    Input('input_id', 'value'))
def update_graph(input_text):

请注意,为简洁起见,我还删除了 component_idcomponent_property 键,因为在当前版本的 Dash 中也不需要它们(但它们并没有错)。

您的回调中还有另一个问题:您在 else 的情况下返回一个字符串,但 inflow_graph.figure 将需要一个 Figure 对象或字典。您可以通过返回一个空字典 (return {}) 来解决此问题。

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 2021-06-07
    • 2021-02-25
    • 2020-08-12
    • 2021-10-23
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多