def color_picker(): def color_slider(title, color): return Slider(title=title, show_value=False, height=300, value=127, start=0, end=255, step=1, orientation="vertical", bar_color=color) red = color_slider("R", "red") green = color_slider("G", "green") blue = color_slider("B", "blue") div = Div(width=100, height=100, style=dict(backgroundColor="rgb(127, 127, 127")) cb = CustomJS(args=dict(red=red, green=green, blue=blue, div=div), code=""" var color = "rgb(" + red.value + ", " + green.value + ", " + blue.value + ")"; div.style = {backgroundColor: color}; """) red.callback = cb green.callback = cb blue.callback = cb return Row(children=[ WidgetBox(width=50, children=[red]), WidgetBox(width=50, children=[green]), WidgetBox(width=50, children=[blue]), div, ])
def make_layout(): import pandas as pd plot, source = make_plot() template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>""" columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] df = pd.DataFrame([ ['this is a longer text that needs a tooltip, because otherwise we do not see the whole text', 'this is a short text'], ['this is another loooooooooooooooong text that needs a tooltip', 'not much here'], ], columns=['a', 'b']) columns = [TableColumn(field=c, title=c, width=20, formatter=HTMLTemplateFormatter(template=template)) for c in ['a', 'b']] source = ColumnDataSource(data=df) data_table = DataTable(source=source, columns = columns) l = layout([[data_table]]) return l data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", button_type="success") button.on_click(click_handler) buttons = WidgetBox(children=[button], width=400) column = Column(children=[buttons, plot, data_table]) return column
def create_layout(): year_select = Select(title="Year:", value="2010", options=years) location_select = Select(title="Location:", value="World", options=locations) year_select.on_change('value', on_year_change) location_select.on_change('value', on_location_change) controls = WidgetBox(children=[year_select, location_select], height=150, width=600) layout = Column(children=[controls, pyramid(), population()]) return layout
def make_data_table(self): # Add Table columns = [TableColumn(field=col, title=col) for col in self.data_df.keys()] dt = DataTable(source=self.table_source, columns=columns, width=1800, height=400, scroll_to_selection=False) return WidgetBox(dt)
def make_layout(): plot, source = make_plot() columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", button_type="success") button.on_click(click_handler) buttons = WidgetBox(children=[button], width=400) column = Column(children=[buttons, plot, data_table]) return column
radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click( lambda value: print('radio_button_group: %s' % value)) radio_button_group.js_on_click( CustomJS( code= "console.log('radio_button_group: ' + this.active, this.toString())")) widgetBox = WidgetBox(children=[ button, button_disabled, toggle_inactive, toggle_active, dropdown, dropdown_disabled, #dropdown_split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, ]) document = curdoc() document.add_root(widgetBox) if __name__ == "__main__": session = push_session(document) session.show() session.loop_until_closed()
def test_WidgetBox(): check_props(WidgetBox()) check_widget_box_children_prop(WidgetBox)
def test_widgetbox_deprecated() -> None: from bokeh.util.deprecation import BokehDeprecationWarning with pytest.warns(BokehDeprecationWarning): WidgetBox()
label_data = ColumnDataSource( data=dict(x=[1, 2, 3], y=[0, 0, 0], t=['Original', 'Normal', 'Uniform'])) label_set = LabelSet(x='x', y='y', text='t', y_offset=-4, source=label_data, render_mode='css', text_baseline="top", text_align='center') p.add_layout(label_set) callback = CustomJS(args=dict(source=source, normal=normal, uniform=uniform), code=""" data=source.get('data') for (i=0; i < data['y'].length; i++) { data['xn'][i] = normal.compute(data['x'][i]+1) } for (i=0; i < data['y'].length; i++) { data['xu'][i] = uniform.compute(data['x'][i]+2) } source.trigger('change') """) button = Button(label='Press to apply Jitter!', callback=callback) output_file("transform_jitter.html", title="Example Jitter Transform") show(Column(WidgetBox(button, width=300), p))
plot.scatter(flowers["petal_length"], flowers["petal_width"], color=color, fill_alpha=0.2, size=12) return Panel(title="Tab 1: %s" % color.capitalize(), child=plot) tabs = Tabs(tabs=[mk_tab("red"), mk_tab("green"), mk_tab("blue")]) widgets = Row(children=[ WidgetBox(children=[ button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, ]), WidgetBox(children=[ text_input, autocomplete_input, select, multi_select, slider, range_slider, #date_range_slider, date_picker, paragraph, div, pre_text,
except Exception as exception: errbox.text = str(exception) else: errbox.text = "" update_data() slider = Slider(start=1, end=20, value=order, step=1, title="Order", callback_policy='mouseup') slider.on_change('value', on_slider_value_change) text = TextInput(value=str(expr), title="Expression:") text.on_change('value', on_text_value_change) errbox = PreText() inputs = WidgetBox(children=[slider, text, errbox], width=600) layout = Column(children=[inputs, plot]) update_data() document.add_root(layout) session.show(layout) if __name__ == "__main__": document.validate() print("\npress ctrl-C to exit") session.loop_until_closed()
def create(self): print("running create...") manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True, width=1300) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(self.source, cty_glyph) hwy = plot.add_glyph(self.source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) controls = WidgetBox(manufacturer_select, model_select, transmission_select, drive_select, class_select) top_panel = Row(controls, plot) layout = Column(top_panel, data_table) return layout
order = int(new) update_data() def on_text_value_change(attr, old, new): try: global expr expr = sy.sympify(new, dict(x=xs)) except (sy.SympifyError, TypeError, ValueError) as exception: dialog.content = str(exception) dialog.visible = True else: update_data() dialog = Dialog(title="Invalid expression") slider = Slider(start=1, end=20, value=order, step=1, title="Order",callback_policy='mouseup') slider.on_change('value', on_slider_value_change) text = TextInput(value=str(expr), title="Expression:") text.on_change('value', on_text_value_change) inputs = WidgetBox(children=[slider, text],width=400) layout = Column(children=[inputs, plot, dialog]) update_data() document.add_root(layout) session.show(layout) if __name__ == "__main__": print("\npress ctrl-C to exit") session.loop_until_closed()
split = Dropdown(label="Split button", button_type="danger", menu=split_menu) 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) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(radio_button_group_handler) widgetBox = WidgetBox(children=[ button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group ]) document = Document() document.add_root(widgetBox) session = push_session(document) session.show() if __name__ == "__main__": session.loop_until_closed()
def render_plot(self, display_type='object', directory=None, legend_position='below', legend_orientation='horizontal', widget_position='left'): """ Pull everything together into a plot ready for display. Parameters: display_plot (str): either 'object', 'notebook', or an arbitrary string. If 'object', it returns the plot object. If 'notebook', the plot is displayed in the notebok. If an arbitrary string that does not match one of the other pptions, the plot is saved to '{display_plot}.html' in the current working directory if `directory` is None, or in `directory` if not None. legend_position (str): 'below', 'above', 'left', or 'right' legend_orientation (str): 'horizontal' or 'vertical' widget_position (str): 'below', 'above', 'left', or 'right' """ self._validate_workflow('render_plot') for k in self.columndatasources.keys(): for suffix in self.remove_columns[k]: self.columndatasources[k].data.pop('xs' + suffix) self.columndatasources[k].data.pop('ys' + suffix) if len(self.legend.items) > 0: self.legend.orientation = legend_orientation self.plot.add_layout(self.legend, legend_position) self.plot.toolbar.autohide = self.autohide if self.colorbar is not None: self.plot = Row(children=[self.plot, self.colorbar]) if len(self.widgets) > 0: if 'animation' in self.widgets.keys(): animate = True button = self.widgets.pop('animation') button = button['widget'] else: animate = False button = None widget_list = [d['widget'] for d in self.widgets.values()] if animate: if (len(widget_list) > 1) or not isinstance( widget_list[0], bokeh_utils.Slider): raise NotImplementedError( 'Animations are currently only implented for plots that have only a Slider widget.' ) widget_list = [button] + widget_list if widget_position not in ('left', 'right', 'above', 'below'): raise ValueError( "Valid widget positions are 'left', 'right', 'above', 'below'." ) if widget_position == 'left': self.plot = Row( children=[WidgetBox(children=widget_list), self.plot]) if widget_position == 'right': self.plot = Row( children=[self.plot, WidgetBox(children=widget_list)]) if widget_position == 'above': self.plot = Column( children=[WidgetBox(children=widget_list), self.plot]) if widget_position == 'below': self.plot = Column( children=[self.plot, WidgetBox(children=widget_list)]) if len(self.data_tables) > 0: self.plot = Column(children=[self.plot] + self.data_tables) self.validation['render_plot'] = True if display_type == 'notebook': output_notebook(CDN, hide_banner=True, load_timeout=60000) show(self.plot) elif display_type == 'object': return self.plot else: if directory is not None: display_type = path.join(directory, display_type) save(self.plot, filename='{}.html'.format(display_type), resources=CDN, title=display_type) return display_type
def make_plot(self,title, x, y): """ :param title: :param x: :param y: :return: """ print(title,x,y) t0 = time() pt = PanTool() lst = LassoSelectTool() pst = PolySelectTool() bst = BoxSelectTool() wzt = WheelZoomTool() tt = TapTool() st = SaveTool() ut = UndoTool() rt = RedoTool() p = figure( tools=[pt,lst,pst,bst,wzt,tt,st,ut,rt], plot_width=400, plot_height=400, title=self.initial_plot_2_data_mapper[x]+" vs. "+self.initial_plot_2_data_mapper[y], webgl=accelerator) # configure so that no drag tools are active p.toolbar.active_drag = pt # configure so that Bokeh chooses what (if any) scroll tool is active p.toolbar.active_scroll = wzt # configure so that a specific PolySelect tap tool is active p.toolbar.active_tap = tt p.xaxis.axis_label = self.initial_plot_2_data_mapper[x] p.yaxis.axis_label = self.initial_plot_2_data_mapper[y] c = p.circle(x=x, y=y, size=5, color="__COLOR__", alpha=.75, source=self.source, hover_color='white', hover_alpha=1, hover_line_color='grey') c.data_source.on_change('selected', self.update) # Edge generator ''' self.graph_set = [{i: [[1,0.15],[2,0.5],[3,0.99]] for i in range(self.n)}] self.edge_colors = qual_2_color(['g'+str(i) for i,_ in enumerate(self.graph_set)]) self.edge_sources = [ColumnDataSource({'x0': [], 'y0': [], 'x1': [], 'y1': [], 'alpha': []}) for i in self.graph_set] self.edge_segments = [p.segment(x0='x0', y0='y0', x1='x1', y1='y1', color=self.edge_colors[i], alpha='alpha', line_width=3, #line_dash=[1,1], source=self.edge_sources[i]) for i, _ in enumerate(self.graph_set)] for i, _ in enumerate(self.graph_set): code1 = """ var links = %s; var data = {'x0': [], 'y0': [], 'x1': [], 'y1': [], 'alpha': []}; var cdata = circle.get('data'); var indices = cb_data.index['1d'].indices; for (i=0; i < indices.length; i++) { ind0 = indices[i] for (j=0; j < links[ind0].length; j++) { ind1 = links[ind0][j][0]; w = links[ind0][j][1]; """ % self.graph_set[i] code2 = "data['x0'].push(cdata['" + x + "'][ind0]);\n" + \ "data['y0'].push(cdata['" + y + "'][ind0]);\n" + \ "data['x1'].push(cdata['" + x + "'][ind1]);\n" + \ "data['y1'].push(cdata['" + y + "'][ind1]);\n" + \ "data['alpha'].push([w]);\n" code3 = "}}segment.set('data', data);" code = code1 + code2 + code3 callback = CustomJS(args={'circle': c.data_source, 'segment': self.edge_segments[i].data_source}, code=code) p.add_tools(HoverTool(tooltips=None, callback=callback, renderers=[c])) ''' p.select(BoxSelectTool).select_every_mousemove = False p.select(LassoSelectTool).select_every_mousemove = False # Plot Controls xdim_select = Select(title="X Dim", options=self.data_dict.keys(), value=self.initial_plot_2_data_mapper[x],width=400) ydim_select = Select(title="Y Dim", options=self.data_dict.keys(), value=self.initial_plot_2_data_mapper[y],width=400) xdim_select.on_change('value', self.plot_update) ydim_select.on_change('value', self.plot_update) remove = Button(label="Remove", button_type="danger",width=400) remove.on_click(partial(self.remove_plot,title,x,y)) self.plot_control_dict[title] = {'x':xdim_select, 'y':ydim_select, 'xprev':xdim_select.value, 'yprev':ydim_select.value, 'figure':p, 'tooltip':HoverTool(tooltips=self.tooltip_list,point_policy='snap_to_data',show_arrow=False)} # Give the hover tool a tool tip self.plot_control_dict[title]['figure'].add_tools(self.plot_control_dict[title]['tooltip']) # Form Tab plot_options = WidgetBox(xdim_select,ydim_select,remove) tab1 = Panel(child=self.plot_control_dict[title]['figure'], title=title,width=400,height=400) tab2 = Panel(child=plot_options, title="options",width=400,height=400) tabs = Tabs(tabs=[tab1, tab2],width=400,height=400) self.tab_list.append(tabs) self.circle_list.append(c) print('Plot Time: ' + str(time() - t0)) return tabs, c