python-3.x KeyError:“变量”在虚线绘制的多图中

2w3kk1z5  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(169)

我试图在一个图表中绘制多个线图。我得到:KeyError:“变量”。我认为这与显示的布局有关,因为在单线图的情况下没有布局要求,所以我没有得到错误。添加多个线图后,我开始得到这个错误。
样本 Dataframe :

app = dash.Dash(__name__)

app.layout = html.Div([
    
# Creating drop down list
    dcc.Dropdown(options=[
       {'label': value, 'value': value} for value in sorted(countries)
   ],
   value='Equity 1', id='demo-dropdown'),
    
# Creating graph id
    html.Div([dcc.Graph(id='graph')])
])

# app callback for line chart
@app.callback(
    Output('graph', 'figure'),
    Input('demo-dropdown', 'value')
)

# updating line chart with the selected equity from dropdown and slected date range
def update_graph(value):
    df = covid_19_data[covid_19_data.Country == value]
    df = df.groupby(['Last_Update']).sum().reset_index()
    fig = px.line(df, 
        x="Last_Update", y=["Confirmed","Deaths", "Recovered",], labels={"value": "count", "variable": "color coding"})
    fig.update_layout(yaxis={'title':'# of Cases'},
                      title={'text':'Number of confirmed Covid 19 cases',
                      'font':{'size':28},'x':0.5,'xanchor':'right'})
    return fig
Exception on /_dash-update-component [POST]
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\ProgramData\Anaconda3\lib\site-packages\dash\dash.py", line 1078, in dispatch
    response.set_data(func(*args, outputs_list=outputs_list))
  File "C:\ProgramData\Anaconda3\lib\site-packages\dash\dash.py", line 1009, in add_context
    output_value = func(*args, **kwargs)  # %% callback invoked %%
  File "<ipython-input-41-035859195027>", line 25, in update_graph
    fig = px.line(df,
  File "C:\ProgramData\Anaconda3\lib\site-packages\plotly\express\_chart_types.py", line 252, in line
    return make_figure(args=locals(), constructor=go.Scatter)
  File "C:\ProgramData\Anaconda3\lib\site-packages\plotly\express\_core.py", line 1889, in make_figure
    for val in sorted_group_values[m.grouper]:
KeyError: 'variable'
Exception on /_dash-update-component [POST]
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\ProgramData\Anaconda3\lib\site-packages\dash\dash.py", line 1078, in dispatch
    response.set_data(func(*args, outputs_list=outputs_list))
  File "C:\ProgramData\Anaconda3\lib\site-packages\dash\dash.py", line 1009, in add_context
    output_value = func(*args, **kwargs)  # %% callback invoked %%
  File "<ipython-input-41-035859195027>", line 25, in update_graph
    fig = px.line(df,
  File "C:\ProgramData\Anaconda3\lib\site-packages\plotly\express\_chart_types.py", line 252, in line
    return make_figure(args=locals(), constructor=go.Scatter)
  File "C:\ProgramData\Anaconda3\lib\site-packages\plotly\express\_core.py", line 1889, in make_figure
    for val in sorted_group_values[m.grouper]:
KeyError: 'variable'
Exception on /_dash-update-component [POST]
Traceback (most recent call last):

数据集链接:https://www.kaggle.com/code/manishkc06/exploring-covid-19-data/data?select=covid_19_data.csv

ffscu2ro

ffscu2ro1#

嗯,我看到你的代码中有一些问题。

  • 首先:您正在设置value = 'Equity 1',但它不是 Dataframe 中的值。
  • 第二:您按Last_Update分组,但它应该是Last Update
  • 第三:您正在过滤df = covid_19_data[covid_19_data.Country == value],但它应该是df = covid_19_data[covid_19_data['Country/Region'] == value]

所以我认为你应该改变你的代码如下:

import dash
app = dash.Dash(__name__)

app.layout = html.Div([
    
# Creating drop down list
    dcc.Dropdown(options=[
       {'label': value, 'value': value} for value in sorted(countries)
   ],
   value='Burundi', id='demo-dropdown'),
    
# Creating graph id
    html.Div([dcc.Graph(id='graph')])
])

# app callback for line chart
@app.callback(
    Output('graph', 'figure'),
    Input('demo-dropdown', 'value')
)

# updating line chart with the selected equity from dropdown and slected date range
def update_graph(value):
    df = covid_19_data[covid_19_data['Country/Region'] == value]
    df = df.groupby(['Last Update']).sum().reset_index()
    fig = px.line(df, 
        x="Last Update", y=["Confirmed","Deaths", "Recovered",], labels={"value": "count", "variable": "color coding"})
    fig.update_layout(yaxis={'title':'# of Cases'},
                      title={'text':'Number of confirmed Covid 19 cases',
                      'font':{'size':28},'x':0.5,'xanchor':'right'})
    return fig

if __name__ == '__main__':
    app.run_server(debug=False)

3b6akqbq

3b6akqbq2#

我无法重现您的错误,但KeyError通常发生在您尝试访问不存在的列时。当您使用Jupyter笔记本时,有可能您以某种方式更改了DataFrame而没有意识到这一点,特别是当您无序运行单元格时。是否对您的covid_19_data进行了任何修改,而您所包含的代码中没有显示这些修改?
使用下载链接中的数据并重命名列以匹配我相信您所拥有的内容,我能够使用您的代码获得一个工作的破折号应用程序:

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

covid_19_data = pd.read_csv("covid_19_data.csv").rename(columns={
    'Country/Region': 'Country',
    'Last Update': 'Last_Update'
})
countries = covid_19_data.Country.unique().tolist()

app = dash.Dash(__name__)

app.layout = html.Div([
    
# Creating drop down list
    dcc.Dropdown(options=[
       {'label': value, 'value': value} for value in sorted(countries)
   ],
   value='Equity 1', id='demo-dropdown'),
    
# Creating graph id
    html.Div([dcc.Graph(id='graph')])
])

# app callback for line chart
@app.callback(
    Output('graph', 'figure'),
    Input('demo-dropdown', 'value')
)

# updating line chart with the selected equity from dropdown and slected date range
def update_graph(value):
    df = covid_19_data[covid_19_data.Country == value]
    df = df.groupby(['Last_Update']).sum().reset_index()
    fig = px.line(df, 
        x="Last_Update", y=["Confirmed","Deaths", "Recovered",], labels={"value": "count", "variable": "color coding"})
    fig.update_layout(yaxis={'title':'# of Cases'},
                      title={'text':'Number of confirmed Covid 19 cases',
                      'font':{'size':28},'x':0.5,'xanchor':'right'})
    return fig

if __name__ == "__main__":
    app.run_server(debug=True)

相关问题