Slider Callback Issue - Pandas DF

Completely and utterly stumped. I believe my issue lies in how I’m managing my pandas dataframe as I’m getting an error when I add another input to the callback (lengths not the same).

Once I try to add another input or an additional graph px.scatter (commented out below) it fails. Ideally I would like to have a range slider and date picker but am not able to figure it out.

The error messages I’m getting seem to be around the length not being the same as well as a value error.

Thanks in advance for the help.

import requests, json
from token_auth import refresh_token
from datetime import datetime, timedelta
import datetime as dt
import dash, dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd
import plotly.express as px
pd.options.plotting.backend = 'plotly'

#-------------------------------------------------------------------
#App Variables

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

colors = {'markers':'DarkOrange',
          'text': 'Black',
          'graph_background': 'rgb(220,220,220)'}

app.title = "Strava Dashboard"

#-------------------------------------------------------------------
#API Call
tokens = refresh_token()

url = f"http://www.strava.com/api/v3/athlete/activities/?per_page=200"
payload = {}
headers = {
'Authorization': f'Bearer {tokens}'
}

response = requests.request("GET", url, headers=headers, data = payload)
data = response.json()

df = pd.DataFrame(data)

app.layout = html.Div([

    html.H1("Strava Activities Dashboard", style={'text-align': 'center', 'color': colors['markers']}),

    html.Div([

            html.Div([
                html.H4(f'Date Range',style={'color': colors['markers']}),
                dcc.DatePickerRange(
                    id='date-range',
                    style={'color': colors['markers']},
                    start_date=datetime.now()
                )  
            ], className="four columns"),

            html.Div([
                html.H4('Activity Type', style={'color': colors['markers']}),
                dcc.Dropdown(
                    id='activity_type_dropdown',
                    options=[{'label': 'Ride', 'value': 'Ride'},
                             {'label': 'Run', 'value': 'Run'},
                             {'label': 'Swim', 'value': 'Swim'}],
                    value='Ride',   
                   ),
                ], className="four columns"),

            html.Div([
                html.H4('Distance Slider', style={'color': colors['markers']}),
                dcc.Slider(
                    id='distance-slider',
                    min=0,
                    max=70,
                    step=1,
                    marks={0: '0', 10:'10', 20:'20', 30:'30', 40:'40', 50: '50', 60: '60', 70: '70',},
                ),
            ], className="four columns"),
        
    ], className="row"),

    html.Br(),

    html.Div([

        html.Div([
                dcc.Graph(id='mile-distance-scatter'), 
                ], className="six columns"),

        html.Div([
            dcc.Graph(id='distance-range-scatter')
            ], className="six columns"),

    ], className="row"),
    ])


@app.callback(
    Output('mile-distance-scatter', 'figure'),
    Input('activity_type_dropdown', 'value')
    )

def distance_scatter(activity_type_filter):

    dff = df[df['type'] == activity_type_filter]

    graph_distance=round(dff['distance']*0.000621371,2)

    fig = px.scatter(x=dff['start_date_local'], y=graph_distance, hover_name=dff['name'])

    fig.update_traces(marker=dict(
                        color=colors['markers']))

    fig.update_layout(
    xaxis_title='Date',
    title='Distance',
    title_font_color=colors['text'],
    plot_bgcolor=colors['graph_background'],
    yaxis_title="Distance")

    return fig

@app.callback(
#     Output('distance-range-scatter', 'figure'),
#     [Input('distance-slider', 'value')]
#     )

#def distance_range(distance_filter):

#     dff = df[round(df['distance']*0.000621371,2) == distance_filter]

#     date = dff['start_date_local']
#     distance = dff['distance']

#     fig = px.scatter(x=date, y=distance)

#     fig.update_traces(marker=dict(
#                     color=colors['markers']))

#     fig.update_layout(
#     xaxis_title='Date',
#     yaxis_title="Elevation",
#     title='Elevation',
#     title_font_color=colors['text'],
#     plot_bgcolor=colors['graph_background'])

#     return fig

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

Welcome to Dash @bgallupp
I’m not sure what your graph_distance looks like, but try to plot your scatter like this:

fig = px.scatter(dff, x='start_date_local', y='distance', hover_name='name')

Thanks for the help Adam! I was actually able to resolve the cross filtering by indexing the data frame with the input type.

Now on to figuring out the date picker. :grinning:

1 Like