C. Haeberlen
C. Haeberlen

Reputation: 39

formating datetime in bokeh hover tool

I am trying to have a properly formated date in bokeh when using hovertool and ploting data from a pandas dataframe. I think I tried all solution I have seen proposed around but none is working. With the example code below, I obtain this:

enter image description here

import pandas as pd
import datetime
from datetime import datetime


from bokeh.plotting import figure, show, gridplot
from bokeh.io import output_notebook, push_notebook


from bokeh.models.formatters import DatetimeTickFormatter
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
from bokeh.models import LinearAxis, Range1d

output_notebook()



data  = [["2022-08-05", 25,545,1],["2022-08-06",33,543,0],["2022-08-07",17,542,1]]
df_test = pd.DataFrame(data, columns=['Date','sum','size','present'])
df4 = df_test.set_index('Date')
df4.index = pd.to_datetime(df4.index)

Source = ColumnDataSource(data={'date' : df4.index, 
                                'percent' : 100*df4['sum']/df4['size']})

hover = HoverTool(tooltips = [('Date', '@date'),('Percent', '@percent')],
                  formatters = {'@date' : 'datetime'}, mode='vline')



f2 = figure(plot_height=400, plot_width=800,x_axis_label="Date",y_axis_label="Pourcentage de grises",\
            x_axis_type="datetime")

l1 = f2.circle(x = 'date',y = "percent", source=Source, line_width=4,color="sandybrown",legend_label='% gris',
              )


f2.legend.location = "top_right"
f2.legend.click_policy="hide"

f2.add_tools(hover)

show(f2)

Upvotes: 0

Views: 87

Answers (1)

Baron Legendre
Baron Legendre

Reputation: 2188

Percentage(%) is a format, therefore we don't multiply 100,
@date{%F} is equivalent to @date{%Y-%m-%d}

Source = ColumnDataSource(data={'date' : df4.index,
                                'percent' : df4['sum']/df4['size']})
hover = HoverTool(tooltips = [('Date', '@date{%F}'),('Percent', '@percent{%0.2f}')],
                  formatters = {'@date' : 'datetime'}, mode='vline')

enter image description here

from bokeh.models.formatters import NumeralTickFormatter
f2.yaxis.formatter = NumeralTickFormatter(format='0.00 %')

enter image description here

Upvotes: 1

Related Questions