I want to make a DateRangeSlider.
I have written the following code but I have two problems:
1- When I change the DateRangeSlider, the chart is hidden! (disappears)
2- When I change the DateRangeSlider, the X-axis does not change.
please guide me.
from bokeh.plotting import figure, output_file, show
import pandas as pd
from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource,HoverTool,Range1d,DatetimeTicker,DatetimeTickFormatter, ColumnDataSource,ColumnDataSource,HoverTool
from bokeh.models import DateRangeSlider
import numpy as np
from bokeh.layouts import layout, column
from bokeh.models.callbacks import CustomJS
from bokeh.plotting import figure, output_file, show, save
#Read csv file
dataset= pd.read_csv(r"Example.csv")
Date1=dataset["Date"]
dataset['Date'] = pd.to_datetime(dataset['Date'])
STD= dataset["STD"]
Date5=list(dataset['Date'])
datase = pd.to_datetime(Date5, format='%Y-%B-%d')
# keep track of the unchanged, y-axis values
source = ColumnDataSource(data={'x': dataset['Date'], 'y': STD})
source2 = ColumnDataSource(data={'x': dataset['Date'], 'y': STD})
# output to static HTML file
output_file('sliders.html')
hover = HoverTool(
tooltips=[('Date', '@x{%F}'), ('STD', '@y')],
formatters={'@x': 'datetime'},)
TOOLS="pan,wheel_zoom,box_zoom,reset,save"
ss=list(dataset['Date'])
yr1 = Range1d(start=-0.2, end=0.2)
xr1 = Range1d(start=ss[0] , end=ss[-1])
p = figure(x_range=xr1,y_range=yr1,tools=TOOLS, width=800, height=500)
# add a line renderer with legend and line thickness
p.line(x='x',y='y',source=source, line_color="#DAA520", line_width=2,alpha=1)
p.xaxis.ticker = DatetimeTicker(desired_num_ticks=12)
p.xaxis.formatter = DatetimeTickFormatter(days=["%d-%b-%Y"],months=["%d-%b-%Y"])
p.xaxis.major_label_orientation = 45
p.add_tools(hover)
plot_width = 800
startdate=datase[0]
enddate=datase[-1]
slider = DateRangeSlider(start=startdate, end=enddate, value=(startdate,enddate),
step=1, title='Date')
# Adding callback code
callback = CustomJS(args=dict(source=source, ref_source=source2), code="""
// 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();
""")
slider.js_on_change('value', callback)
# Arrange plots and widgets in layouts
layout = column(slider, p)
output_file('exam.html')
show(layout)