Bokeh自定义JS回调日期范围滑块

2022-04-07 00:00:00 python bokeh callback

问题描述

我尝试创建一个交互式图表,它绘制日期X上的Y值。到目前为止还不错。现在我想通过DateRangeSlider调整x轴的限制xmin和xmax,但我不理解js回调函数(我想在最后有一个独立的html文件),而且我甚至不知道如何从函数内部打印值并且不会产生任何错误,所以我不知道现在该怎么办。

以下是代码的运行示例:

import numpy as np
import pandas as pd
from datetime import datetime
from bokeh.models import ColumnDataSource, DatetimeTickFormatter, HoverTool
from bokeh.models.widgets import DateRangeSlider
from bokeh.layouts import layout, column
from bokeh.models.callbacks import CustomJS
from bokeh.plotting import figure, output_file, show, save

datesX = pd.date_range(start='1/1/2018', periods=100)
valuesY = pd.DataFrame(np.random.randint(0,25,size=(100, 1)), columns=list('A'))

source = ColumnDataSource(data={'x': datesX, 'y': valuesY['A']}) 

# output to static HTML file
output_file('file.html')

hover = HoverTool(tooltips=[('Timestamp', '@x{%Y-%m-%d %H:%M:%S}'), ('Value', '@y')],
                           formatters={'x': 'datetime'},)
    
date_range_slider = DateRangeSlider(title="Zeitrahmen", start=datesX[0], end=datesX[99], 
                                        value=(datesX[0], datesX[99]), step=1, width=300)

# create a new plot with a title and axis labels
p = figure(title='file1', x_axis_label='Date', y_axis_label='yValue',  x_axis_type='datetime', 
               tools="pan, wheel_zoom, box_zoom, reset", plot_width=300, plot_height=200)

# add a line renderer with legend and line thickness
    
p.line(x='x', y='y', source=source, line_width=2)
p.add_tools(hover)
       
callback = CustomJS(args=dict(source=source), code="""

    ##### what to do???

    source.change.emit();
    """)
    
date_range_slider.js_on_change('value', callback)
layout = column(p, date_range_slider)

# show the results
show(layout)

我试图调整和适应stackoverflow和bokeh演示中类似的人的例子,但我没有设法生成运行的代码。希望一切都清楚了,您能帮忙。


解决方案

更改滑块时需要创建新的source.data。要做到这一点,您还需要不更改的备份&q;source,并将其用作包含哪些数据的参考。将这两个参数作为参数传递给回调函数将使它们可用于Java代码。

datesX = pd.date_range(start='1/1/2018', periods=100)
valuesY = pd.DataFrame(np.random.randint(0,25,size=(100, 1)), columns=list('A'))

# keep track of the unchanged, y-axis values
source = ColumnDataSource(data={'x': datesX, 'y': valuesY['A']}) 
source2 = ColumnDataSource(data={'x': datesX, 'y': valuesY['A']})

# output to static HTML file
output_file('file.html')

hover = HoverTool(
    tooltips=[('Timestamp', '@x{%Y-%m-%d %H:%M:%S}'), ('Value', '@y')],
    formatters={'x': 'datetime'},)
    
date_range_slider = DateRangeSlider(
    title="Zeitrahmen", start=datesX[0], end=datesX[99],
    value=(datesX[0], datesX[99]), step=1, width=300)

# create a new plot with a title and axis labels
p = figure(
    title='file1', x_axis_label='Date', y_axis_label='yValue',
    y_range=(0, 30), x_axis_type='datetime',
    tools="pan, wheel_zoom, box_zoom, reset",
    plot_width=600, plot_height=200)

# add a line renderer with legend and line thickness
    
p.line(x='x', y='y', source=source, line_width=2)
p.add_tools(hover)

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());
    
    const data = source.data;
    const ref = ref_source.data;
    
    const from_pos = ref["x"].indexOf(date_from);
    // add + 1 if you want inclusive end date
    const to_pos = ref["x"].indexOf(date_to);
        
    // re-create the source data from "reference"
    data["y"] = ref["y"].slice(from_pos, to_pos);
    data["x"] = ref["x"].slice(from_pos, to_pos);
    
    source.change.emit();
    """)
    
date_range_slider.js_on_change('value', callback)
layout = column(p, date_range_slider)

# show the results
show(layout)

相关文章