0
votes

Issue:

I'm trying to load a simple plotly scatter plot, where

  • x axis = keyword
  • y axis = date
  • color = locale

however, even plotly throws a key error every time I add the "color" variable. The error code I get states that I don't have a column by that name, but when I print the column names I see the column there.

Anyone faced a similar issue?

Data:

data image

Code:

# Importing needed libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import random
import datetime
import plotly.graph_objects as go

# Reading the dataframe
df = pd.read_csv('./beanstalk_app/ti_data_ti_dash_v1.csv')

categories = df['category']
locales = df['locale']

# clean dataframe
ti_data = df.copy()
ti_data = ti_data.sample(1000)

# Contents of the app
# 1.Controls
# 1.1 Dropdown list

locs = dcc.Dropdown(id='choose_loc',
                    options=[
                        {
                            'label': locale, 'value': locale
                        } for locale in locales.unique()
                    ],
                    placeholder='Select Locale')

cats = dcc.Dropdown(id='choose_cat',
                    options=[
                        {
                            'label': c, 'value': c
                        } for c in categories.unique()
                    ],
                    placeholder='Select Category')


# 1.2 DatePicker
datepick = dcc.DatePickerRange(
    id='choose_date',
    min_date_allowed=df.date.min(),
    max_date_allowed=df.date.max(),
    initial_visible_month=df.date.min(),
    clearable=True,
    start_date=df.date.min(),
    end_date=df.date.max()
)


# 2.Interactive table
table = dash_table.DataTable(
    id='datatable',
    columns=[
            {"name": i, "id": i, "selectable": True, "presentation": "markdown"}
            if i == "google_query"
            else {"name": i, "id": i, "selectable": True}
            for i in df.columns
        ],
    data=df.to_dict('records'),
    editable=False,
    filter_action="native",
    sort_action="native",
    sort_mode="multi",
    column_selectable="single",
    row_selectable="multi",
    row_deletable=True,
    selected_columns=[],
    selected_rows=[],
    page_action="native",
    page_current=0,
    page_size=10,
    style_cell={
        'whiteSpace': 'normal',
        'height': 'auto',
    },

)

# Initialize the app

app = dash.Dash(__name__)
app.title = 'Dot Graph Demo - All Entities'
app.layout = html.Div([
    # modifiable table
    dbc.Container([
        dbc.Row(
            [
                dbc.Col(locs, width=4),
                dbc.Col(cats, width=4),
                dbc.Col(datepick, width=4)
            ]
        ),
        dbc.Row(
            table
        ),
    ], style={'backgroundColor': '#faf9f9'}),
    # graphs resulting from modified table
    html.Div(dcc.Graph(id='key_graph_l'))
],
style={'backgroundColor': '#faf9f9'})


# add callback functions
@app.callback(
    Output('datatable', 'data'),
    [
        Input('choose_cat', 'value'),
        Input('choose_loc', 'value'),
        Input('choose_date', 'start_date'),
        Input('choose_date', 'end_date')
    ]
)
def update_table(choose_cat, choose_loc, start_date, end_date):
    df = ti_data.copy()
    df['date'] = pd.to_datetime(df['date'])
    df['date'] = df['date'].dt.date
    if choose_cat is not None:
        df = df[df['category'] == choose_cat]
    if choose_loc is not None:
        df = df[df['locale'] == choose_loc]
    if start_date is not None and end_date is not None:
        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
        df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
    data = df.to_dict('records')
    return data


@app.callback(
    Output('datatable', 'style_data_conditional'),
    Input('datatable', 'selected_columns')
)
def update_styles(selected_columns):
    return [{
        'if': {'column_id': column},
        'background_color': '#D2F3FF'
    } for column in selected_columns]

@app.callback(
    Output('key_graph_l', 'figure'),
    [
        Input('choose_date', 'start_date'),
        Input('choose_date', 'end_date'),
        Input('choose_cat', 'value'),
        Input('choose_loc', 'value')
    ]
)

def update_key_l(choose_loc, choose_cat, start_date, end_date):
    df = ti_data.copy()
    if choose_cat is not None:
        df = df[df['category'] == choose_cat]
    if choose_loc is not None:
        df = df[df['locale'] == choose_loc]
    if start_date is not None and end_date is not None:
        df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
        df = df.sort_values('total_count', ascending=False)[:25]
        figure = px.scatter(df, x='keyword', y='date', color='locale', size='total_count',labels={'keyword': 'Keyword', 'total_count': 'Total Count', 'locale': 'Locale', 'date': 'Date'},
                            title='Weighing top words accross locales')

    return figure


# requirements for beanstalk (aws)
if __name__ == '__main__':
    app.run_server(debug=True)
1

1 Answers

1
votes

The reason for the error is that the order of the arguments in the callback function is different. The error occurs because the date format that is set when there is no calendar selection does not match the date format handled in Dash.

# Importing needed libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import random
import datetime
import plotly.graph_objects as go
from jupyter_dash import JupyterDash

# Reading the dataframe
df = pd.read_csv('./beanstalk_app/ti_data_ti_dash_v1.csv')

categories = df['category']
locales = df['locale']

# clean dataframe
ti_data = df.copy()
ti_data = ti_data.sample(4) # sample data

# Contents of the app
# 1.Controls
# 1.1 Dropdown list

locs = dcc.Dropdown(id='choose_loc',
                    options=[
                        {
                            'label': locale, 'value': locale
                        } for locale in locales.unique()
                    ],
                    placeholder='Select Locale')

cats = dcc.Dropdown(id='choose_cat',
                    options=[
                        {
                            'label': c, 'value': c
                        } for c in categories.unique()
                    ],
                    placeholder='Select Category')


# 1.2 DatePicker
datepick = dcc.DatePickerRange(
    id='choose_date',
    min_date_allowed=df.date.min(),
    max_date_allowed=df.date.max(),
    initial_visible_month=df.date.min(),
    clearable=True,
    start_date=df.date.min(),
    end_date=df.date.max()
)


# 2.Interactive table
table = dash_table.DataTable(
    id='datatable',
    columns=[
            {"name": i, "id": i, "selectable": True, "presentation": "markdown"}
            if i == "google_query"
            else {"name": i, "id": i, "selectable": True}
            for i in df.columns
        ],
    data=df.to_dict('records'),
    editable=False,
    filter_action="native",
    sort_action="native",
    sort_mode="multi",
    column_selectable="single",
    row_selectable="multi",
    row_deletable=True,
    selected_columns=[],
    selected_rows=[],
    page_action="native",
    page_current=0,
    page_size=10,
    style_cell={
        'whiteSpace': 'normal',
        'height': 'auto',
    },

)

# Initialize the app
app = dash.Dash(__name__)

app.title = 'Dot Graph Demo - All Entities'
app.layout = html.Div([
    # modifiable table
    dbc.Container([
        dbc.Row(
            [
                dbc.Col(locs, width=4),
                dbc.Col(cats, width=4),
                dbc.Col(datepick, width=4)
            ]
        ),
        dbc.Row(
            table
        ),
    ], style={'backgroundColor': '#faf9f9'}),
    # graphs resulting from modified table
    html.Div(dcc.Graph(id='key_graph_l'))
],
style={'backgroundColor': '#faf9f9'})


# add callback functions
@app.callback(
    Output('datatable', 'data'),
    [
        Input('choose_cat', 'value'),
        Input('choose_loc', 'value'),
        Input('choose_date', 'start_date'),
        Input('choose_date', 'end_date')
    ]
)
def update_table(choose_cat, choose_loc, start_date, end_date):
    df = ti_data.copy()
    # df['date'] = pd.to_datetime(df['date'])
    # df['date'] = df['date'].dt.date
    if choose_cat is not None:
        df = df[df['category'] == choose_cat]
    if choose_loc is not None:
        df = df[df['locale'] == choose_loc]
    if start_date is not None and end_date is not None:
        # start_date = datetime.datetime.strptime(start_date, "%Y-%m-%dT00:00:00").date()
        # end_date = datetime.datetime.strptime(end_date, "%Y-%m-%dT00:00:00").date()
        df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
    data = df.to_dict('records')
    return data


@app.callback(
    Output('datatable', 'style_data_conditional'),
    Input('datatable', 'selected_columns')
)
def update_styles(selected_columns):
    return [{
        'if': {'column_id': column},
        'background_color': '#D2F3FF'
    } for column in selected_columns]

@app.callback(
    Output('key_graph_l', 'figure'),
    [
        Input('choose_cat', 'value'),
        Input('choose_loc', 'value'),
        Input('choose_date', 'start_date'),
        Input('choose_date', 'end_date')
    ]
)

def update_key_l(choose_cat, choose_loc, start_date, end_date):
    df = ti_data.copy()
    if choose_cat is not None:
        df = df[df['category'] == choose_cat]
    if choose_loc is not None:
        df = df[df['locale'] == choose_loc]
    if start_date is not None and end_date is not None:
        df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
        df = df.sort_values('total_count', ascending=False)[:25]
        figure = px.scatter(df, x='keyword', y='date', color='locale', size='total_count',labels={'keyword': 'Keyword', 'total_count': 'Total Count', 'locale': 'Locale', 'date': 'Date'},
                            title='Weighing top words accross locales')

    return figure


# requirements for beanstalk (aws)
if __name__ == '__main__':
    app.run_server(debug=True)

enter image description here