def add_countdown(self, vi_countdown): #- VI countdown assert vi_countdown > 0 self.vi_countdown_callback = CustomJS(args=dict(vi_countdown=vi_countdown), code=""" if ( (cb_obj.label).includes('Start') ) { // Callback doesn't do anything after countdown started var countDownDate = new Date().getTime() + (1000 * 60 * vi_countdown); var countDownLoop = setInterval(function(){ var now = new Date().getTime(); var distance = countDownDate - now; if (distance<0) { cb_obj.label = "Time's up !"; clearInterval(countDownLoop); } else { var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); //var stuff = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; var stuff = minutes + "m " + seconds + "s "; cb_obj.label = "Countdown: " + stuff; } }, 1000); } """) self.vi_countdown_toggle = Toggle(label='Start countdown ('+str(vi_countdown)+' min)', active=False, button_type="success") self.vi_countdown_toggle.js_on_change('active', self.vi_countdown_callback)
def create_index_sliders_toggle(self) -> Toggle: """ Create the index sliders' visibility toggle button. Returns ------- Toggle A Toggle type button instance to control index sliders' visibility. """ sliders_toggle = Toggle(label="Plane Indices", active=False) sliders_toggle.on_click(self.toggle_index_sliders_visibility) return sliders_toggle
def create_displayed_values_toggle(self): """ Create the range sliders' visibility toggle button. Returns ------- Toggle A Toggle type button instance to control range sliders' visibility. """ displayed_values_toggle = Toggle(label="Displayed Values") displayed_values_toggle.on_click(self.toggle_range_sliders_visibility) return displayed_values_toggle
def __init__(self, number: int, name: str, gui_name: str = "", selected: bool = False, incompatibilities: List[str] = []): self.number = number self.name = name self.gui_name = gui_name if gui_name else name self.selected = selected self.incompatibilities = incompatibilities self.incompatibility_count = 0 self.button = Toggle(label=self.gui_name, width=200, button_type="primary") self.button.on_click(self.button_function)
def set_globals(parsed_result): global button_generate, buttons_toggle_x, dropdown_eval_method, slider_n_points, max_pars, source, old_active_list global result, x_eval_selectors, layout, x_eval_selectors_values, button_partial_dependence, y_value, button_color_map, colorbar, button_draw_confidence # Here we se the values of the global variables and create the layout result = parsed_result x_eval_selectors_values = copy.copy(result.x) max_pars = len(result.space.dimensions) # Layout button_generate = Button(label="Generate", button_type="success") button_generate.on_click(lambda: handle_button_generate(layout, result)) buttons_toggle_x = CheckboxButtonGroup( labels=['x ' + str(s) for s in range(max_pars)], active=[]) button_partial_dependence = Toggle(label="Use partial dependence", button_type="default") button_color_map = Toggle(label="Use same color map", button_type="default") button_draw_confidence = Toggle(label="Draw upper confidence limit", button_type="default") dropdown_eval_method = Select( title="Evaluation method:", value='Result', options=['Result', 'Exp min', 'Exp min rand', 'Sliders'], width=200, height=40) slider_n_points = Slider(start=1, end=20, value=10, step=1, title="n-points", width=200, height=10) y_value = Div(text="""""", width=300, height=200) colorbar = Div( ) # We initiate colorbar as an empty div first and then change it to a plot in case we want to show it row_plots = row([]) row_top = row(button_generate, buttons_toggle_x) col_right_side = column(button_partial_dependence, button_color_map, button_draw_confidence, dropdown_eval_method, slider_n_points, y_value, colorbar) col_left_side = column(row_top, row_plots) layout = row(col_left_side, col_right_side)
def init(): output_notebook() display(Javascript(_init_js)) but = '<img src="resources/show.png" width="34" height="25" style="display: inline" alt="Slideshow button" title="Enter/Exit RISE Slideshow">' txt = Div(text='<h2>You can now start the slideshow!</h3>' + f'<h3 style="margin: 0.5em 0;">Just click the RISE slideshow button above - the one that looks like: {but}<br/>' + '(or you can press alt+R on your keyboard instead if you prefer).</h3>') clearbutton = Button(label="Clear") clearbutton.js_on_click(CustomJS(code='primes_clear();')) cleartext = Paragraph(text='Clear all plots and outputs (e.g. before restarting slideshow).') increm = Toggle(label='Incremental', active=True) increm.js_on_click(CustomJS(code='primes_incremental(cb_obj.active)')) incremtext = Paragraph(text='Update timing plots incrementally (disable for static slide show).') repeats = Slider(start=1, end=10, value=3) repeats.js_on_change('value', CustomJS(code='primes_repeats(cb_obj.value)')) repeatstext = Paragraph(text='Repeats for timing measurements (higher is more accurate, but slower).') controls = layout([[clearbutton, cleartext], [increm, incremtext], [repeats, repeatstext]]) show(column(txt, controls, sizing_mode='stretch_width'))
def create_state_ctrls(self, btn_width=70, btn_container_width=90, layout='row'): """ Create state buttons: Run, Pause, Stop, Exit, etc. """ btn_run = Button(label="Run", button_type="success") btn_run.on_click(self.on_run_handler) btn_pause = Toggle(label="Pause", button_type="primary") btn_pause.on_change('active', self.on_pause_handler) btn_stop = Button(label="Stop", button_type="default") btn_stop.on_click(self.on_stop_handler) btn_exit = Button(label="Exit", button_type="danger") btn_exit.on_click(self.on_exit_handler) tmp = [] for btn in [btn_run, btn_pause, btn_stop, btn_exit]: btn.width = btn_width tmp.append(widgetbox(btn, width = btn_container_width)) if layout == 'row': self.state_ctrls = row(tmp) else: self.state_ctrls = column(tmp)
class BasicOption: """ Basic option class. If you need to add further attributes to your options, create your class and inherit from this. """ number: int name: str gui_name: str selected: bool incompatibilities: List[str] def __init__(self, number: int, name: str, gui_name: str = "", selected: bool = False, incompatibilities: List[str] = []): self.number = number self.name = name self.gui_name = gui_name if gui_name else name self.selected = selected self.incompatibilities = incompatibilities self.incompatibility_count = 0 self.button = Toggle(label=self.gui_name, width=200, button_type="primary") self.button.on_click(self.button_function) def button_function(self, state): """ Disables incompatible options. """ if state: # styling self.button.button_type = "success" else: self.button.button_type = "primary" for incomp_opt in self.incompatibilities: # incompatibility logic if state: incomp_opt.incompatibility_count += 1 incomp_opt.button.disabled = True else: incomp_opt.incompatibility_count -= 1 if incomp_opt.incompatibility_count == 0: incomp_opt.button.disabled = False
def setupLyricTable(self): self.lyricTableHandler = dataTableGenerator(self.subtitleDict) # self.dtg.source.selected.on_change('indices', self.dataTableCallback) self.importFileButton = Button(label="Import file", button_type="success", width=self.buttonWidth) self.lyricModeButton = Toggle(label="Change to end lyric", button_type="success", width=self.buttonWidth) self.gui = column(self.lyricTableHandler.gui, row(self.importFileButton, self.lyricModeButton), width=self.toolWidth)
def __init__(self, data): self.map_data = data p_wgs84 = pyproj.Proj(init='epsg:4326') p_web = pyproj.Proj(init='epsg:3857') self.map_data.shape_country['geometry'] = self.map_data.shape_country['geometry'].to_crs(epsg=3857) self.country_source = GeoJSONDataSource( geojson=self.map_data.shape_country.to_json() ) self.priority_toggles = {} self.priority_groups = {} self.priority_groups_rect = {} self.priority_names = { 10: 'High', 20: 'Medium', 30: 'Low' } self.map_width = 800 self.map_height = 800 tooltips_map = [ ("Name", "@names"), ("POI", "@categories"), ] hover_map = HoverTool(tooltips=tooltips_map, mode='mouse', names=['marker'] ) plot_options_map = dict(plot_height=self.map_height, plot_width=self.map_width, tools=["pan,wheel_zoom,reset,save", hover_map], sizing_mode="fixed", toolbar_location='above', title='BiH' ) self.figure_map = figure(**plot_options_map) self.figure_map.xgrid.grid_line_color = None self.figure_map.ygrid.grid_line_color = None self.figure_map.xaxis.visible = False self.figure_map.yaxis.visible = False tile_provider = get_provider(Vendors.CARTODBPOSITRON) self.figure_map.add_tile(tile_provider) self.figure_map.multi_line('xs', 'ys', source=self.country_source, color='red', line_width=3 ) for shape in self.map_data.shape_municipalities: shape['geometry'] = shape['geometry'].to_crs(epsg=3857) source = GeoJSONDataSource( geojson=shape.to_json() ) self.figure_map.patches('xs', 'ys', source=source, line_color='green', color='navy', alpha=0.1, line_width=2) for priority in map_data.priorities: df = self.map_data.data.loc[self.map_data.data['priority'] == priority] urls = ['BiH/static/symbols/' + str(icon) + '.png' for icon in df['icon'].tolist()] x = df['longitude'].tolist() y = df['latitude'].tolist() names = df['name'].tolist() categories = df['category'].tolist() x, y = pyproj.transform(p_wgs84, p_web, x, y) w = [32 for i in range(len(x))] h = [37 for i in range(len(x))] source_marker = ColumnDataSource(data={ 'urls': urls, 'x': x, 'y': y, 'w': w, 'h': h }) self.priority_groups[priority] = self.figure_map.image_url(url='urls', x='x', y='y', w='w', h='h', h_units='screen', w_units='screen', anchor='center', source=source_marker) source_tooltip = ColumnDataSource(data={ 'x': x, 'y': y, 'names': names, 'categories': categories, 'w': w, 'h': h }) self.priority_groups_rect[priority] = self.figure_map.rect( x='x', y='y', width='w', height='h', fill_alpha=0, line_alpha=0, height_units='screen', width_units='screen', name='marker', source=source_tooltip) self.table_source = ColumnDataSource(data={ 'category': self.map_data.categories['category'], 'icon': self.map_data.categories['icon'], 'priority': self.map_data.categories['priority'], 'priority_names': [self.priority_names[p] for p in self.map_data.categories['priority']] }) columns = [TableColumn(field="icon", title="Icon", width=40, formatter=HTMLTemplateFormatter( template='<img src="BiH/static/symbols/<%= value %>.png" height="37" width="32">' )), TableColumn(field="category", title="Category", width=180, formatter=HTMLTemplateFormatter( template='<div style="position:relative;top:6px;font-size:12px;"><%= value %></div>' )), TableColumn(field="priority_names", title="Priority", width=80, formatter=HTMLTemplateFormatter( template='<div style="position:relative;top:6px;font-size:12px;"><%= value %></div>' ) )] data_view = CDSView(source=self.table_source, filters=[]) self.table = DataTable(columns=columns, source=self.table_source, view=data_view, sizing_mode='stretch_height', index_position=None, fit_columns=True, width=300, row_height=38, selectable=False) for priority in self.map_data.priorities: toggle = Toggle(label=self.priority_names[priority], button_type='success', width=48) toggle.on_change("active", update_table) self.priority_toggles[priority] = toggle
from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models.widgets import Toggle output_file("toggle.html") toggle = Toggle(label="Foo", button_type="success") show(widgetbox(toggle))
sample_size_input = Spinner(high=200, low=2, step=1, value=10, title="Sample Size for Simulations") msmt_error_input = RangeSlider( start=0, end=100., value=(10, 35), step=2, title="Measurement Uncertainty [%]", ) toggle_button = Toggle(label="Simulate Measurement Error", button_type="success") ffa_info = Div(width=550, text="Mean of {} simulations for a sample size of {}.".format( 'x', 'y')) error_info = Div(text="", style={'color': 'red'}) # Set up data table for summary statistics datatable_columns = [ TableColumn(field="parameter", title="Parameter"), TableColumn(field="value_all", title="All Data"), TableColumn(field="value_selection", title="Selected Data"), ] data_table = DataTable(source=datatable_source,
def histogram_bokeh(ks_distributions, labels): """ Run an interactive bokeh application. This requires a running bokeh server! Use ``bokeh serve &`` to start a bokeh server in the background. :param ks_distributions: a list of Ks distributions (pandas data frames) :param labels: a list of labels for the corresponding distributions :return: bokeh app """ from bokeh.io import curdoc from bokeh.layouts import widgetbox, layout from bokeh.models.widgets import Select, TextInput, Slider, Div from bokeh.models.widgets import CheckboxGroup, Toggle from bokeh.plotting import figure, output_file, show from bokeh.client import push_session from pylab import cm from .utils import gaussian_kde from .modeling import reflect # helper functions def get_colors(cmap_choice='binary'): too_light = [ 'binary', 'hot', 'copper', 'pink', 'summer', 'bone', 'Pastel1', 'Pastel2', 'gist_ncar', 'nipy_spectral', 'Greens' ] cmap = cm.get_cmap(cmap_choice, len(ks_distributions)) if cmap_choice in too_light: cmap = cm.get_cmap(cmap_choice, len(ks_distributions) * 4) c = [] for i in range(cmap.N): rgb = cmap(i)[:3] # will return rgba, but we need only rgb c.append(matplotlib.colors.rgb2hex(rgb)) if cmap_choice in too_light: if len(ks_distributions) > 1: c = c[2:-2] else: c = [c[-1]] return c def get_data(df, var, scale, r1, r2, outliers_included): df = filter_group_data(df, min_ks=r1, max_ks=r2, weights_outliers_included=outliers_included) data = df[var].dropna() if scale == 'log10': data = np.log10(data) return data, df # get the distributions dists = [pd.read_csv(x, sep='\t') for x in ks_distributions] if labels: labels = labels.split(',') else: labels = ks_distributions # basics c = get_colors() variables = ['Ks', 'Ka', 'Omega'] scales = ['Normal', 'log10'] # set up widgets div = Div(text=BOKEH_APP_DIV, width=800) var = Select(title='Variable', value='Ks', options=variables) scale = Select(title='Scale', value='Normal', options=scales) r1 = TextInput(title="Minimum", value='0.1') r2 = TextInput(title="Maximum", value='5') bins = TextInput(title="Bins", value='50') bandwidth = TextInput(title="Bandwidth", value='0.1') line = Slider(title="Lines", start=0, end=1, value=0.3, step=0.1) density = CheckboxGroup(labels=["Histogram", "KDE"], active=[0]) density_alpha = Slider(title="Density alpha value", start=0, end=1, value=0.6, step=0.1) hist_alpha = Slider(title="Histogram alpha value", start=0, end=1, value=0.6, step=0.1) color_choice = Select(options=[ 'binary', 'hsv', 'hot', 'magma', 'viridis', 'Greens', 'spring', 'autumn', 'copper', 'cool', 'winter', 'pink', 'summer', 'bone', 'RdBu', 'RdYlGn', 'coolwarm', 'inferno', 'Pastel1', 'Pastel2', 'tab10', 'gnuplot', 'brg', 'gist_ncar', 'jet', 'rainbow', 'nipy_spectral', 'ocean', 'cubehelix' ], value='binary', title='Color map') no_reweight = Toggle(label="Don't adapt weights when filtering", active=False) # set up figure p1 = figure( plot_width=1000, plot_height=700, # output_backend="svg", tools='pan,wheel_zoom,xwheel_zoom,ywheel_zoom,save') p1.xgrid.grid_line_color = None p1.ygrid.grid_line_color = None p1.border_fill_color = 'white' p1.outline_line_color = None p1.yaxis.axis_label = 'Duplications' p1.xaxis.axis_label = 'Ks' # draw initial plot hist_dict = {} density_dict = {} all_data = [] # set up callbacks def update(selected=None): redraw_plots() def redraw_plots(): print(density.active) c = get_colors(color_choice.value) p1.legend.items = [] all_data = [] for i in range(len(dists)): df = dists[i] data, df = get_data(df, var.value, scale.value, float(r1.value), float(r2.value), no_reweight.active) all_data.append(data) edges = np.histogram(np.hstack(tuple(all_data)), bins=int(bins.value))[1] for i in range(len(dists)): if density.active == [0]: hist = np.histogram(all_data[i], bins=int(bins.value))[0] p1.yaxis.axis_label = 'Duplications' else: hist = np.histogram(all_data[i], bins=int(bins.value), density=True)[0] p1.yaxis.axis_label = 'density' # First histograms if i in hist_dict: remove_plot(hist_dict, i) if 0 in density.active: hist_dict[i] = p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=c[i], line_color="black", fill_alpha=hist_alpha.value, line_alpha=line.value, legend=labels[i]) # Then KDEs if i in density_dict: density_dict[i].data_source.data['x'] = [] density_dict[i].data_source.data['y'] = [] if 1 in density.active: X = reflect(all_data[i]) kde = gaussian_kde(X, bw_method=float(bandwidth.value)) x = np.linspace( float(r1.value) + 0.000001, float(r2.value), 1000) if scale.value == 'log10': x = np.log10(x) pdf = np.array(kde(x)) * 2 # add boundaries such that it is a nice curve! pdf = np.hstack([0, pdf, 0]) if scale.value == 'log10': x = np.hstack([ np.log10(float(r1.value) + 0.00000099), x, np.log10(float(r2.value) + 0.000001) ]) else: x = np.hstack( [float(r1.value), x, float(r2.value) + 0.000001]) density_dict[i] = p1.patch(x=x, y=pdf, fill_color=c[i], line_width=2, line_color="black", line_alpha=line.value, alpha=density_alpha.value, legend=labels[i]) p1.legend.label_text_font_style = "italic" p1.legend.click_policy = "hide" p1.legend.inactive_fill_alpha = 0.6 v = var.value if v == "Omega": v = "Ka/Ks" if scale.value == 'log10': v = 'log10(' + v + ')' p1.xaxis.axis_label = v def remove_plot(hist_dict, i): hist_dict[i].data_source.data["top"] = [] hist_dict[i].data_source.data["left"] = [] hist_dict[i].data_source.data["right"] = [] def change_update(attrname, old, new): update() def feat_change(attrname, old, new): c = get_colors(color_choice.value) for i, d in density_dict.items(): d.glyph.fill_color = c[i] d.glyph.line_color = "black" d.glyph.fill_alpha = density_alpha.value d.glyph.line_alpha = line.value for i, d in hist_dict.items(): d.glyph.fill_color = c[i] d.glyph.line_color = "black" d.glyph.fill_alpha = hist_alpha.value d.glyph.line_alpha = line.value def bins_update(attrname, old, new): update() var.on_change('value', bins_update) bandwidth.on_change('value', bins_update) scale.on_change('value', bins_update) r1.on_change('value', bins_update) r2.on_change('value', bins_update) line.on_change('value', feat_change) bins.on_change('value', bins_update) color_choice.on_change('value', feat_change) density.on_change('active', bins_update) density_alpha.on_change('value', feat_change) hist_alpha.on_change('value', feat_change) no_reweight.on_change("active", bins_update) # set up layout widgets1 = widgetbox(var, scale, color_choice, density, line, hist_alpha, density_alpha, r1, r2, bins, bandwidth, no_reweight, sizing_mode='fixed') l = layout([ [div], [widgets1, p1], ], sizing_mode='fixed') # initialize update() session = push_session(curdoc()) curdoc().add_root(l) session.show(l) # open the document in a browser session.loop_until_closed() # run forever return # show(p1)
def generate_km_plot(kms, models, color_dict): surv_plt1 = figure(title="Survival Analysis", tools=['hover,box_zoom,wheel_zoom,save,reset']) hover = surv_plt1.select(dict(type=HoverTool)) hover.tooltips = [("Model ", "@model"), ("Time ", "@timeline"), ("survival fraction ", "@km_surv"), ("upper 95% bound ", "@surv_upper"), ("lower 95% bound ", "@surv_lower")] if len(kms) > 1: hover.mode = 'mouse' else: hover.mode = 'vline' km_colors = [ '#1a1334', '#03c383', '#fbbf45', '#ed0345', '#26294a', '#aad962', '#01545a', '#ef6a32', '#017351', '#a12a5e', '#710162', '#110141' ] #km_colors = [str(color_dict[model_key]) if model_key in color_dict else 'grey' for model_key in models] n = 0 surv_plt_objs1 = [] surv_plt_objs2 = [] for km in kms: model = models[n] time = km['time'] surv = km['surv'] surv_upper = km['surv_lower'] surv_lower = km['surv_upper'] band_x = np.append(time, time[::-1]) band_y = np.append(surv_upper, surv_lower[::-1]) source = ColumnDataSource(data=dict(timeline=[i for i in time], km_surv=[i for i in surv], model=[models[n] for i in time], surv_lower=[i for i in surv_lower], surv_upper=[i for i in surv_upper])) tmp = surv_plt1.patch(band_x, band_y, color=km_colors[n], fill_alpha=0.2) surv_plt_objs1.append(tmp) tmp = surv_plt1.line('timeline', 'km_surv', line_width=2, alpha=.8, source=source, legend=models[n], color=km_colors[n]) surv_plt_objs2.append(tmp) n += 1 surv_plt1.xaxis.axis_label = 'Time (Years)' surv_plt1.yaxis.axis_label = 'Kaplan-Meier Estimation (survival fraction)' # grid styles surv_plt1.toolbar.logo = None surv_plt1.grid.grid_line_alpha = 0 surv_plt1.ygrid.band_fill_color = None #"grey" surv_plt1.ygrid.band_fill_alpha = 0.1 surv_plt1.x_range.range_padding = 0 surv_plt1.legend.location = "bottom_left" surv_plt1.plot_height = 700 surv_plt1.plot_width = 790 #surv_plt1.border_fill_color = "black" #surv_plt1.background_fill_color = "white" surv_plt1.min_border_left = 80 surv_plt1.outline_line_width = 1 surv_plt1.outline_line_alpha = 0.3 surv_plt1.xaxis.minor_tick_line_color = None #'N' surv_plt1.yaxis.minor_tick_line_color = None #'#C1C1C1' #surv_plt1.xaxis.major_label_text_color = 'white' surv_plt1.y_range = Range1d(0.0, 1.02) code1 = '''\ object1.visible = toggle.active object2.visible = toggle.active ''' #Toggle possible attributes are: # active, button_type, callback, css_classes, disabled, height, icon, js_callbacks, label, name, sizing_mode, tags or width callbacks = [] toggles = [] for i in range(len(models)): callbacks.append(CustomJS.from_coffeescript(code=code1, args={})) km_color = km_colors[i].lstrip("#") style_class = ('bk-' + km_color, 'bk-' + km_color) toggles.append( Toggle(label=models[i], button_type="success", callback=callbacks[i], css_classes=style_class)) callbacks[i].args = { 'toggle': toggles[i], 'object1': surv_plt_objs1[i], 'object2': surv_plt_objs2[i] } togs = [t for t in list(toggles)] controls = widgetbox(togs, width=190) layout = row(controls, surv_plt1) return layout
d2['index'].push( d1['index'][i]); d2['sx_value'].push( d1['sx_value'][i]); d2['start_datetime_str'].push(d1['start_datetime_str'][i]); d2['end_datetime_str'].push( d1['end_datetime_str'][i]); d2['start_datetime_dt'].push( d1['start_datetime_dt'][i]); d2['end_datetime_dt'].push( d1['end_datetime_dt'][i]); } } source_sx_persistency.data = d2; console.log(d2); source_sx_persistency.change.emit(); """)) toggle_sx = Toggle(label="Persistence", button_type="success", active=True) toggle1 = Toggle(label="Word", button_type="success", active=True) toggle1.js_link('active', r_wcrd_2, 'visible') toggle2 = Toggle(label="Thumbnail", button_type="success", active=True) toggle2.js_link('active', r_tcrd_2, 'visible') slider_alpha_Value = Slider(start=0, end=1, value=1, step=.1, title="Alpha Value") #slider.on_change('value', slider_onchange) slider_alpha_Value.js_link('value', image_tcrd, 'global_alpha') silder_draw_index = Slider(start=0, end=TSET_INTERVAL_NUM-1, value=FIRST_DRAW_INDEX, step=-1, title="Draw Index", direction="rtl", sizing_mode='stretch_width') callback = CustomJS( args=dict( source_wcrd=source_wcrd, source_wcrd_view=source_wcrd_view, source_tcrd=source_tcrd, source_tcrd_view=source_tcrd_view,
options=sorted([ (key, val) for (key, val) in cols.items() ], key = lambda x:x[1]), value = 'corresponding_wt_score' ) widgets.append(x_field) y_field = Select( title = 'Y-Axis Value', options=sorted([ (key, val) for (key, val) in cols.items() ], key = lambda x:x[1]), value = 'best_mt_score' ) widgets.append(y_field) hide_null = Toggle( active=True, label="Hide 0 results with null X or Y axis values" ) widgets.append(hide_null) presets = RadioButtonGroup( labels=["MT vs WT Epitope Affinity", "Tumor Clonality and Expression"], active=0) def available(x): for entry in entries: if x in entry and entry[x] is not None: return True return False if not available('corresponding_wt_score') or not available('best_mt_score'): presets.labels.remove('MT vs WT Epitope Affinity') if not available('tumor_dna_vaf') or not available('tumor_rna_vaf'):
def checkbox_button_group_handler(active): print("checkbox_button_group_handler: %s" % active) def radio_button_group_handler(active): print("radio_button_group_handler: %s" % active) button = Button(label="Push button", icon=Icon(icon_name="check"), type="primary") button.on_click(button_handler) toggle = Toggle(label="Toggle button", type="success") toggle.on_click(toggle_handler) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_value="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
def make_start_end_figure(doc): """ Creates a Bokeh app for visualizations of start and end of hurricanes """ df_spawn_end = pd.read_csv('files/df_start_end_bokeh.csv', index_col=0) year_min, year_max, lon_boundaries, lat_boundaries = get_boundaries(df_spawn_end) gulf_stream_lon1, gulf_stream_lon2, gulf_stream_lat1, gulf_stream_lat2 = get_gulf_stream() # credits of the map url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" add_paragraph = additional_legend(loc='tracks') # ----------------------------------------------------- # WIDGETS # ----------------------------------------------------- # definition and configuration of the number selection options_number = ['-1'] + [str(x) for x in list(np.arange(1, 21))] select_number = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection options_zone = ['All', 'Mexico_Caribbean', 'Atlantic'] select_zone = Select(title='Spawning Zone:', value='All', options=options_zone) # Definition of buttons for end points and distances toggle_month = Toggle(label="Show end points", button_type="success") toggle_dist_month = Toggle(label="Show distance traveled", button_type="success") # definition and configuration of the year and month sliders slider_year = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") slider_month = RangeSlider(start=1, end=12, value=(1, 12), step=1, title="Months") # End points toggle_season = Toggle(label="Show end points", button_type="success") toggle_dist_season = Toggle(label="Show distance traveled", button_type="success") # definition and configuration of the number selection select_number_season = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection select_zone_season = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and sliders slider_year_season = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") # definition and configuration of the season selection options_season = ['All', 'Winter', 'Spring', 'Summer', 'Autumn'] select_season = Select(title='Season:', value='All', options=options_season) # ------------------------------------------------------- # DATA SOURCE AND RANDOMIZATION # ------------------------------------------------------- np.random.seed(42) n = 5 select_list = list(np.random.choice(df_spawn_end.index, size=n, replace=False)) filtr = df_spawn_end.index.map(lambda x: x in select_list) source = ColumnDataSource(data=df_spawn_end[filtr]) # -------------------------------------------------------- # FIRST TAB # -------------------------------------------------------- # Initialization of the map p = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c1 = p.circle(x='x_start', y='y_start', fill_color='green', size=8, source=source, legend_label='Start points') c2 = p.circle(x='x_end', y='y_end', fill_color='orange', size=8, source=source, legend_label='End points') d1 = p.circle(x='x_start', y='y_start', fill_color='green', radius='Distance_draw', source=source) # Line between start and end points s1 = p.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Initial configuration of WIDGETS for FIRST TAB # - Don't show end points # - Don't show segments between start and end points # - Uniform size for starting points c2.visible, s1.visible, d1.visible = False, False, False # Configuration of the hovertool hover = HoverTool(tooltips=[("ID", "@ID"), ("Duration", "@Duration"), ("Distance", "@Distance")], renderers=[c1, c2, d1], formatters={'Duration': 'printf'}) p.tools.append(hover) # Draw the Gulf Stream p.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p.legend.location = "top_left" # DataFrame display no_cols = ['x_start', 'x_end', 'y_start', 'y_end', 'Distance_draw'] cols = [TableColumn(field=col, title=col) for col in df_spawn_end.columns if col not in no_cols] data_table = DataTable(columns=cols, source=source, width=1100, selectable=False) # ------------------------------------------------------------------------ # UPDATING FIRST TAB # ------------------------------------------------------------------------ # updating process of the data underlying the map depending on user actions. def update_map_se(attr, old, new): yr = slider_year.value month = slider_month.value zone = select_zone.value n = select_number.value n = int(n) if zone == 'All': df_temp = df_spawn_end.loc[(df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1]) & (df_spawn_end['Month_start'] >= month[0]) & (df_spawn_end['Month_start'] <= month[1])] else: df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1]) & (df_spawn_end['Month_start'] >= month[0]) & (df_spawn_end['Month_start'] <= month[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.index, size=n, replace=False)) filtr = df_temp.index.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) def month_active(atrr, old, new): active = toggle_month.active dist = toggle_dist_month.active if not active: c2.visible, s1.visible = False, False toggle_month.label = "Show end points" else: c2.visible, s1.visible = True, True toggle_month.label= "Unshow end points" if not dist: c1.visible, d1.visible = True, False toggle_dist_month.label = "Show distance traveled" else: c1.visible, d1.visible = False, True toggle_dist_month.label = "Unshow distance traveled" # activation of the changes on user action select_number.on_change('value', update_map_se) slider_year.on_change('value', update_map_se) slider_month.on_change('value', update_map_se) select_zone.on_change('value', update_map_se) toggle_month.on_change('active', month_active) toggle_dist_month.on_change('active', month_active) # Make first tab tab_month = Panel(child=column(row(column(slider_year, slider_month, select_number, select_zone, toggle_month, toggle_dist_month), p, add_paragraph), data_table), title="Monthly") # ---------------------------------------------------------------------------- # SECOND TAB # ---------------------------------------------------------------------------- p_season = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p_season.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c3 = p_season.circle(x='x_start', y='y_start', fill_color='green', size=8, source=source, legend_label='Start points') c4 = p_season.circle(x='x_end', y='y_end', fill_color='orange', size=8, source=source, legend_label='End points') d2 = p_season.circle(x='x_start', y='y_start', fill_color='green', radius='Distance_draw', source=source) # line between start and end points s2 = p_season.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Initial configuration of WIDGETS for SECOND TAB # - Don't show end points # - Don't show segments between start and end points # - Uniform size for starting points c4.visible, s2.visible, d2.visible = False, False, False # Configuration of the hovertool hover_season = HoverTool(tooltips=[("ID", "@ID"), ("Duration", "@Duration"), ("Distance", "@Distance")], renderers=[c3, c4], formatters={'Duration': 'printf'}) p_season.tools.append(hover_season) # Gulf Stream p_season.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p_season.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p_season.legend.location = "top_left" # ------------------------------------------------------------------------ # UPDATING SECOND TAB # ------------------------------------------------------------------------ # updating process of the data underlying the map depending on user actions. def update_map_season(attr, old, new): yr = slider_year_season.value season = select_season.value zone = select_zone_season.value n = select_number_season.value n = int(n) if (zone == 'All') & (season == 'All'): df_temp = df_spawn_end.loc[(df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] elif (zone != 'All') & (season == 'All'): df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] elif (zone == 'All') & (season != 'All'): df_temp = df_spawn_end.loc[(df_spawn_end.Season_start == season) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] else: df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end.Season_start == season) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.index, size=n, replace=False)) filtr = df_temp.index.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) def season_active(atrr, old, new): active = toggle_season.active dist = toggle_dist_season.active if not active: c4.visible, s2.visible = False, False toggle_season.label = "Show end points" else: c4.visible, s2.visible = True, True toggle_season.label = "Show end points" if not dist: c3.visible, d2.visible = True, False toggle_dist_season.label = "Show distance traveled" else: c3.visible, d2.visible = False, True toggle_dist_season.label = "Unshow distance traveled" select_number_season.on_change('value', update_map_season) slider_year_season.on_change('value', update_map_season) select_season.on_change('value', update_map_season) select_zone_season.on_change('value', update_map_season) toggle_season.on_change('active', season_active) toggle_dist_season.on_change('active', season_active) # Make second tab tab_season = Panel(child=column(row(column(slider_year_season, select_number_season, select_season, select_zone_season,toggle_season, toggle_dist_season), p_season, add_paragraph), data_table), title="Seasonal") # ---------------------------------------------------------------------------- # FINAL SET UP # ---------------------------------------------------------------------------- tabs = Tabs(tabs=[tab_month, tab_season]) def tab_change(atrr, old, new): if tabs.active == 0: update_map_se('', '', '') else: update_map_season('', '', '') tabs.on_change('active', tab_change) # Make document doc.add_root(tabs) doc.title = 'Hurricanes' doc.theme = Theme(filename="theme.yaml")
from bokeh.models.widgets import Toggle from bokeh.io import output_file, show, vform output_file("toggle.html") toggle = Toggle(label="Foo", type="success") show(vform(toggle))
formatter=NumberFormatter(format="0.000")), TableColumn(field="v", title="voltage (V/1023)", editor=IntEditor(step=1)), ]) ############################################################################## # Widgets _div = Div(text=""" """, height=4) checkbox = CheckboxGroup(labels=['', '', ''], active=[0]) device_slc = Select(title="Device ID:", value=g.device_id, options=DEVICES['code']) device_conn_btn = Toggle(label="Connect to device", button_type="success", active=True) read_point_btn = Button(label="Read point", button_type="primary") clear_points_btn = Button(label="Clear selected points", button_type="warning") clear_everything_btn = Button(label="Clear everything", button_type="danger") calibrate_btn = Button(label="Get calibration curve", button_type="success") save_btn = Button(label="Save calibration", button_type="primary") export_btn = Button(label="Export points", button_type="success") # Select: esp device selection by Id def device_slc_callback(attr, old, new): g.device_id = new g.d_idx = DEVICES['code'].index(g.device_id) if conn_status.value:
y='y', source=source1, selection_fill_color='Black', nonselection_fill_color='Gray') # table with points in subset columns = [ TableColumn(field="x", title="X"), TableColumn(field="z", title="Text"), ] data_table = DataTable(source=source2, columns=columns, width=400, height=280) button = Toggle(label="Select") button.callback = CustomJS(args=dict(source1=source1, source2=source2), code=""" var inds_in_source2 = source2.get('selected')['1d'].indices; var d = source2.get('data'); var inds = [] if (inds_in_source2.length == 0) { return; } for (i = 0; i < inds_in_source2.length; i++) { inds.push(d['index'][i]) } source1.get('selected')['1d'].indices = inds
def ToggleWidget(*args, **kw): kw['active'] = kw.pop('value') kw['label'] = kw.pop('title') return Toggle(*args, **kw)
slider_time_unit_mapping = {0: "hour", 1: "day", 2: "month"} # create plots map_figure, map_glyph = _create_choropleth_map(geo_source, width=LEFT_COLUMN_WIDTH, height=700) ts_figure, ts_glyph = _create_time_series(\ dfincident, "Hour", "Daily", "None", dfincident["dim_incident_incident_type"].unique(), width=600, height=350) # create widgets slider_time_unit = "hour" time_slider = create_slider(slider_time_unit) slider_active_toggle = Toggle(label="slider not active", active=False, button_type="default", width=150) pattern_select = _create_radio_button_group(["Daily", "Weekly", "Yearly"]) aggregate_select = _create_radio_button_group(["Hour", "Day", "Week", "Month"]) groupby_select = _create_radio_button_group( ["None", "Type", "Day of Week", "Year"]) incident_types = dfincident["dim_incident_incident_type"].astype(str).unique() #type_filter = _create_type_filter(incident_types) type_filter = MultiSelect(title="Incident Types:", value=list(incident_types), options=[(t, t) for t in incident_types], size=10) select_all_types_button = Button(label="Select all", button_type="primary", width=150)
CheckboxButtonGroup, RadioButtonGroup, ) button = Button(label="Button (enabled) - has click event", button_type="primary") button.js_on_click( CustomJS(code="console.log('button: click ', this.toString())")) button_disabled = Button(label="Button (disabled) - no click event", button_type="primary", disabled=True) button_disabled.js_on_click( CustomJS(code="console.log('button(disabled): click ', this.toString())")) toggle_inactive = Toggle(label="Toggle button (initially inactive)", button_type="success") toggle_inactive.js_on_click( CustomJS( code= "console.log('toggle(inactive): active=' + this.active, this.toString())" )) toggle_active = Toggle(label="Toggle button (initially active)", button_type="success", active=True) toggle_active.js_on_click( CustomJS( code= "console.log('toggle(active): active=' + this.active, this.toString())" ))
x_field = Select(title="X-Axis Value", options=sorted([(key, val) for (key, val) in cols.items() if key not in removed_columns], key=lambda x: x[1]), value='corresponding_wt_score' if 'corresponding_wt_score' in cols.keys() else 'wt_ic50') widgets.append(x_field) y_field = Select( title='Y-Axis Value', options=sorted( [(key, val) for (key, val) in cols.items() if key not in removed_columns], key=lambda x: x[1]), value='best_mt_score' if 'best_mt_score' in cols.keys() else 'mt_ic50') widgets.append(y_field) hide_null = Toggle(active=True, label="Hide 0 results with null X or Y axis values") widgets.append(hide_null) # Set up the data dictionary (a transposed version of entries) data_dict = {key: [] for key in cols} data_dict.update({ '_x': [], '_y': [], }) source = ColumnDataSource( data=data_dict) #wrap a datasource around the dictionary source.tags = [ sample ] # save sample name to tags to access for naming downloaded CSV files
def radio_group_handler(active): print("radio_group_handler: %s" % active) session.store_document(document) def checkbox_button_group_handler(active): print("checkbox_button_group_handler: %s" % active) session.store_document(document) def radio_button_group_handler(active): print("radio_button_group_handler: %s" % active) session.store_document(document) button = Button(label="Push button", icon=Icon(name="check"), type="primary") button.on_click(button_handler) toggle = Toggle(label="Toggle button", type="success") toggle.on_click(toggle_handler) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_action="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(radio_group_handler)
var state = cb_obj.active var data = source.data var leg = leg_source.data if (state){ data['color'] = data['cb_colors']; leg['colors'] = color_source['cb']; } else{ data['color'] = data['def_colors']; leg['colors'] = color_source['reg']; } source.change.emit(); leg_source.change.emit(); """) color_toggle = Toggle(label="Colorblind Mode", button_type="success", callback=clr_callback, width=200) ### Plotting p_tools = "hover, wheel_zoom, box_zoom, reset" p = figure(title="Amount per 100g", tools=p_tools, plot_width=900, x_range=(-50, 1050), x_axis_label='Calories', y_range=(-5, 105), y_axis_label='Protein (g)', sizing_mode='scale_width') p.circle(x='x', y='y',
from bokeh.document import Document from bokeh.embed import file_html from bokeh.resources import INLINE from bokeh.models import CustomJS, WidgetBox from bokeh.models.widgets import ( Button, Toggle, Dropdown, CheckboxGroup, RadioGroup, CheckboxButtonGroup, RadioButtonGroup, ) button = Button(label="Button (enabled) - has click event", button_type="primary") button.js_on_click(CustomJS(code="console.log('button: click', this.toString())")) button_disabled = Button(label="Button (disabled) - no click event", button_type="primary", disabled=True) button_disabled.js_on_click(CustomJS(code="console.log('button_disabled: click', this.toString())")) toggle_inactive = Toggle(label="Toggle button (initially inactive)", button_type="success") toggle_inactive.js_on_click(CustomJS(code="console.log('toggle_inactive: ' + this.active, this.toString())")) toggle_active = Toggle(label="Toggle button (initially active)", button_type="success", active=True) toggle_active.js_on_click(CustomJS(code="console.log('toggle_active: ' + this.active, this.toString())")) menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())")) dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", disabled=True, menu=menu) dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())")) #dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default") #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))
nvote_slider = Slider(start=0, end=end_slider, value=0, step=10, title="Nombre de votes minimum", callback=filtervote) filtervote.args["nvote"] = nvote_slider vote_slider = Slider(start=50, end=100, value=50, title="Approbation/rejet(%)", callback=filtervote) filtervote.args["vote"] = vote_slider toggle = Toggle(label="Cacher points non significatifs", callback=filtervote, width=50) toggle_expl = Div( text= """Ce bouton masque les propositions dont l'approbation <b>ne peut pas être distinguée statistiquement de 50%</b>. Par exemple, une approbation de 60% ne veut presque rien dire si on la calcule sur 10 votes, par contre sur 5000 on est sûr qu'une majorité des votants est d'accord avec la proposition.Formellement, ce filtrage est obtenu par un test binomial exact bi-directionnel avec correction de Bonferroni.""" ) toggletxt = Toggle(label="Afficher le titre des revendications", callback=filtervote, width=50) toggletxt_exp = Div( text= """<b>Attention:</b> Filtrer les points et/ou zoomer avant d'afficher le texte pour que le graphique reste lisible.""" ) filtervote.args["ci"] = toggle filtervote.args["txt"] = toggletxt
t2 = p.text(zmin+1.5, 1.3, text=['\u03BB = u/f = {} m'.format(wavelength_m)], text_align="left", text_font_size="10pt") t3 = p.text(zmin+1.5, 1.7, text=['u = {:.1e} m/s'.format(velocity_mps)], text_align="left", text_font_size="10pt") # Set up toggle button & callback function def toggle_handler(active): if active: toggle.label = 'Stop' checkbox_group.disabled = True #t3.data_source.data["text"] = ['Running'] curdoc().add_periodic_callback(update, periodic_callback_time_ms) else: toggle.label = 'Start' checkbox_group.disabled = False #t3.data_source.data["text"] = ['Stopped'] curdoc().remove_periodic_callback(update) toggle = Toggle(label="Start", type="success") toggle.on_click(toggle_handler) toggle.active = False # Set up reset button def reset_handler(): global ii, current_time ii = 0 current_time = 0 l_forward.data_source.data["y"] = forward_wave() l_reverse.data_source.data["y"] = reverse_wave() l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \ l_reverse.data_source.data["y"] #t2.data_source.data["text"] = ['t = {:.3f} s'.format(current_time)] button_reset = Button(label="Reset", type="success") button_reset.on_click(reset_handler)
x = Select(title='X-Axis', value=X_INIT, options=continuous) # link widget callback to update_plot() x.on_change('value', update_plot) # create y-axis dropdown widget with continuous var columns y = Select(title='Y-Axis', value=Y_INIT, options=continuous) # link widget callback to update_plot() y.on_change('value', update_plot) # create dot color dropdown widget with "countable" var columns color = Select(title='Color', value=COLOR_INIT, options=countable) # link widget callback to update_plot() color.on_change('value', update_plot) # create image glyph toggle button toggle = Toggle(label="Show Images", button_type="success") # link button callback to toggle_callback() toggle.on_click(toggle_callback) # create lasso lasso = LassoSelectTool() # download button button = Button(label="Download", button_type="success") # button.callback = download_callback() button.callback = CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read()) # add button and dropdown selections to a widgetbox
from bokeh.models import CustomJS from bokeh.models.layouts import WidgetBox from bokeh.models.widgets import ( Button, Toggle, Dropdown, CheckboxGroup, RadioGroup, CheckboxButtonGroup, RadioButtonGroup, ) button = Button(label="Button (enabled) - has click event", button_type="primary") button.on_click(lambda: print('button: click')) button.js_on_click(CustomJS(code="console.log('button: click', this.toString())")) button_disabled = Button(label="Button (disabled) - no click event", button_type="primary", disabled=True) button_disabled.on_click(lambda: print('button_disabled: click')) button_disabled.js_on_click(CustomJS(code="console.log('button_disabled: click', this.toString())")) toggle_inactive = Toggle(label="Toggle button (initially inactive)", button_type="success") toggle_inactive.on_click(lambda value: print('toggle_inactive: %s' % value)) toggle_inactive.js_on_click(CustomJS(code="console.log('toggle_inactive: ' + this.active, this.toString())")) toggle_active = Toggle(label="Toggle button (initially active)", button_type="success", active=True) toggle_active.on_click(lambda value: print('toggle_active: %s' % value)) toggle_active.js_on_click(CustomJS(code="console.log('toggle_active: ' + this.active, this.toString())")) menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown.on_click(lambda value: print('dropdown: %s' % value)) dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())")) dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", menu=menu) dropdown_disabled.on_click(lambda value: print('dropdown_disabled: %s' % value))
DateRangeSlider, DatePicker, Paragraph, Div, PreText, Panel, Tabs, ) from bokeh.plotting import figure from bokeh.sampledata.iris import flowers button = Button(label="Button (disabled) - still has click event", button_type="primary", disabled=True) toggle = Toggle(label="Toggle button", button_type="success") menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu, default_value="item_1_value") split_menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] split = Dropdown(label="Split button", button_type="danger", menu=split_menu) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
N_HOST = Select(title='Neighbourhood:', value=c.EMPTY_STRING, options=[c.EMPTY_STRING] + FILTER_PROPERTIES[c.NC]) NG_HOST = Select(title='Neighbourhood Group:', value=c.EMPTY_STRING, options=[c.EMPTY_STRING] + NG_LIST) ROOM_TYPE_HOST = Select(title='Room Type:', value=c.EMPTY_STRING, options=[c.EMPTY_STRING] + RT_LIST) # Radio Button Widget USER_TYPE = RadioButtonGroup(labels=['Guest', 'Host'], active=0) USER_TYPE.on_change(c.ACTIVE, update_layout) # Button Toggle Widget PREDICT_VALUE = Toggle(label='Submit', button_type='success') PREDICT_VALUE.on_click(predict_price) # Text Widget HOST_PRICE = Paragraph(text="""Select all listing values and press submit to view your listings valued price.""", width=500, height=500) WIDGETS_BOTH_1 = [USER_TYPE, CITY_INPUT] WIDGETS_BOTH_2 = [ ACCOMMODATES_SLIDER, BEDROOM_SLIDER, BED_SLIDER, BATHROOM_SLIDER ] WIDGETS_BOTH_3 = [AMENITIES_SELECT] WIDGETS_GUEST = widgetbox(
) button = Button(label="Button (enabled) - has click event", button_type="primary") button.on_click(lambda: print('button: click')) button.js_on_click( CustomJS(code="console.log('button: click', this.toString())")) button_disabled = Button(label="Button (disabled) - no click event", button_type="primary", disabled=True) button_disabled.on_click(lambda: print('button_disabled: click')) button_disabled.js_on_click( CustomJS(code="console.log('button_disabled: click', this.toString())")) toggle_inactive = Toggle(label="Toggle button (initially inactive)", button_type="success") toggle_inactive.on_click(lambda value: print('toggle_inactive: %s' % value)) toggle_inactive.js_on_click( CustomJS( code="console.log('toggle_inactive: ' + this.active, this.toString())") ) toggle_active = Toggle(label="Toggle button (initially active)", button_type="success", active=True) toggle_active.on_click(lambda value: print('toggle_active: %s' % value)) toggle_active.js_on_click( CustomJS( code="console.log('toggle_active: ' + this.active, this.toString())")) menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None,
def forceSaveFilename_InputChange(attr, old, new): if "." not in new: force_save_filename_input.value = new + ".h5" elif new.split(".")[-1] != "h5": force_save_filename_input.value = old def loadFile_InputChange(attr, old, new): if not os.path.isfile(new): load_file_input.value = old #Initialize Widgets # toggle buttons all_off_button = Toggle(label="All Off", button_type="warning") all_on_button = Toggle(label="All On", button_type="warning") reset_button = Toggle(label="Reset Scope", button_type="warning") autoscale_button = Toggle(label="AutoScale Scope", button_type="warning") pulse_capture_button = Toggle(label="Pulse Capture", button_type="success") auto_save_button = Toggle(label="Stop Auto Save", button_type="warning") load_button = Toggle(label="Load", button_type="success") force_save_button = Toggle(label="Force Save", button_type="warning") save_PC_button = Toggle(label="Save", button_type="warning") # Single select dropdown menus acq_period_select = Select(title="Acquisition Period (s):", value="100", options=[".5","1","10","100","300","1000"]) num_avgs_select = Select(title="Number of Points to Average:", value="100", options=["100","1000","10000","100000","1000000"])