Reputation:
I am working on example that you should be able to run,
as you can see everything looks fine, but when i am trying to apply this on my example where i have dates in this format : 20-08-2019
(%d-%m-%y)
Dash slider not working, i've tried to convert this df['year']
using to_datetime, any many others conversions but i am still receiving error:
Invalid argument `value` passed into Slider with ID "year-slider".
Expected `number`.
Was supplied type `string`.
Value provided: "2018-08-24T00:00:00"
code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
df = pd.read_csv(
'https://raw.githubusercontent.com/plotly/'
'datasets/master/gapminderDataFiveYear.csv')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
id='year-slider',
min=df['year'].min(),
max=df['year'].max(),
value=df['year'].min(),
marks={str(year): str(year) for year in df['year'].unique()},
step=None
)
])
@app.callback(
Output('graph-with-slider', 'figure'),
[Input('year-slider', 'value')])
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]
traces = []
for i in filtered_df.continent.unique():
df_by_continent = filtered_df[filtered_df['continent'] == i]
traces.append(go.Scatter(
x=df_by_continent['gdpPercap'],
y=df_by_continent['lifeExp'],
text=df_by_continent['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
))
return {
'data': traces,
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(debug=True)
Upvotes: 1
Views: 2781
Reputation: 330
Dash Slider objects only deal with int
/float
, so you will need to first convert the dates to int
, such as Unix/epoch timestamps and then map the labels to whichever str
date format you wish.
The example you provided works with the current version of dash 1.1.1
so - without a working example at hand - I will do some guesswork here. Assuming that you are using pandas
and numpy
, based on the example you provided, this should work:
import numpy as np
df['epoch_dt'] = df['year'].astype(np.int64) // 1e9
dcc.Slider(
id='year-slider',
min=df['epoch_dt'].min(),
max=df['epoch_dt'].max(),
value=df['epoch_dt'].min(),
marks={str(epoch): str(year) for epoch, year in df[['epoch_dt', 'year']].drop_duplicates().set_index('epoch_dt')['year'].to_dict()},
step=None
)
Upvotes: 2