Bokeh FixedTicker with Custom Datetime/Timestamp values

限于喜欢 提交于 2019-12-07 17:40:42

问题


Objective: I want to have tick marks on the x axis only on 2017/10/2 and 2017/10/5. One constraint is that my times are not guaranteed to be evenly separated, so converting to a string and doing a categorical axis is not possible. They need to be numeric/datetime.

Problem: I'm unsure how to properly format the desired dates so they are rendered properly by Bokeh. I've tried dividing by 10 ** 9 and such to convert to milliseconds. This has not worked.

Sample Code:

from bokeh.plotting import figure, show
from bokeh.models import FixedTicker
import pandas as pd
import numpy as np

y = list(range(3))
x = [pd.Timestamp('2017-10-01'), pd.Timestamp('2017-10-09'), pd.Timestamp('2017-10-10')]

tick_vals = pd.Series([pd.Timestamp('2017-10-02'), 
                       pd.Timestamp('2017-10-05')]).astype(np.int64)
tick_vals = tick_vals
tick_vals = tick_vals.astype(float)

fig = figure(x_axis_type='datetime')
fig.line(x, y, y_range_name=None)
fig.xaxis.ticker = FixedTicker(ticks=list(tick_vals)) # Commenting this line works okay using the x values. They are properly formatted.

show(fig)

Versions: Bokeh: 0.12.9 Pandas: 0.20.3 Python: 3.5.4 Numpy: 1.13.3


回答1:


Converting pandas Timestamps to integers gives nanoseconds. So dividing by 10^6 to get milliseconds works for me:

y = list(range(3))
x = pd.to_datetime(['2017-10-01', '2017-10-09', '2017-10-10'])
tick_vals = pd.to_datetime(['2017-10-02', '2017-10-05']).astype(int) / 
10**6

fig = figure(x_axis_type='datetime')
fig.line(x, y)
fig.xaxis.ticker = FixedTicker(ticks=list(tick_vals)) 
show(fig)


来源:https://stackoverflow.com/questions/46916489/bokeh-fixedticker-with-custom-datetime-timestamp-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!