首页 > 解决方案 > Python / Bokeh - 带有日期时间格式的颜色条

问题描述

有人可以帮我将散景颜色条上的代码格式化为日期时间吗?

下面的示例使用日期时间索引为散点图着色。我希望将颜色条格式化为显示带有年/月的几个刻度,类似于 figure(x_axis_type = 'datetime') 的工作方式。

请参阅绘图。目前它以毫秒为单位显示时间。这可能与在 LinearColorMapper() 中为低和高参数设置正确的值有关,然后从 DatetimeTickFormatter() 中获取正确的格式

玩具示例:

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)

标签: pythonbokehcolorbar

解决方案


正如 bigreddot 指出的那样,散景日期时间自纪元以来以毫秒为单位表示为浮点数。LinearColorMapper 需要的 low 和 high 定义如下:

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

推荐阅读