我正在尝试使用plotly和dash在python中构造一个仪表板,该仪表板将使用滑块更改图形的范围(x轴)。 x轴包含日期。
我正在跟随plotly网站(https://dash.plot.ly/dash-core-components/rangeslider)上的滑块的示例。滑块示例在我的环境中运行良好。当我用数据框中的最小和最大日期值替换滑块的最小值,最大值时,如下所示:
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.RangeSlider(
id='slider',
min = df['date'].min(),
max = df['date'].max()
),
html.Div(id='slider-container')
])
我的浏览器抛出以下错误:“加载依赖项时出错”。我数据框中的“日期”是pandas._libs.tslibs.timestamps.Timestamp
我已经卸载并重新安装了dash,dash-renderer,dash-html-components,dash-core-components并按照https://github.com/plotly/dash/issues/82
关于出什么问题的任何建议?我的示例的完整代码是:
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.RangeSlider(
id='slider',
min = df['date'].min(),
max = df['date'].max()
),
html.Div(id='slider-container') ])
@app.callback(
dash.dependencies.Output('slider-container', 'children'),
[dash.dependencies.Input('slider', 'value')])
def update_output(value):
return 'You have selected "{}"'.format(value)
if __name__ == '__main__':
app.run_server(debug=True)
如果将滑块值设置为:
dcc.RangeSlider(
id='slider',
min=0,
max=20,
step=0.5,
value=[5, 15]
答案 0 :(得分:1)
似乎RangeSlider
无法直接与Timestamp
对象一起使用。您需要将它们转换为数值(POSIX)时间戳才能与滑块一起使用,然后再次将它们转换为回调函数中的对象。
以下对我有用:
import dash
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# Demo dataframe with a 'date' column
df = pd.DataFrame({'date': pd.to_datetime(np.linspace(1500000000, 1550000000, 9), unit='s')})
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.RangeSlider(
id='slider',
min=df['date'].min().timestamp(),
max=df['date'].max().timestamp(),
value=[df['date'].min().timestamp(), df['date'].max().timestamp()],
),
html.Div(id='slider-container')
])
@app.callback(
dash.dependencies.Output('slider-container', 'children'),
[dash.dependencies.Input('slider', 'value')])
def update_output(value):
if value:
return 'You have selected "{}"'.format(list(pd.to_datetime(value, unit='s')))
if __name__ == '__main__':
app.run_server(debug=True)