简体   繁体   中英

Bokeh: how to dynamically display nominal values for X-axis with stream?

I'm trying to run a simple bokeh server, where I constantly receive a value and corresponding string, updating the data using stream() . The y-axis is a real number, while the x-axis is a nominal value which I do not know in advance. Currently, I have something similar to this example:

from bokeh.layouts import column, gridplot
from bokeh.models import ColumnDataSource
from bokeh.plotting import curdoc, figure
import random
import string


def update():
    global val
    val = int(val + 10 * random.randint(-100, 100)/50)
    s = ''.join(random.choice(string.ascii_letters))  # A random string I have no control over
    log.append(s)
    source.stream(new_data=dict(value=[val], time=[len(log)], log=[s]))


val = 100
log = []
source = ColumnDataSource(dict(value=[], time=[], log=[]))

p = figure()
p.x_range.follow = "end"
p.x_range.follow_interval = 200

p_curr = p.line(x='time', y='value', line_width=3, source=source)

curdoc().add_root(column(gridplot([[p]])))
curdoc().add_periodic_callback(update, 50)

Run with: bokeh serve --show app.py

The only thing I want to change is that instead of displaying an integer (in my case, the value of the time column) the figure should display for each data point the value of s associated with it (ie, the value of the command column). The position of the line itself should be identical, just each x-axis tick should be replaced with the corresponding string that was derived each update() .

This can be done by using SingleIntervalTicker and FuncTickFormatter . Add following code after p = figure() :

from bokeh.models import SingleIntervalTicker, FuncTickFormatter
p.xaxis.ticker = SingleIntervalTicker(interval=1, num_minor_ticks=0)
p.xaxis.formatter = FuncTickFormatter(args=dict(source=source), code='''
if(tick < 0){
    return '';
}
if(tick < source.data.log.length){
    return source.data.log[tick];
}
else{
    return '';
}
''')

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