首页 > 解决方案 > 散景 DateRangeSlider 行为不端

问题描述

我刚开始使用 Boken 并正在努力使用 DateRangeSlider。我没有找到太多文档,但我使用了一些我在网上找到的代码并设法让它工作......或多或少。

问题是,如果您尝试运行我编写的代码,有时切片器会工作,而有时图表会消失。

2017 年 9 月 16 日至 2021 年 4 月 29 日: 2017 年 9 月 16 日 - 2021 年 4 月 29 日.

所以,我需要了解为什么它并不总是有效,此外,有没有办法使用日期范围内的列中的值,以便仅显示可用日期(周一至周五)?或者我正在尝试做的事情是否有另一种解决方案,也许是 2 个滑块??不知道

我用共享数据替换了我的数据,因为在这种情况下,我没有每天的数据,而只有工作日的数据。

import pandas as pd
import pandas_datareader as web
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource,HoverTool,DateRangeSlider,CustomJS
from bokeh.layouts import column


company = 'TSLA'
df = web.DataReader('TSLA',data_source = 'yahoo', start = '2012-01-01')
tools_to_show = 'pan,crosshair,wheel_zoom,zoom_in,zoom_out,box_zoom,save,reset'

source = ColumnDataSource(data={
    'date' : df.index.values,
    'close' : df['Close'],
    'date_formatted' : df.index.astype(str)
})

source2 = ColumnDataSource(data={
    'date' : df.index.values,
    'close' : df['Close'],
    'date_formatted' : df.index.astype(str)
})

date_range_slider = DateRangeSlider(value=(min(df.index.values), max(df.index.values)), 
                                    start=min(df.index.values), end=max(df.index.values), step=1)    

callback = CustomJS(args=dict(source=source, ref_source=source2), code="""
    // print out array of date from, date to
    console.log(cb_obj.value); 
    // dates returned from slider are not at round intervals and include time;
    const date_from = Date.parse(new Date(cb_obj.value[0]).toDateString());
    const date_to = Date.parse(new Date(cb_obj.value[1]).toDateString());
    console.log(date_from, date_to)

    // Creating the Data Sources
    const data = source.data;
    const ref = ref_source.data;

    // Creating new Array and appending correctly parsed dates
    let new_ref = []
    
    ref["date"].forEach(elem => {
        elem = Date.parse(new Date(elem).toDateString());
        new_ref.push(elem);
        console.log(elem);
    })

    // Creating Indices with new Array
    const from_pos = new_ref.indexOf(date_from);
    const to_pos = new_ref.indexOf(date_to) + 1;
   
    
    // re-create the source data from "reference"
    data["close"] = ref["close"].slice(from_pos, to_pos);
    data["date"] = ref["date"].slice(from_pos, to_pos);

    source.change.emit();
    """)

p = figure(plot_height =800, plot_width = 1200,
           x_axis_label='Date', y_axis_label='Close price USD $',x_axis_type='datetime',
           tools=tools_to_show,title="Stock Price")

p.line(source=source, x = 'date', y='close',line_width=2)
p.add_tools(HoverTool(
    tooltips=[
        ( 'date','@date_formatted'),
        ( 'close','$@close{0.2f}')
    ],mode='vline'))

layout = column(p,date_range_slider)

date_range_slider.js_on_change('value', callback)
output_file('close_chart.html')
show(layout)

标签: pythonjupyter-notebookbokehspyder

解决方案


推荐阅读