简体   繁体   中英

How to use a datetime axis with a Bokeh image_rgba element?

I have a situation where I would like to generate a Bokeh image_rgba plot with datetime axes. When I try this, with something similar to the following code:

p1 = figure(x_axis_type = 'datetime', y_axis_type = 'datetime',
           x_range = [min(dates),max(dates)], 
           y_range = [min(dates),max(dates)],
           x_axis_label = 'Purchase Date', y_axis_label = 'Sell Date', 
           plot_width = 500, plot_height = 500)
p1.image_rgba(image = [plotmatrix], x = [min(dates)], y = [min(dates)], dh = [max(dates)-min(dates)], dw = [max(dates)-min(dates)])
p1.grid.grid_line_color = None
show(p1)

I get the following error:

TypeError: Timedelta('2139 days 00:00:00') is not JSON serializable

The plotmatrix variable is a square numpy matrix with a data type of uint32 which has been packed with RGBA values based on the example at

http://docs.bokeh.org/en/latest/docs/gallery/image_rgba.html .

What is the recommended way to address this. I realize that one option for me would be to cast all of the times into unixtime, plot the data based on seconds and then find some sort of axis label formatter to produce the correct time information. But something about that solution seems a bit too hackish for me.

The non-serializability of TimeDelta was recently addressed in PR #8027 Handle Pandas PeriodIndex and Timedelta properly . As of July 2018 this fix is not yet included in any official release. It will be part of the upcoming 1.0 release in Q3 2018.

Alternatively, if you want to convert timedelta values directy by hand to a format that Bokeh can always understand, the following function (which is all the PR above does) will work:

def convert_timedelta_type(obj):
    ''' Convert any recognized timedelta value to floating point absolute milliseconds.

    Arg:
        obj (object) : the object to convert
    Returns:
        float : milliseconds

    '''
    if isinstance(obj, dt.timedelta):
        return obj.total_seconds() * 1000.
    elif isinstance(obj, np.timedelta64):
        return (obj / np.timedelta64(1, 'ms'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM