Creating Marks on Slider from Dictionary


I am working on creating a dashboard with a slider to filter data by time. I am having some issues creating date marks on the slider that are dynamic and equally spaced out. My dates are stored in a dictionary with the following format:

{0: '2020-01-03',
 1: '2020-01-04',
 2: '2020-01-05',
 n: 'DateN'}

Here is a reproducible example:

#Import packages
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import time
from datetime import date, datetime

#Load data
who_data = pd.read_csv("")
who_data['Date_reported_string'] = who_data['Date_reported'].copy()

#Create slider dictionary
slider_options = dict((d_key, d_val) for d_key, d_val in enumerate(sorted(who_data['Date_reported_string'].unique())))

#Create array of equally spaced out dates
x = np.linspace(min(slider_options.keys()), max(slider_options.keys()), 10,dtype=int)
x = x.round(0)

#Dash App layout
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
        dcc.Tab(label="Slider Example",
                        html.Label(dcc.Markdown('''**Choose a date: **''')),
                                   min = min(slider_options.keys()),
                                   max = max(slider_options.keys()),                                   
                                   value = max(slider_options.keys()),
                                   marks = {i: str(i) for i in range(x[0],x[-1]) if i %75 ==0}
                    ],style={'width': '100%','display': 'inline-block','text-align': 'center'}),
                        html.Label('Date selected'),

def date_show(date_value):
    return date_value


I want to get the actual dates from the dictionary instead of the keys. Iโ€™ve tried making a list out of the dictionary values like this:


However, when I stick date_list in place of x in the marks argument, I get a Type error that reads: โ€˜strโ€™ object cannot be interpreted as an integer. Not sure how to solve this one.

Can someone help me figure this out? Iโ€™m stuck and not sure of how to proceed. Any help would be appreciated!

Hi @plotme1

Try changing the marks to:

marks = {i: slider_options[i] for i in range(x[0], x[-1]) if i % 75 == 0}

and then the callback:

return slider_options[date_value]
1 Like

Thank you so much! Works perfectly!

1 Like