Stefan Meili
Stefan Meili

Reputation: 99

Python / Bokeh - Colorbar with datetime formatting

Can someone please give me a little help formatting the ticker on a bokeh colorbar to datetime?

The example below colors a scatterplot with the datetime index. I'd like to have the colorbar formatted to show a few ticks with Year / Month, similar to how figure(x_axis_type = 'datetime') works.

See Plot. Currently it shows time in ms. It's likely something to do with setting the right values for the low and high arguments in LinearColorMapper(), and then getting the right format out of DatetimeTickFormatter()

Toy Example:

import pandas as pd
import numpy as np
import bokeh.plotting as bk_plt
import bokeh.palettes as bk_pal
import bokeh.models as bk_mod

bk_plt.output_notebook()

Data = pd.DataFrame(index = pd.date_range(start = '2012-04-01', end = '2013-08-16', freq = 'H'))
Data['X'] = np.random.rand(len(Data.index))
Data['Y'] = np.random.rand(len(Data.index))

Data['Time'] = Data.index.to_julian_date()
CMin = Data['Time'].min()
CRange = Data['Time'].max() - Data['Time'].min()
Cols = (Data['Time'] - CMin) * 255 // CRange
Data['Colors'] = np.array(bk_pal.Plasma256)[Cols.astype(int).tolist()]

color_mapper = bk_mod.LinearColorMapper(palette='Plasma256', low = int(Data.index[0].strftime("%s")) * 1000, high = int(Data.index[-1].strftime("%s")) * 1000)

color_bar = bk_mod.ColorBar(color_mapper=color_mapper, ticker=bk_mod.BasicTicker(), formatter = bk_mod.DatetimeTickFormatter(), label_standoff=12, border_line_color=None, location=(0,0))


p = bk_plt.figure()
p.circle(x = Data.X, y = Data.Y, size = 5, color = Data.Colors, alpha = 0.5)
p.add_layout(color_bar, 'right')
bk_plt.show(p)

Upvotes: 0

Views: 1014

Answers (1)

Stefan Meili
Stefan Meili

Reputation: 99

As bigreddot pointed out, Bokeh datetimes are represented as float in ms since epoch. LinearColorMapper needs low and high defined as follows:

color_mapper = bk_mod.LinearColorMapper(
    palette='Plasma256', 
    low = int(Data.index[0].strftime("%s")) * 1000, 
    high = int(Data.index[-1].strftime("%s")) * 1000
)

Upvotes: 1

Related Questions