Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - 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 (i.e., 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().

question from:https://stackoverflow.com/questions/65937955/bokeh-how-to-dynamically-display-nominal-values-for-x-axis-with-stream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 '';
}
''')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...