1

我正在研究您应该能够运行的示例,因为您可以看到一切看起来都很好,但是当我尝试在我的示例中应用它时,我有这种格式的日期:20-08-2019(%d-%m-%y)破折号滑块不起作用,我尝试df['year']使用 to_datetime 进行转换,任何其他转换,但我仍然收到错误:

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)
4

1 回答 1

2

Dash Slider 对象仅处理int/ float,因此您需要首先将日期转换为int,例如 Unix/epoch 时间戳,然后将标签映射到str您希望的任何日期格式。

您提供的示例适用于当前版本的dash 1.1.1so - 手头没有工作示例 - 我将在这里做一些猜测。假设您正在使用pandasand 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
)
于 2019-08-22T13:21:35.373 回答