Skip to content

Instantly share code, notes, and snippets.

@rothnic
Created October 23, 2015 15:10
Show Gist options
  • Save rothnic/54b049eaa26fe0ec1f2d to your computer and use it in GitHub Desktop.
Save rothnic/54b049eaa26fe0ec1f2d to your computer and use it in GitHub Desktop.
Prototype Interactive Bokeh Chart
from bokeh.models import Plot, ColumnDataSource, GlyphRenderer
from bokeh.properties import Instance, Dict, String, Any
from bokeh.server.app import bokeh_app
from bokeh.server.utils.plugins import object_page
from bokeh.models.widgets import HBox, TextInput, VBoxForm, Select
from bokeh.charts import Bar
class ChartApp(HBox):
"""An example of a browser-based, interactive plot with column selection controls."""
extra_generated_classes = [["ChartApp", "ChartApp", "HBox"]]
inputs = Instance(VBoxForm)
text = Instance(TextInput)
value_select = Instance(Select)
label_select = Instance(Select)
plot = Instance(Plot)
source = Instance(ColumnDataSource)
data = Dict(String, Any)
@classmethod
def create(cls):
obj = cls()
obj.data = {'a': [1, 2, 3, 4],
'b': [3, 5, 4, 5],
'c': ['foo', 'bar', 'foo', 'bar']}
col_names = list(obj.data.keys())
obj.value_select = Select(
title='values', name='value_select',
options=col_names, value='a'
)
obj.label_select = Select(
title='label', name='label_select',
options=col_names, value='c'
)
plot = Bar(obj.data, values='a', label='c')
obj.plot = plot
obj.inputs = VBoxForm(
children=[
obj.value_select, obj.label_select
]
)
obj.children.append(obj.inputs)
obj.children.append(obj.plot)
return obj
def setup_events(self):
super(ChartApp, self).setup_events()
if not self.value_select:
return
self.value_select.on_change('value', self, 'input_change')
self.label_select.on_change('value', self, 'input_change')
def input_change(self, obj, attrname, old, new):
self.update_data()
def update_data(self):
plot = Bar(self.data,
values=self.value_select.value,
label=self.label_select.value,
id=self.plot._id)
for old, new in zip(self.plot.renderers, plot.renderers):
if isinstance(old, GlyphRenderer):
old.data_source.data = new.data_source.data
self.plot.x_range.factors = plot.x_range.factors
self.plot.y_range.start = plot.y_range.start
self.plot.y_range.end = plot.y_range.end
# The following code adds a "/bokeh/chart/" url to the bokeh-server. This
# URL will render this sine wave sliders app. If you don't want to serve this
# applet from a Bokeh server (for instance if you are embedding in a separate
# Flask application), then just remove this block of code.
@bokeh_app.route("/bokeh/chart/")
@object_page("chart")
def make_app():
app = ChartApp.create()
return app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment