问题
I am trying to recreate this Plotly example with Dash, but I cannot get the buttons and the range slider. Does anyone know how I can do this?
That's what I tried:
traces =[{
'x':df.index,
'y':df.level,
'type': 'scatter',
'mode': 'lines',
'name': 'a_level'
}]
graphs.append(dcc.Graph(
id='a_level',
figure={
'data': traces,
'layout': {
'type': 'date',
'rangeslider': {'visible':True},
'margin': {'b': 0, 'r': 10, 'l': 60, 't': 0}
}
}
)
回答1:
The RangeSlider
is a Dash Core Component, it's not an attribute of Graph
(which is also a Dash Core Component).
Here is a simple app layout:
import dash_core_components as dcc
app.layout = html.Div(children=[
html.H1('My Dash App'),
html.Div(
[
html.Label('From 2007 to 2017', id='time-range-label'),
dcc.RangeSlider(
id='year_slider',
min=1991,
max=2017,
value=[2007, 2017]
),
],
style={'margin-top': '20'}
),
html.Hr(),
dcc.Graph(id='my-graph')
])
Now you just have to define a callback that gets called every time the value of the RangeSlider
changes. This is the Input
that causes _update_graph
to get called.
You could have multiple inputs (e.g. a Dropdown
, another RangeSlider
, etc).
The Output
is always a single one. In this example it's the figure
attribute of the Graph
component.
# the value of RangeSlider causes Graph to update
@app.callback(
output=Output('my-graph', 'figure'),
inputs=[Input('year_slider', 'value')]
)
def _update_graph(year_range):
date_start = '{}-01-01'.format(year_range[0])
date_end = '{}-12-31'.format(year_range[1])
# etc...
A Dash Core Component could cause several components to update. For example, a RangeSlider
could cause a Label
to change.
# the value of RangeSlider causes Label to update
@app.callback(
output=Output('time-range-label', 'children'),
inputs=[Input('year_slider', 'value')]
)
def _update_time_range_label(year_range):
return 'From {} to {}'.format(year_range[0], year_range[1])
回答2:
rangeslider
is a property of xaxis
.
I use something like this:
app = dash.Dash(__name__, external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'])
app.layout = html.Div([
dcc.Graph(
id='bar_plot',
figure=go.Figure(
data=area,
layout=go.Layout(
xaxis={
'rangeslider': {'visible':True},
'rangeselector': {'visible':True, 'buttons':[{'step':'all'}, {'step':'day'}, {'step':'hour'}]}
},
)))
])
回答3:
I did something like this (with a df that has datetimeindex):
Function
def get__marks(f):
dates = {}
for z in f.index:
dates[f.index.get_loc(z)] = {}
dates[f.index.get_loc(z)] = str(z.month) + "-" + str(z.day)
return j
App Layout
dcc.RangeSlider(
id='range-slider',
updatemode='mouseup',
min=0,
max=len(df.index) - 1,
count=1,
step=1,
value=[0, len(df.index) - 1],
marks=get_marks(df),
)
来源:https://stackoverflow.com/questions/46519518/how-to-range-slider-and-selector-with-plotly-dash