Skip to content

Instantly share code, notes, and snippets.

@bnaul
Created July 25, 2017 16:18
Show Gist options
  • Save bnaul/0f4e24f21f37b4161cc41e1fe24b572c to your computer and use it in GitHub Desktop.
Save bnaul/0f4e24f21f37b4161cc41e1fe24b572c to your computer and use it in GitHub Desktop.
import numpy as np
from bokeh.layouts import row
from bokeh.models.widgets import CheckboxGroup
from bokeh.plotting import figure, show
from bokeh.core.json_encoder import serialize_json
from bokeh.document import Document
from bokeh.util.serialization import make_id
def _plot_to_json(plot):
"""Convert plot to JSON objects necessary for rendering with `bokehJS`.
Parameters
----------
plot : bokeh.plotting.figure.Figure
Bokeh plot object to be rendered.
Returns
-------
(str, str)
Returns (docs_json, render_items) json for the desired plot.
"""
render_items = [{'docid': plot._id, 'elementid': make_id()}]
doc = Document()
doc.add_root(plot)
docs_json_inner = doc.to_json()
docs_json = {render_items[0]['docid']: docs_json_inner}
docs_json = serialize_json(docs_json)
render_items = serialize_json(render_items)
return docs_json, render_items
class CheckboxWithLegendGroup(CheckboxGroup):
__implementation__ = """
import {empty, input, label, div} from "core/dom"
import * as p from "core/properties"
import {Widget, WidgetView} from "models/widgets/widget"
export class CheckboxWithLegendGroupView extends WidgetView
render: () ->
super()
empty(@el)
active = @model.active
for text, i in @model.labels
inputEl = input({type: "checkbox", value: "#{i}"})
inputEl.addEventListener("change", () => @change_input())
if @model.disabled then inputEl.disabled = true
if i in active then inputEl.checked = true
labelEl = label({}, inputEl, "▌ " + text)
if @model.inline
labelEl.classList.add("bk-bs-checkbox-inline")
@el.appendChild(labelEl)
else
divEl = div({class: "bk-bs-checkbox"}, labelEl)
@el.appendChild(divEl)
return @
export class CheckboxWithLegendGroup extends Widget
type: "CheckboxWithLegendGroup"
default_view: CheckboxWithLegendGroupView
@define {
active: [ p.Array, [] ]
labels: [ p.Array, [] ]
inline: [ p.Bool, false ]
callback: [ p.Instance ]
}
"""
plot = figure()
plot.scatter(x=np.random.random(5), y=np.random.random(5))
toggle = CheckboxWithLegendGroup(labels=['a', 'b', 'c'])
show(row(plot, toggle))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment