带有 Plotly Dash 的日期滑块不起作用 [英] Date slider with Plotly Dash does not work

查看:59
本文介绍了带有 Plotly Dash 的日期滑块不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用日期时间滑块构建一个破折号应用程序,但以下代码不起作用 - url 显示错误加载布局".我在做一些愚蠢的事情,还是在日期时间对象上构建滑块所需的任何技巧?可重现的代码如下:

I am trying to build a dash app with a datetime slider, but the following code does not work - the url displays "Error loading layout". Am I doing something stupid, or are the any tricks needed to build a slider on datetime objects? Reproducible code follows:

import dash
import dash_core_components as dcc
import dash_html_components as html
import datetime

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(0, 10)]

app = dash.Dash()

app.layout = html.Div([
    html.Label('Slider'),
    dcc.RangeSlider(min=min(date_list), 
                    max=max(date_list), 
                    value=min(date_list))
    ])

if __name__ == '__main__':
    app.run_server()

推荐答案

Plotly-Dash 目前不支持日期时间对象.

Plotly-Dash does currently not support datetime objects.

在我对另一个问题的回答中描述了您问题的解决方案 Ploly datetime

A solution for you problem is to described in my answer to an other question Ploly datetime

一种可能的解决方案是在初始化时使用两个不同的参数:

One possible solution is to use two different arguments at the initialization:

  • 价值
  • 标记

使用 Pandas 生成时间戳的示例:

Example by using pandas for timestamp generation:

需要导入:

import pandas as pd
import time

一些需要的功能:

daterange = pd.date_range(start='2017',end='2018',freq='W')

def unixTimeMillis(dt):
    ''' Convert datetime to unix timestamp '''
    return int(time.mktime(dt.timetuple()))

def unixToDatetime(unix):
    ''' Convert unix timestamp to datetime. '''
    return pd.to_datetime(unix,unit='s')

def getMarks(start, end, Nth=100):
    ''' Returns the marks for labeling. 
        Every Nth value will be used.
    '''

    result = {}
    for i, date in enumerate(daterange):
        if(i%Nth == 1):
            # Append value to dict
            result[unixTimeMillis(date)] = str(date.strftime('%Y-%m-%d'))

    return result

对于 RangeSlider 对象,您可以像这样初始化它:

For the RangeSlider object you can initialize it like this:

dcc.RangeSlider(
                id='year_slider',
                min = unixTimeMillis(daterange.min()),
                max = unixTimeMillis(daterange.max()),
                value = [unixTimeMillis(daterange.min()),
                         unixTimeMillis(daterange.max())],
                marks=getMarks(daterange.min(),
                            daterange.max())
            )

这篇关于带有 Plotly Dash 的日期滑块不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆