I'm trying to understand how to create an interactive widget with Bokeh. The goal is to have the TextInput box change the x value in the code, and in turn alter the position of the dot on the graph.
If someone could help me out with an example and describe what I should be learning in order to achieve this would be greatly appreciated!
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))
There are different ways of handling that, but in the long run it's better to use a ColumnDataSource
. In general, when you want to update something that's managed by Bokeh, you want to change already existing Bokeh models.
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))