# Slider not working

**URL:** <https://community.plotly.com/t/slider-not-working/8471>\
**Category:** Dash Python\
**Created:** [February 20, 2018, 7:26am UTC](https://community.plotly.com/t/slider-not-working/8471 "2018-02-20T07:26:59Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![ankittri](https://avatars.discourse-cdn.com/v4/letter/a/9fc29f/32.png) [@ankittri](https://community.plotly.com/u/ankittri)\
**Post date:** [February 20, 2018, 7:26am UTC](https://community.plotly.com/t/slider-not-working/8471/1 "2018-02-20T07:26:59Z")

</div>

Hi Guys,

Following is the code for a scatter plot with year-month input in form of slider.

import dash  
import dash\_core\_components as dcc  
import dash\_html\_components as html  
import plotly.graph\_objs as go  
import pandas as pd  
import sqlalchemy as sq  
from datetime import datetime

engine\_prd = sq.create\_engine(“connection URL”)  
df=pd.read\_sql(“select substring(order\_created\_date,1,4)|| ‘-’ || substring(order\_created\_date,5,2) as year\_month,master\_category, article\_type,brand,sum(item\_revenue\_inc\_cashback+shipping\_charges\_shipment+gift\_charges\_shipment+cod\_charges\_shipment) as revenue,sum(item\_revenue\_inc\_cashback)/count(distinct order\_group\_id) as ASP,count(distinct order\_group\_id) as num\_orders, sum(order\_quantity) as order\_quanitity from fact\_core\_item where order\_created\_date\>20170101 and store\_id=1 and (is\_realised=1 or is\_shipped=1) group by year\_month,master\_category,article\_type,brand ;”,engine\_prd)

year\_month=df[‘year\_month’].unique()

app=dash.Dash()

app.layout=html.Div([  
dcc.Graph(id=‘graph-with-dropdown’),  
dcc.Slider(  
id=‘year-month-slider’,  
min=‘2017-01’,  
max=‘2018-02’,  
value=‘2018-02’,  
step=None,  
#marks={i: ‘Label {}’.format(i) for i in df[‘year\_month’].unique()},  
marks={str(yearm) : str(yearm) for yearm in df[‘year\_month’].unique()}

```
	)
])

```

@app.callback(  
dash.dependencies.Output(‘graph-with-dropdown’, ‘figure’),  
[dash.dependencies.Input(‘year-month-slider’, ‘value’)])

def update\_figure(selected\_year\_month):  
filtered\_df=df[df.year\_month==selected\_year\_month]  
traces=[]

```
for i in filtered_df.master_category.unique():
	df_by_master_category=filtered_df[filtered_df['master_category'] == i]

	traces.append(go.Scatter(
		 x=df_by_master_category['revenue'],
		 y=df_by_master_category['asp'],
		 text=df_by_master_category['brand']+'-'+df_by_master_category['article_type'],
		 mode='markers',
		 opacity=0.3,
		 marker={
		 'size':15,
		 'line': {'width': 0.5, 'color': 'white'}
	 	},
	 	name=i
	 ))
return {
	'data': traces,
    'layout': go.Layout(
        xaxis={'type': 'log', 'title': 'Total Revenue'},
        yaxis={'title': 'Average Selling Price'},
        #margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
        legend={'x': 0, 'y': 1},
        hovermode='closest'
    )

}

```

if **name** == ‘ **main** ’:  
app.run\_server()

Following is the df.head() output:

| year\_month | master\_category | article\_type | brand | revenue | asp | num\_orders | order\_quanitity |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | 2017-01 | Accessories | Accessory Gift Set | Hakashi | 9.274500e+02 | 927.450000 | 1 |

The plot’s slider is not working. Will be great if someone can point out the error.

---

<div class="post-metadata">

**Author:** ![mikesmith1611](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/mikesmith1611/32/2130_2.png) [@mikesmith1611](https://community.plotly.com/u/mikesmith1611)\
**Post date:** [February 20, 2018, 4:14pm UTC](https://community.plotly.com/t/slider-not-working/8471/2 "2018-02-20T16:14:59Z")

</div>

> [@ankittri](#):
>
> year\_month==selected\_year\_month

Is selected\_year\_month definitely the same data type as df.year\_month?  
According to your ‘marks’ in your slider selected\_year\_month will be a sting. The values df.year\_month may be integers?

---

<div class="post-metadata">

**Author:** ![ankittri](https://avatars.discourse-cdn.com/v4/letter/a/9fc29f/32.png) [@ankittri](https://community.plotly.com/u/ankittri)\
**Post date:** [February 21, 2018, 6:33am UTC](https://community.plotly.com/t/slider-not-working/8471/3 "2018-02-21T06:33:53Z")

</div>

Hey Mike

Year-month is a string datatype. To stay safe I also used:  
df[‘year\_month’]=df[‘year\_month’].astype(str) initially. Yet the slider isn’t working.

---

<div class="post-metadata">

**Author:** ![mikesmith1611](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/mikesmith1611/32/2130_2.png) [@mikesmith1611](https://community.plotly.com/u/mikesmith1611)\
**Post date:** [February 21, 2018, 9:47am UTC](https://community.plotly.com/t/slider-not-working/8471/4 "2018-02-21T09:47:03Z")

</div>

What do you mean by insn’t working? Are there any errors in the console?

---

<div class="post-metadata">

**Author:** ![ankittri](https://avatars.discourse-cdn.com/v4/letter/a/9fc29f/32.png) [@ankittri](https://community.plotly.com/u/ankittri)\
**Post date:** [February 21, 2018, 10:03am UTC](https://community.plotly.com/t/slider-not-working/8471/5 "2018-02-21T10:03:16Z")

</div>

![46%20PM](https://us1.discourse-cdn.com/flex024/uploads/plot/original/2X/8/8397e431efa13ef9749043cd06183a0bb4008791.png)

Attached is the screenshot. First, the labels on slider don’t appear. Secondly, chart turns blank if clicked anywhere on slider.

---

<div class="post-metadata">

**Author:** ![mikesmith1611](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/mikesmith1611/32/2130_2.png) [@mikesmith1611](https://community.plotly.com/u/mikesmith1611)\
**Post date:** [February 21, 2018, 11:49am UTC](https://community.plotly.com/t/slider-not-working/8471/6 "2018-02-21T11:49:17Z")

</div>

So I think the problem is the way you are defining the Slider parameters compared to what the component expects. The keys in the marks dictionary seem to want to be integers (or stringified ints) so that the min and max values can be treated as a range. You can then use the State of the marks to get the date label eg:

```python
app.layout=html.Div([
    dcc.Graph(id=‘graph-with-dropdown’),
    dcc.Slider(
        id=‘year-month-slider’,
        min=0,
        max=len(df[‘year_month’].unique()), # max value is the number of unique values
        value=0, # set the value to 0
        marks={i : str(yearm) for i, yearm in enumerate(df[‘year_month’].unique())} # enumerate the dates
	)
])

@app.callback(
    dash.dependencies.Output(‘graph-with-dropdown’, ‘figure’),
    [dash.dependencies.Input(‘year-month-slider’, ‘value’)],
    [dash.dependencies.State(‘year-month-slider’, ‘marks’)]) # Add the marks as a State
def update_figure(selected_year_month_key, marks):
    selected_year_month = marks[str(selected_year_month_key)] # use the selected marker to get date
    filtered_df=df[df.year_month==selected_year_month]
    traces=[]

    for i in filtered_df.master_category.unique():
        df_by_master_category=filtered_df[filtered_df['master_category'] == i]
        traces.append(go.Scatter(
            x=df_by_master_category['revenue'],
            y=df_by_master_category['asp'],
            text=df_by_master_category['brand']+'-'+df_by_master_category['article_type'],
            mode='markers',
            opacity=0.3,
            marker={
            'size':15,
            'line': {'width': 0.5, 'color': 'white'}
            },
            name=i
	 ))
    return {
            'data': traces,
            'layout': go.Layout(
            xaxis={'type': 'log', 'title': 'Total Revenue'},
            yaxis={'title': 'Average Selling Price'},
            legend={'x': 0, 'y': 1},
            hovermode='closest'
    )
}

```

---

<div class="post-metadata">

**Author:** ![ankittri](https://avatars.discourse-cdn.com/v4/letter/a/9fc29f/32.png) [@ankittri](https://community.plotly.com/u/ankittri)\
**Post date:** [February 22, 2018, 5:46am UTC](https://community.plotly.com/t/slider-not-working/8471/7 "2018-02-22T05:46:17Z")

</div>

That worked! Thanks so much for your help. I just have some queries to understand it better:

1. I don’t know much about ‘State’ and its usage. Is there a documentation regarding that?
2. In selected\_year\_month = marks[str(selected\_year\_month\_key)], why is str required over the selected\_year\_month\_key. Marks dictionary has ‘i’ (an integer) as key if I am correct.

Thanks again for your help.

---

<div class="post-metadata">

**Author:** ![mikesmith1611](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/mikesmith1611/32/2130_2.png) [@mikesmith1611](https://community.plotly.com/u/mikesmith1611)\
**Post date:** [February 22, 2018, 9:40am UTC](https://community.plotly.com/t/slider-not-working/8471/8 "2018-02-22T09:40:52Z")

</div>

No problem!

1. See here: [https://plot.ly/dash/state](https://plot.ly/dash/state)

2. This is probably a bug in the Slider component that assumes the dictionary keys for marks are of type string (JSON doesn’t accept integer keys I believe) and doesn’t attempt to convert them. Is this the case @chriddyp?

---

<div class="post-metadata">

**Author:** ![chriddyp](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/chriddyp/32/16855_2.png) [@chriddyp](https://community.plotly.com/u/chriddyp)\
**Post date:** [February 23, 2018, 2:23am UTC](https://community.plotly.com/t/slider-not-working/8471/9 "2018-02-23T02:23:49Z")

</div>

> [@mikesmith1611](#):
>
> This is probably a bug in the Slider component that assumes the dictionary keys for marks are of type string (JSON doesn’t accept integer keys I believe) and doesn’t attempt to convert them

That sounds right. In JavaScript and JSON, dictionary keys are strings. I logged the issue here: [Slider `marks` keys are only strings · Issue #163 · plotly/dash-core-components · GitHub](https://github.com/plotly/dash-core-components/issues/163)
