Reputation: 107
I have built a scatter plot with an radiobuttongroup on the top. How can I link the widget with the plot? The outcome I want to achieve is like the following:
choose 'one' - only show the dots when their x value equals 1
choose 'two' - only show the dots when their x value equals 2
choose 'three' - only show the dots when their x value equals 3
Here's my code so far:
dataset = {'x':[0,1,2],'y':[0,1,2]}
source2 = ColumnDataSource(data=dataset)
p2 = figure(plot_width=600, plot_height=600,
x_range=(-0.1, 2.1), y_range=(-0.1,2.1))
p2.scatter('x', 'y', source=source2,
size=15,
alpha=0.8,
line_color=None)
# option
option = RadioButtonGroup(labels=["One", "Two", "Three"], active=0)
show(column(option, p2))
Upvotes: 0
Views: 3399
Reputation: 2277
This does what you are looking for:
from bokeh.io import show
from bokeh.models import ColumnDataSource,
from bokeh.plotting import figure
from bokeh.models.widgets import RadioButtonGroup
from bokeh.layouts import column, widgetbox
from bokeh.models.callbacks import CustomJS
dataset = {'x':[0,1,2],'y':[0,1,2],'x_filter':[0,1,2]}
source = ColumnDataSource(data=dataset)
p = figure(plot_width=600, plot_height=600,
x_range=(-0.1, 2.1), y_range=(-0.1,2.1))
p.scatter('x', 'y', source=source,
size=15, alpha=0.8, line_color=None)
# add callback to control
callback = CustomJS(args=dict(p=p, source=source), code="""
var radio_value = cb_obj.active;
var data = source.data;
x = data['x']
x_filter = data['x_filter']
y = data['y']
for (i = 0; i < x.length; i++) {
if(x_filter[i] == radio_value) {
x[i] = x_filter[i];
} else {
x[i] = undefined;
}
}
source.change.emit();
""")
# option
option = RadioButtonGroup(labels=["One", "Two", "Three"],
active=0, callback=callback)
show(column(widgetbox(option),p))
The interesting code is in JavaScript. Basically, it checks for each point if the point's x coordinate equals your RadioButton selection. If it doesn't, the point is set to missing. This makes the point disappear in the plot. A new column x_filter
is added to your data. It is used for comparing the Radio choice to your original x. The actual x
is used for plotting.
Upvotes: 2