使用 TextInput 在 Bokeh 中创建交互式小部件以更改图形

Creating an interactive widget in Bokeh using TextInput to alter graph

我正在尝试了解如何使用 Bokeh 创建交互式小部件。目标是让 TextInput 框更改代码中的 x 值,进而更改点在图形上的位置。

如果有人能帮我举个例子并描述我应该学习什么才能实现这一目标,我们将不胜感激!

from bokeh.plotting import *
from bokeh.models import *
from bokeh.io import *
from bokeh.transform import *
from bokeh.layouts import *
import numpy as np

x = 1
y = 5

def x_funtion(x):
    x_value = x*4
    return x_value

number = x_funtion(x)

def handler(attr, old, new):
    global number
    number = x_funtion(new)
    return number

text_input = TextInput(value=str(x), title="x")
text_input.on_change("value", handler)



p =figure()
p.circle(number,y)


curdoc().title = "Hello, world!"
curdoc().add_root(row(p,text_input))

有不同的处理方法,但在较长的 运行 中,最好使用 ColumnDataSource。通常,当您想更新由 Bokeh 管理的内容时,您想要更改现有的 Bokeh 模型。

from bokeh.layouts import *
from bokeh.models import *
from bokeh.plotting import *


def x_function(x):
    x_value = x * 4
    return x_value


x_init = 1
ds = ColumnDataSource(data=dict(x=[x_function(x_init)], y=[5]))


def handler(attr, old, new):
    try:
        new = int(new)
    except ValueError:
        pass
    else:
        ds.data['x'] = [x_function(new)]


text_input = TextInput(value=str(x_init), title="x")
text_input.on_change("value", handler)

p = figure()
p.circle('x', 'y', source=ds)

curdoc().title = "Hello, world!"
curdoc().add_root(row(p, text_input))