1

I am trying to plot multiple line plots in one graph. I am getting : KeyError:'variable'. I think this has something to do with the layouts displayed because in case of single line plot there was no requirement of layout, so i was not getting error. After adding multiple line plots I started getting this error.

Sample Dataframe: enter image description here

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):

Dataset link: https://www.kaggle.com/code/manishkc06/exploring-covid-19-data/data?select=covid_19_data.csv

2
  • can we have a link to your data, or can you include a sample of your dataframe in the question? including the output from covid_19_data.head().to_dict() would be helpful to help us debug the issue Commented Jan 12, 2023 at 6:20
  • 1
    Added the sample dataframe as well as the dataset link. Commented Jan 12, 2023 at 8:55

2 Answers 2

2

I wasn't able to reproduce your error, but KeyError usually occurs when you are trying to access a column that doesn't exist. When you are using a Jupyter notebook, there is a possibility that you change a DataFrame in some way without realizing it, especially if you run your cells out of order. Are there any modifications to your covid_19_data that aren't shown in the code you've included?

Using the data from the download link and renaming the columns to match what I believe you have, I am able to get a working dash app using your code:

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)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

Hm I saw that have some problem in your code.

  • First: you are setting value = 'Equity 1' and it's not value in dataframe.
  • Second: you are group by by Last_Update but it should be Last Update.
  • Third: you are filtering df = covid_19_data[covid_19_data.Country == value] but it should be df = covid_19_data[covid_19_data['Country/Region'] == value]

So I think you should change your code as below:

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)

enter image description here

2 Comments

I don't think this is quite what is happening because those column names exist in the screenshot of the dataframe that he showed – but to be honest, I cannot reproduce the error
Yep, I tried another one with variable in labels but it did not reproduce the error too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.