只是从excel文件创建一个简单的图,它会正确加载,但在更新图破折号时会返回此错误:
Failed component prop type: Invalid component prop figure key props supplied to Graph.
Bad object: {
“props”: {
“id”: “average_country”,
“figure”: {
“data”: [
{
“x”: [
“DE”,
“ES”,
“FR”,
“IT”,
“UK”
],
“y”: [
[
2365.56,
4528.33875,
4851.085,
4325.14,
2107.921428571429
]
],
“type”: “bar”
}
],
“layout”: {
“title”: “Hyperzone”
}
}
},
“type”: “Graph”,
“namespace”: “dash_core_components”
}
Valid keys: [
“data”,
“layout”,
“frames”
]
我只是使用数据透视表来创建某些国家/地区的数据平均值,这是我的代码,数据透视表是正确的,并且会以所需的值输出有效结果,正当我尝试使用回调函数,它返回一条错误消息。
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output
HP= pd.read_excel(r’C:\Users\salinejs\HP.xlsx’)
Columns = [‘Station’, ‘Week’, ‘Owner’, ‘Cost’,‘Country’]
HP_filtered = HP[Columns]
avaliable_weeks= HP_filtered[‘Week’].unique()
external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]
app = dash.Dash(name, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id= 'Week_filter',
options = [{'label':j, 'value':j}for j in avaliable_weeks],
value= 'Week 42'
),
],
style= {'float':'left', 'display':'inline-block'}
),
html.Div([
dcc.Graph(
id='average_country',
)
],
)
]
),
],
)
@app.callback(
Output(‘average_country’, ‘figure’),
[Input(‘Week_filter’,‘value’)]
)
def update_value(week):
HP_filtered_week = HP_filtered[ HP_filtered['Week'] == week ]
pv = pd.pivot_table(HP_filtered_week, values='Cost', columns='Country', index='Week')
print(pv)
print(pv.columns)
return dcc.Graph(
id='average_country',
figure={
'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar'
}],
'layout':{
'title': 'Cost',
}
})
if name == ‘main’:
app.run_server(debug=True)
这是因为您正在将回调输出发送到图形,但该函数返回的是整个dcc.Graph()而不是图形。
更改
return dcc.Graph(
id='average_country',
figure={
'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar'
}],
'layout':{
'title': 'Cost',
}
})
到
return {'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar' }], 'layout':{ 'title': 'Cost',},}