Python 使用plotly dash为pandas数据帧绘制交互式图形会引发回调错误更新输出
我正在尝试为我拥有的timeseries数据帧创建一个基本的交互式绘图。我已将数据读入数据框Python 使用plotly dash为pandas数据帧绘制交互式图形会引发回调错误更新输出,python,pandas,callback,plotly,plotly-dash,Python,Pandas,Callback,Plotly,Plotly Dash,我正在尝试为我拥有的timeseries数据帧创建一个基本的交互式绘图。我已将数据读入数据框df。它有datetime作为索引,还有另外两个列category(有3个唯一值),count。 现在,我正在尝试使用plotly dash绘制一个具有以下特性的交互式图形 它将有一个输入框,用户应在其中输入他们想要查看其绘图的类别值 如果他们输入的值在df['category'].unique()中,它将返回对应于该特定类别的时间序列图。否则它将抛出一个错误 这是我为它编写的代码 import dash
df
。它有datetime
作为索引,还有另外两个列category
(有3个唯一值),count
。
现在,我正在尝试使用plotly dash绘制一个具有以下特性的交互式图形
类别
值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)
在@app.callback()
中,您放置了一个包含单个元素的输出列表。如果这样做,还需要返回一个列表,因此return[fig]
而不是return fig
但是,您根本不需要列表,因此您的回调装饰器可以如下所示:
@app.callback(
Output('inflow_graph', 'figure'),
Input('input_id', 'value'))
def update_graph(input_text):
请注意,为了简洁起见,我还删除了component_id
和component_属性
键,因为当前版本的Dash中也不需要它们(但它们没有错)
不过,回调中还有另一个问题:在else
案例中返回字符串,但是inflow\u图。figure
将需要一个figure对象或dictionary。您可以通过返回一个空字典(return{}
)来修复此问题。在@app.callback()
中,您放置了一个包含单个元素的输出列表。如果这样做,还需要返回一个列表,因此return[fig]
而不是return fig
但是,您根本不需要列表,因此您的回调装饰器可以如下所示:
@app.callback(
Output('inflow_graph', 'figure'),
Input('input_id', 'value'))
def update_graph(input_text):
请注意,为了简洁起见,我还删除了component_id
和component_属性
键,因为当前版本的Dash中也不需要它们(但它们没有错)
不过,回调中还有另一个问题:在
else
案例中返回字符串,但是inflow\u图。figure
将需要一个figure对象或dictionary。您可以通过返回一个空字典(return{}
)来修复此问题。请共享一个数据示例,以使代码可复制。在编辑中添加了示例数据请共享一个数据示例,以使代码可复制。在编辑中添加了示例数据