I have a bokeh server app which is similar to the below code with call back functions and I have been trying to explore ways to deploy the bokeh app to any public server or html so that people even without python will be able to access the app.
Please let me know if there is a way to deploy the app to public
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, TextInput
from bokeh.plotting import figure
# Set up data
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
# Set up plot
plot = figure(plot_height=400, plot_width=400, title="my sine wave",
tools="crosshair,pan,reset,save,wheel_zoom",
x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# Set up widgets
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1)
phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
# Set up callbacks
def update_title(attrname, old, new):
plot.title.text = text.value
text.on_change('value', update_title)
def update_data(attrname, old, new):
# Get the current slider values
a = amplitude.value
b = offset.value
w = phase.value
k = freq.value
# Generate the new curve
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x=x, y=y)
for w in [offset, amplitude, phase, freq]:
w.on_change('value', update_data)
# Set up layouts and add to document
inputs = column(text, offset, amplitude, phase, freq)
curdoc().add_root(row(inputs, plot, width=800))
curdoc().title = "Sliders"
Related
I have a Bokeh plot in which I have a slider. I want to change the coordinates of the line drawn with the slider, as shown in the screenshot of the figure. When I change the slider, the line changes its coordinates.
I tried using a slider widget with columndatasource. But, as I am new to Python, I cannot get to move the location and text of the label with the slider. Is there a way to do that?
My code is given below:
import math
import numpy as np
from bokeh.io import output_file
from bokeh.plotting import figure, show
from bokeh.layouts import column, row
from bokeh.models import CustomJS, Slider, Label, LabelSet
from bokeh.plotting import ColumnDataSource, figure, show
from bokeh.models import Arrow, OpenHead, NormalHead, VeeHead
theta = 0 #input the value here
theta = np.radians(-theta)
#Inputs to be made text boxes
sig_x = 10
# line
x=[1,1]
y=[-1,1]
x1=[1,1]
y1=[1,1]
I want to introduce a variable which will change with the slider also, which, for now is 10 here.
sig_1 = 10*sig_x
then i introduced dictionaries, and along with x=x, y=y the x1=x1, y1=y1.
source = ColumnDataSource(data=dict(x=x, y=y))
fig = figure(title = 'Test of Text Rotation',
plot_height = 300, plot_width = 300,
x_range = (-3,3), y_range=(-3,3),
toolbar_location = None)
I could not find a way to add label to the line, so I added layout (from tutorial example). However, unlike fig.line command, the 'x' and 'y' cannot be added as variables (pardon me if i do not use the right jargon).
citation = Label(x=1, y=1, text = str(sig_1))
fig.line('x', 'y',source=source, line_width = 2) # Main Stress block
fig.add_layout(citation)
amp_slider = Slider(start=0, end=360, value=theta, step=1, title="theta")
# Adding callback code,
callback = CustomJS(args=dict(source=source ,val=amp_slider),
code="""
const data = source.data;
var x = data['x'];
var y = data['y'];
var pi = Math.PI;
var theta = -1*(val.value) * (pi/180);
x[0]=(1*Math.cos(theta))-(1*Math.sin(theta)); // addition
x[1]=(1*Math.cos(theta))+(1*Math.sin(theta)); // addition
y[0]=(-1*Math.sin(theta))-(1*Math.cos(theta)); // addition
y[1]=(-1*Math.sin(theta))+(1*Math.cos(theta)); // addition
source.change.emit();
""")
amp_slider.js_on_change('value', callback)
layout = row(fig, column(amp_slider),)
show(layout)
I added the lines of x1[0]=(1*Math.cos(theta))-(1*Math.sin(theta)), x1[1]=(1*Math.cos(theta))+(1*Math.sin(theta));, y[0]=(-1*Math.sin(theta))-(1*Math.cos(theta)); and y[1]=(-1*Math.sin(theta))+(1*Math.cos(theta));
This code, as anticipated does not move the label along with the line. Any explanation of what i am doing wrong, and the possibility of doing it will be very helpful.
You can pass the Lable to the CustomJS-callback as well and modify the values of this model like you do with the ColumnDataSource. Don't forget to call lable.change.emit();.
See the complete example below.
import numpy as np
from bokeh.plotting import figure, show, output_notebook
from bokeh.layouts import row
from bokeh.models import CustomJS, Slider, Label, ColumnDataSource
output_notebook()
theta = 0 #input the value here
theta = np.radians(-theta)
#Inputs to be made text boxes
sig_x = 10
source = ColumnDataSource(data=dict(x=[1,1], y=[-1,1]))
fig = figure(
title = 'Test of Text Rotation',
plot_height = 300,
plot_width = 300,
x_range = (-3,3),
y_range=(-3,3),
toolbar_location = None
)
fig.line('x', 'y',source=source, line_width = 2)
citation = Label(x=1, y=1, text = str(10*sig_x))
fig.add_layout(citation)
amp_slider = Slider(start=0, end=360, value=theta, step=1, title="theta")
# Adding callback code
callback = CustomJS(args=dict(source=source ,val=amp_slider, lable=citation),
code="""
const data = source.data;
var x = data['x'];
var y = data['y'];
var pi = Math.PI;
var theta = -1*(val.value) * (pi/180);
x[0]=(1*Math.cos(theta))-(1*Math.sin(theta));
x[1]=(1*Math.cos(theta))+(1*Math.sin(theta));
y[0]=(-1*Math.sin(theta))-(1*Math.cos(theta));
y[1]=(-1*Math.sin(theta))+(1*Math.cos(theta));
source.change.emit();
lable['x'] = x[1]
lable['y'] = y[1]
lable.change.emit();
"""
)
amp_slider.js_on_change('value', callback)
layout = row(fig, amp_slider)
show(layout)
Result
If you want to modify the text of the lable, you can use a similar approach.
Goal - I would like to slide the sliders around THEN when i'm ready to update press the button to update the values based upon where the current sliders are at.
Below is an example borrowed from Bokeh's website. Ideally, I would like to change the slider parameters, then when i'm ready for them all to update, click the button, have all the sliders update and display the changes. This process would be repeated over and over. I've tried the below but I'm not getting the desired result.
import numpy as np
from bokeh.io import curdoc,output_file, show
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, TextInput, Button
from bokeh.plotting import figure
# Set up data
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
# Set up plot
plot = figure(plot_height=400, plot_width=400, title="my sine wave",
tools="crosshair,pan,reset,save,wheel_zoom",
x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# Set up widgets
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1)
phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
button = Button(label="Update Changes", button_type="success")
# Set up callbacks
def update_title(attrname, old, new):
plot.title.text = text.value
text.on_change('value', update_title)
def update_data(attrname, old, new):
# Get the current slider values
a = amplitude.value
b = offset.value
w = phase.value
k = freq.value
# Generate the new curve
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x=x, y=y)
def update():
for w in [offset, amplitude, phase, freq]:
w.on_change('value', update_data)
button.on_click(update)
# Set up layouts and add to document
inputs = column(text, offset, amplitude, phase, freq, button)
curdoc().add_root(row(inputs, plot, width=800))
Delete the code that sets up the callbacks on slider change (because you don't want that) and call update_data from the button instead (after updating the callback function signature appropriately):
def update_data():
# Get the current slider values
a = amplitude.value
b = offset.value
w = phase.value
k = freq.value
# Generate the new curve
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x=x, y=y)
button.on_click(update_data)
I am trying to use bokeh to plot the iris data and modify the fill color of the circles interactively but I am running into a problem. I call the plot and the circle with the following:
plot = figure(plot_height=600, plot_width=1000, title="Iris Data",
x_axis_label = 'Sepal length (cm)',
y_axis_label = 'Sepal width (cm)',
tools = "crosshair, pan, reset, save, wheel_zoom")
plot_circle = plot.circle(x='sepal_length', y='sepal_width', source=source,
line_color=None, fill_color={'field':'petal_width','transform':color_mapper},
size='size', fill_alpha = 0.2)
which works but when I try to add the interactivity in the call back it is not clear to me how to modify the 'field' parameter in the fill_color argument to circle. I have tried this:
def update_bubble_color(attrname, old, new):
if new=='petal_width':
color_mapper.low = min(flowers['petal_width'])
color_mapper.high = max(flowers['petal_width'])
fill_color.field='petal_width'
return
if new=='petal_length':
color_mapper.low = min(flowers['petal_length'])
color_mapper.high = max(flowers['petal_length'])
fill_color.field='petal_length'
return
select_bubble_color.on_change('value', update_bubble_color)
the color mapper limits are handled correctly but the colors are not scaled according to the new choice. When I attempt to change it to petal_length with fill_color.field='petal_length' I get an "'name 'fill_color' is not defined" error.
Any help greatly appreciated!
Full code below for reference
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.models.widgets import Select
from bokeh.plotting import figure
# Load Data
from bokeh.sampledata.iris import flowers
# Global constants (even if python dies not like it)
min_bubble_size = 10
max_bubble_size = 90
def get_scaled_size(vector):
min_vector = min(vector)
max_vector = max(vector)
scaling = (max_bubble_size-min_bubble_size)/(max_vector-min_vector)
scaled_size = [ scaling*(item-min_vector) + min_bubble_size for item in vector]
return scaled_size
# Color Mapper
color_mapper = LinearColorMapper(palette='Inferno256',
low = min(flowers['petal_width']),
high = max(flowers['petal_width']) )
# Define source
flowers['size'] = get_scaled_size(flowers['petal_length'])
source = ColumnDataSource(flowers)
# Set up plot
plot = figure(plot_height=600, plot_width=1000, title="Iris Data",
x_axis_label = 'Sepal length (cm)',
y_axis_label = 'Sepal width (cm)',
tools = "crosshair, pan, reset, save, wheel_zoom")
plot_circle = plot.circle(x='sepal_length', y='sepal_width', source=source,
line_color=None, fill_color={'field':'petal_width','transform':color_mapper},
size='size', fill_alpha = 0.2)
# Set up widgets
select_bubble_size = Select(title ='Bubble size by', value='petal_width',
options = ['petal_width','petal_length'],
width = 200)
select_bubble_color = Select(title ='Bubble color by', value='petal_width',
options = ['petal_width', 'petal_length'],
width = 200)
# Colorbar
from bokeh.models import ColorBar
bar = ColorBar(color_mapper=color_mapper,location=(0,0))
plot.add_layout(bar, 'left')
# Set up callbacks=
# Bubble size call back
def update_bubble_size(attrname, old, new):
if new=='petal_width':
source.data['size'] = get_scaled_size(flowers['petal_width'])
return
if new=='petal_length':
source.data['size'] = get_scaled_size(flowers['petal_length'])
return
select_bubble_size.on_change('value', update_bubble_size)
# bubble color call back
def update_bubble_color(attrname, old, new):
if new=='petal_width':
color_mapper.low = min(flowers['petal_width'])
color_mapper.high = max(flowers['petal_width'])
fill_color.field='petal_width'
return
if new=='petal_length':
color_mapper.low = min(flowers['petal_length'])
color_mapper.high = max(flowers['petal_length'])
fill_color.field='petal_length'
return
select_bubble_color.on_change('value', update_bubble_color)
# Set up layouts and add to document
curdoc().add_root(column(plot, row(select_bubble_size,select_bubble_color), width=800))
curdoc().title = "Iris Data"
fill_color is a property of the glyph, you will need to access it through the glyph:
plot_circle.glyph.fill_color
In your script there is not free variable fill_color anywhere, which is the source of the NameError.
In my Bokeh .py app, run by Bokeh server, I'm importing a module. In this module, a part of code depends on whether it is used in the Bokeh app or not (it can be used in "normal" Python script, too). How do I know whether the code is currently being used by Bokeh server or not?
You can check if a bokeh process is running with psutil. I have also made an example where show is used when a bokeh process is running (server) or show when no bokeh prcoess is running ("normal").
import psutil
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure, show
def checkIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False;
# Set up data
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
# Set up plot
plot = figure(plot_height=400, plot_width=400, title="my sine wave",
tools="crosshair,pan,reset,save,wheel_zoom",
x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# Set up widgets
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1)
phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
# Set up callbacks
def update_title(attrname, old, new):
plot.title.text = text.value
text.on_change('value', update_title)
def update_data(attrname, old, new):
# Get the current slider values
a = amplitude.value
b = offset.value
w = phase.value
k = freq.value
# Generate the new curve
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x=x, y=y)
for w in [offset, amplitude, phase, freq]:
w.on_change('value', update_data)
# Set up layouts and add to document
inputs = column(text, offset, amplitude, phase, freq)
if checkIfProcessRunning('bokeh'):
print('A bokeh process is running')
curdoc().add_root(row(inputs, plot, width=800))
curdoc().title = "Sliders"
else:
print('No bokeh process is running')
show(row(inputs, plot, width=800))
I'm building a simple plot with bokeh 0.12.13 with a slider to dynamically update. Everything works nicely with circles but not with vbar and I do not understand why.
See code below
def update_title(attrname, old, new):
''' Update figure title when text box changes'''
plot.title.text = text.value
def update_data(attrname, old, new):
''' Update graph using a slider '''
# Get the current slider values
q = quantile.value
# Generate the new curve
X = np.array(range(len(sample_data[q].Index)))+0.35
Y = sample_data[q].Index_reported_Rate
source.data = dict(x=X, y=Y)
text = TextInput(title="title", value='Enter text')
quantile = Slider(start=0, end=5, value=1, step=1, title="quantile")
X = sample_data[0].Index.values
Y = sample_data[quantile.value].Index_reported_Rate.values
source = ColumnDataSource(data=dict(x=X, top=Y))
# Source below works for circles
# source_c = ColumnDataSource(data=dict(x=X, y=Y))
# Definition of the figure
plot = figure(plot_width=500,
plot_height=500,
x_axis_label=selected_factor,
x_range=sample_data[quantile.value].Index.values,
title="Figure"
)
plot.circle(x='x',
y='y',
source=source_c,
size=20
)
### Set up callbacks
text.on_change('value', update_title)
quantile.on_change('value', update_data)
### Set up layouts and add to document
inputs = widgetbox(text, quantile)
curdoc().add_root(row(inputs, plot, width=500))
curdoc().title = "Sliders"
So this code works perfectly fine (except I can't update the axes yet) but if I replace plot.circle with vbar as shown below, then it does not work.
By "not working", I mean that when I run the server, the figure displays the bars but values do not change when I slide the slider....
plot.vbar(x='x',
top='top',
source=source,
width=0.25,
bottom=0,
color='red'
)