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

时间:2020-04-25 23:23:49

标签: python bokeh

我试图了解如何使用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))

1 个答案:

答案 0 :(得分:1)

有不同的处理方式,但是从长远来看,最好使用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))