Reputation: 911
I am working on creating a dashboard with several sliders to filter data by time. I am having some issues creating date marks on the slider that are dynamically, 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 quick example of my code:
#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("https://covid19.who.int/WHO-COVID-19-global-data.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.Tabs([
dcc.Tab(label="Slider Example",
children=[
html.Div([
html.Label(dcc.Markdown('''**Choose a date: **''')),
dcc.Slider(id='slider',
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.Div([
html.Label('Date selected'),
html.P('',id='date_id')
],style={'text-align':'center'})
])
])
])
@app.callback(
Output('date_id','children'),
Input('slider','value'))
def date_show(date_value):
return date_value
app.run_server(host='0.0.0.0',port='8050')
The way this app is set up right now, the 10 equally spaced out dates are ignored and the code if i%75==0
determines how many dates appear in the slider. If I remove this chunk, all dates will appear on the slider overlapping each other which is not what I want.
Further, I want to get the actual dates (values) from the dictionary instead of the keys. I've tried making a list out of the dictionary values like this:
date_list=list(slider_options.values())
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.
Can someone help me figure this out? I'm stuck and not sure of how to proceed. Any help would be appreciated!
Thank you!
Upvotes: 1
Views: 2790
Reputation: 911
For anyone reading this looking for the answer, I posted the same question over on the Plotly Community Forum and was told to replace
str(i)
in the marks argument with
slider_options[i]
and that solution worked for me.
Upvotes: 1