Home > Software design >  KeyError: 'variable' in dash plotly multi plot
KeyError: 'variable' in dash plotly multi plot

Time:01-13

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: enter image description here

CodePudding user response:

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

  • Related