我正在研究您应该能够运行的示例,
如您所见,一切看起来都很好,但是当我尝试在示例中使用日期格式为20-08-2019
(%d-%m-%y)的示例时,
破折号滑块不起作用,我尝试使用to_datetime转换此df['year']
,进行许多其他转换,但是我仍然收到错误:
Invalid argument `value` passed into Slider with ID "year-slider".
Expected `number`.
Was supplied type `string`.
Value provided: "2018-08-24T00:00:00"
代码:
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)
答案 0 :(得分:0)
Dash Slider对象仅处理int
/ float
,因此您需要先将日期转换为int
,例如Unix / epoch时间戳,然后将标签映射到任何一个您想要的str
日期格式。
您提供的示例适用于dash 1.1.1
的当前版本,因此-在手头没有可用的示例的情况下-我将在此处进行一些猜测。假设您使用的是pandas
和numpy
(根据您提供的示例),这应该可以:
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
)