def create_buttons(): global button, download_button # Play button button = Button(label='► Play', button_type="success", width=60) button.on_click(animate) play_widget = widgetbox(button, width=80, height=50, sizing_mode='fixed') spacer = Spacer(width=300, height=50) # Download button download_button1 = Button(label="Download Minimal HTML", button_type="success", width=150) download_button2 = Button(label="Download With Structures", button_type="success", width=150) download_button1.js_on_event(ButtonClick, download_simple()) download_button2.js_on_event(ButtonClick, download_extended()) download_widget1 = widgetbox(download_button1, width=200, height=50, sizing_mode='fixed') download_widget2 = widgetbox(download_button2, width=200, height=50, sizing_mode='fixed') dpanel = Row(Spacer(width=170), download_widget1, Spacer(width=10), download_widget2, width=600, sizing_mode='fixed') return play_widget, dpanel
def loss_accuracy_plot(df, x, y): df = df.fillna(0) plot = Row(*[Line(df, x, y, legend=True) for y in y]) script, div = components(plot, INLINE) js_resources = RESOURCE.render_js() css_resources = RESOURCE.render_css() return Plot(js_resources, css_resources, script, div)
def color_picker(): def color_slider(title, color): return Slider(title=title, show_value=False, 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=[red, green, blue, div])
def color_picker(): def color_slider(title, color): return Slider(title=title, show_value=False, 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, background="rgb(127, 127, 127)") cb = CustomJS(args=dict(red=red, green=green, blue=blue, div=div), code=""" const r = red.value const g = green.value const b = blue.value div.background = `rgb(${r}, ${g}, ${b})` """) red.js_on_change('value', cb) green.js_on_change('value', cb) blue.js_on_change('value', cb) return Row(children=[red, green, blue, div])
def start_view(): curdoc().add_root( Column( bpViewer, bpButtonGroup, hrViewer, spo2Viewer, ppgViewer, ppgButtonGroup, ppgViewer2, qosButtonGroup, ekgViewer, ekgButtonGroup, Row(pageIndicator, bckButton, fwdButton), Row(alarmIndicator, bckAlarmButton, fwdAlarmButton), # Row(pageIndicator, bckButton, fwdButton,alarmIndicator, bckAlarmButton, fwdAlarmButton) ))
def color_picker(): red = color_slider("R", "red") green = color_slider("G", "green") blue = color_slider("B", "blue") hex_color = '#888888' source = ColumnDataSource(data=dict(color=[hex_color])) p1 = figure(x_range=(-8, 8), y_range=(-4, 4), plot_width=100, plot_height=100, title='move sliders to change', tools='', toolbar_location=None) p1.axis.visible = False p1.rect(0, 0, width=18, height=10, fill_color='color', line_color='black', source=source) cb = CustomJS(args=dict(source=source, red=red, green=green, blue=blue), code=""" function componentToHex(c) { var hex = c.toString(16) return hex.length == 1 ? "0" + hex : hex } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b) } function toInt(v) { return v | 0 } const color = source.data['color'] const R = toInt(red.value[0]) const G = toInt(green.value[0]) const B = toInt(blue.value[0]) color[0] = rgbToHex(R, G, B) source.change.emit() """) red.js_on_change('value_throttled', cb) green.js_on_change('value_throttled', cb) blue.js_on_change('value_throttled', cb) return Row(children=[ red, green, blue, p1, ])
def _checkbox_group(source, subgroup_col): checkbox_title = Div(text=str(subgroup_col).title() + ": ") checkbox_labels = sorted(set(source.data[subgroup_col])) actives = list(range(len(checkbox_labels))) checkboxes = CheckboxGroup( labels=checkbox_labels, active=actives, inline=True, name="subgroup_checkbox", ) checkboxes.js_on_change( "active", CustomJS(code="source.change.emit();", args={"source": source})) return Row(checkbox_title, checkboxes, name="subgroup_widget")
def check_children_prop(layout_callable): ## component subclasses are layouts, widgets and plots components = [Row(), Column(), Figure()] # Test layout accepts splatted components layout1 = layout_callable(*components) assert layout1.children == components # Test layout accepts children argument layout2 = layout_callable(children=components) assert layout2.children == components # Test value error raised when non-layout is provided as children with pytest.raises(ValueError): layout_callable(children=[ColumnDataSource()])
def plot_generations(self): if self.generations is None: return None ugens = list(set(self.generations)) gen_scores = [] for gen in ugens: try: score = max([ s for g, s in zip(self.generations, self.scores) if g == gen ]) except ValueError: score = -np.inf gen_scores.append(max(gen_scores + [score])) p1 = figure(width=450, height=300, tools=[SaveTool()]) p1.line(ugens, gen_scores, color='black') p1.scatter(ugens, gen_scores, color='black') p2 = figure(width=450, height=300, tools=[SaveTool()], x_range=p1.x_range, y_range=p1.y_range) for cluster in self.top_clusters: gen_scores = [] for gen in ugens: cg_scores = [ s for g, s, c in zip(self.generations, self.scores, self.clusters) if g == gen and c == cluster ] try: gen_scores.append(max(gen_scores + cg_scores)) except ValueError: gen_scores.append(-np.inf) p2.line(ugens, gen_scores, color=cluster_cmap(cluster)) p2.scatter(ugens, gen_scores, color=cluster_cmap(cluster)) for p in [p1, p2]: p.xaxis.axis_label = 'Generation' p.xaxis.axis_label_text_font_size = '10pt' p.yaxis.axis_label = 'Score' p.yaxis.axis_label_text_font_size = '10pt' return Row(p1, p2)
def color_picker_python(): red = color_slider("R", "red") green = color_slider("G", "green") blue = color_slider("B", "blue") hex_color = '#888888' source = ColumnDataSource(data=dict(color=[hex_color])) p2 = figure(x_range=(-8, 8), y_range=(-4, 4), plot_width=100, plot_height=100, title='Bokeh serve only', tools='', toolbar_location=None) p2.axis.visible = False r1 = p2.rect(0, 0, width=18, height=10, fill_color='color', line_color='black', source=source) def rgb_to_hex(rgb): return '#%02x%02x%02x' % rgb def callback(attr, old, new): source.data['color'] = [ rgb_to_hex((red.value[0], green.value[0], blue.value[0])) ] return red.on_change('value', callback) green.on_change('value', callback) blue.on_change('value', callback) return Row(children=[ red, blue, green, p2, ], width=400)
def bkapp(dfile, pcol, app_name, server_static_root, title='Sketch-map', pointsize=10, jmol_settings=""): global cv, controls, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, ps, jmolsettings, appname, lay, server_prefix, periodic_checkbox, pss, frac, alphas, grid, marker appname = app_name server_prefix = server_static_root ps = pointsize jmolsettings = jmol_settings #initialise data datafile = join(appname, 'data', dfile) cv = smap(name=title) cv.read(datafile) n = len(cv.data) columns = [i for i in cv.columns] # set up selection options tcol = pcol[0] - 1 xcol = Select(title='X-Axis', value=columns[tcol], options=columns, width=50) xcol.on_change('value', update) tcol = pcol[1] - 1 ycol = Select(title='Y-Axis', value=columns[tcol], options=columns, width=50) ycol.on_change('value', update) roptions = ['None'] for option in columns: roptions.append(option) rcol = Select(title='Size', value='None', options=roptions, width=50) rcol.on_change('value', update) if (len(pcol) > 2): tcol = pcol[2] - 1 ccol = Select(title='Color', value=columns[tcol], options=roptions, width=50) else: ccol = Select(title='Color', value='None', options=roptions, width=50) ccol.on_change('value', update) marker_options = [ 'circle', 'diamond', 'triangle', 'square', 'asterisk', 'cross', 'inverted_triangle', 'variable' ] marker = Select(title='Marker', value='circle', options=marker_options, width=50) marker.on_change('value', update) periodic_checkbox = CheckboxGroup(labels=["Periodic Palette"], active=[]) periodic_checkbox.on_change('active', update) grid = CheckboxGroup(labels=["Show Axis"], active=[0]) grid.on_change('active', update) plt_name = Select(title='Palette', width=50, value='Inferno256', options=[ "Magma256", "Plasma256", "Spectral6", "Inferno256", "Viridis256", "Greys256", "cosmo" ]) plt_name.on_change('value', update) pss = Slider(start=0, end=50, value=ps, step=1, callback_policy='mouseup', title="Point Size", width=150) pss.on_change('value', update) frac = Slider(start=0, end=1, value=min(1.0, round(3000. / n, 1)), step=0.1, callback_policy='mouseup', title="Fraction Of Data Loaded", width=200) frac.on_change('value', update) alphas = Slider(start=0, end=1, value=0.75, step=0.1, callback_policy='mouseup', title="Point Alpha", width=150) alphas.on_change('value', update) xm = widgetbox(xcol, width=170, sizing_mode='fixed') ym = widgetbox(ycol, width=170, sizing_mode='fixed') cm = widgetbox(ccol, width=170, sizing_mode='fixed') mm = widgetbox(marker, width=170, sizing_mode='fixed') cp = widgetbox(periodic_checkbox, width=100, sizing_mode='fixed') gc = widgetbox(grid, width=100, sizing_mode='fixed') rm = widgetbox(rcol, width=170, sizing_mode='fixed') pm = widgetbox(plt_name, width=170, sizing_mode='fixed') psw = widgetbox(pss, width=210, height=50, sizing_mode='fixed') asl = widgetbox(alphas, width=210, height=50, sizing_mode='fixed') fw = widgetbox(frac, width=270, height=50, sizing_mode='fixed') controls = Column( Row(xm, ym, cm, rm, pm, mm, width=1050, sizing_mode='scale_width'), Row(gc, fw, psw, asl, cp, width=1050, sizing_mode='fixed')) # create plot and slider plotpanel = create_plot() # full layout lay = layout([ [controls], [plotpanel], ], sizing_mode='fixed') return lay
def download_extended(): from bokeh.io import output_file, show from bokeh.resources import CDN, INLINE from bokeh.embed import file_html from bokeh.embed import autoload_static from bokeh.resources import INLINE from jinja2 import Template import jinja2 import os, zipfile from shutil import copyfile global cv, indx, controls, selectsrc, xval, yval, plt_name, xcol, ycol, ccol, rcol, jmolsettings, appname, server_prefix, Periodic_color title = 'Sketchmap for ' + appname + ': Colored with ' + ccol.value + ' Point Size Variation: ' + rcol.value Periodic_color = False style = 'smapstyle' if len(grid.active) > 0: style = None if len(periodic_checkbox.active) > 0: Periodic_color = True p1, p2, table, plotdatasrc = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2., alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_width=550, table_height=400, title='', Periodic_color=Periodic_color, return_datasrc=True, frac_load=frac.value, style=style, marker=[marker.value]) # Set up mouse selection callbacks # The following code is very tricky to understand properly. # the %s are the function or variable to pass from python depending on the slider callback or mouse callback. # One could write 3 seperate callbacks to connect slider,jmol and mouse selection but this way it is more compact ! code = """ var refdata = ref.data; var data = source.data; var plotdata=plotsrc.data; var ind = %s ; Array.prototype.min = function() { return Math.min.apply(null, this); }; var inds =ind%s; var idx=plotdata['id'][inds]; var xs = refdata['x'][inds]; var ys = refdata['y'][inds]; data['xs'] = [xs]; data['ys'] = [ys]; data=refdata[inds]; source.change.emit(); %s; var str = "" + idx; var pad = "000000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "%s" ; var file= "javascript:Jmol.script(jmolApplet0," + "'set frank off; load %s/static/%s-structures/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; localStorage.setItem("indexref",indx); document.getElementById("p1").innerHTML = " Selected frame:"+ indx ; """ # Set up Slider #print (jmolsettings) iold = 0 selectsrc = ColumnDataSource({ 'xs': [cv.pd[xcol.value][iold]], 'ys': [cv.pd[ycol.value][iold]] }) refsrc = ColumnDataSource({'x': cv.pd[xcol.value], 'y': cv.pd[ycol.value]}) slider = Slider(start=0, end=n - 1, value=0, step=1, title="Primary Selection", width=400) slider_callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("cb_obj.value", ".toFixed(0)", "", jmolsettings, '.', appname)) slider.js_on_change('value', slider_callback) slider.on_change('value', slider_update) #set up mouse callback = CustomJS(args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("plotsrc.selected['1d'].indices", ".min()", "slider.value=idx", jmolsettings, '.', appname)) taptool = p1.select(type=TapTool) taptool.callback = callback p1.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=15, name="selectcircle") # Draw Selection on Overview Plot p2.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=8, name="mycircle") # spacer1 = Spacer(width=200, height=20) # spacer2 = Spacer(width=200, height=170) # plotpanel=Row(p1,Column(spacer1,p2,spacer2,table)) # layout stuffs spacer1 = Spacer(width=200, height=30) spacer2 = Spacer(width=200, height=170) indx = 0 xval = cv.pd[xcol.value][indx] yval = cv.pd[ycol.value][indx] #slider slider_widget = widgetbox(slider, width=400, height=50, sizing_mode='fixed') spacer = Spacer(width=300, height=50) # create buttons # play_widget,download_widget=create_buttons() playpanel = Row(Spacer(width=80), slider_widget) plotpanel = Row( Column(p1, Spacer(height=40)), Column(spacer1, p2, spacer2, playpanel, Spacer(height=50), table)) # Get JavaScript/HTML resources js, tag = autoload_static(plotpanel, INLINE, "") if (sys.version_info[0] < 3): js = js.decode("utf-8") #need this for python 2.7 but not python 3.3 # print "jS",js # print "TAG",tag # return css = [] for f in ["w3"]: css.append("./static/css/" + f + '.css') templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = appname + "/templates/offline-template.html" #print TEMPLATE_FILE template = templateEnv.get_template(TEMPLATE_FILE) html = template.render(js_resources=js, div=tag, jmolsettings=jmolsettings, appname=appname, server_prefix='.', css_files=css, title=title) fbase = appname + '-sketchmap_' + xcol.value + '-' + ycol.value + '-' + ccol.value + '-' + rcol.value + '-' + plt_name.value + '-f' + str( frac.value) + '-ps' + str(pss.value) + 'a' + str(alphas.value) if Periodic_color: fbase = fbase + '_Periodic' fname = os.path.join(server_prefix, 'static', fbase + '.html') zname = os.path.join(server_prefix, 'static', fbase + '.zip') # fname=fbase+'.html' if (sys.version_info[0] < 3): f = open(fname, 'w') #python 2.7 else: f = open(fname, 'wb') #python 3.3 f.write(html.encode("utf-8")) f.close() # prepare zip file from template if (os.path.isfile(zname)): os.remove(zname) copyfile( os.path.join(server_prefix, 'static', appname + '-static-offline.zip'), zname) zip = zipfile.ZipFile(zname, 'a') zip.write(fname, fbase + '.html') # zip.write(os.path.join(server_prefix,'static','README'),'README') zip.close() return CustomJS(code=""" alert('Extended offline html file might fail to load on your browser. Refer to README file in download for solution. '); window.open("%s",title="%s"); """ % (zname, fbase))
def create_plot(): global cv, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, controls, ps, jmolsettings, Periodic_color, pss, frac # Set up main plot Periodic_color = False if len(periodic_checkbox.active) > 0: Periodic_color = True style = 'smapstyle' if len(grid.active) > 0: style = None p1, p2, table, plotdatasrc = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2.0, alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_height=170, Periodic_color=Periodic_color, return_datasrc=True, frac_load=frac.value, style=style, marker=[marker.value]) # Set up mouse selection callbacks # The following code is very tricky to understand properly. # the %s are the function or variable to pass from python depending on the slider callback or mouse callback. # One could write 3 seperate callbacks to connect slider,jmol and mouse selection but this way it is more compact ! code = """ var refdata = ref.data; var data = source.data; var plotdata=plotsrc.data; var ind = %s ; Array.prototype.min = function() { return Math.min.apply(null, this); }; var inds =ind%s; var idx = %s; //plotdata['id'][inds]; console.log(inds); var xs = refdata['x'][inds]; var ys = refdata['y'][inds]; data['xs'] = [xs]; data['ys'] = [ys]; data=refdata[inds]; source.change.emit(); %s; var str = "" + idx; var pad = "000000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "%s" ; var file= "javascript:Jmol.script(jmolApplet0," + "'set frank off; load %s/static/%s-structures/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; localStorage.setItem("indexref",indx); document.getElementById("p1").innerHTML = " Selected frame:"+ indx ; //document.getElementById("info").innerHTML = "Complete Selection: " + plotdata['id'][ind] ; """ # Set up Slider # print (jmolsettings) iold = 0 selectsrc = ColumnDataSource({ 'xs': [cv.pd[xcol.value][iold]], 'ys': [cv.pd[ycol.value][iold]] }) refsrc = ColumnDataSource({'x': cv.pd[xcol.value], 'y': cv.pd[ycol.value]}) slider = Slider(start=0, end=n - 1, value=0, step=1, title="Structure id", width=400) slider_callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("cb_obj.value", ".toFixed(0)", "inds", "", jmolsettings, server_prefix, appname)) slider.js_on_change('value', slider_callback) slider.on_change('value', slider_update) #set up mouse callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("plotsrc.selected['1d'].indices", ".min()", "plotdata['id'][inds]", "slider.value=idx", jmolsettings, server_prefix, appname)) taptool = p1.select(type=TapTool) taptool.callback = callback # p1.add_tools(HoverTool(tooltips=None, callback=callback)) #test p1.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=15, name="selectcircle") # Draw Selection on Overview Plot p2.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=8, name="mycircle") # layout stuffs spacer1 = Spacer(width=200, height=0) spacer2 = Spacer(width=200, height=190) indx = 0 xval = cv.pd[xcol.value][indx] yval = cv.pd[ycol.value][indx] #slider slider_widget = widgetbox(slider, width=400, height=50, sizing_mode='fixed') spacer = Spacer(width=300, height=50) # create buttons play_widget, download_widget = create_buttons() playpanel = Row(Spacer(width=30), play_widget, Spacer(width=30), slider_widget) plotpanel = Row( Column(p1, Spacer(height=40), Row(Spacer(width=10, height=40), download_widget)), Column(spacer1, p2, spacer2, playpanel, Spacer(height=10), table)) return plotpanel
def add_controllers(self): titles = {'npeople': 'Number of people', 'sensorinterval': 'Interval', 'sensortpr': 'True positive rate', 'sensorexfp': 'Expected num of FP', 'sensorrange': 'Sensor range', 'sensorsnum': 'Fleet size', 'sensorspeed': 'Fleet speed'} idx0 = 1 stacked = [] #Create a controller for the scaling def on_scaling_changed(_, _old, _new): self.scaling = _new self.update_plot() self.scalingwidget = Select(title='Scaling', value='linear', options=['linear', 'log']) self.scalingwidget.on_change('value', on_scaling_changed) stacked.append(self.scalingwidget) # Create a controller for each param for k in titles.keys(): def on_radio_changed(attr, old, new, kk): if self.blocked: return newvalue = self.config[kk][new-1] if new != FIXEDIDX else -1 print('Changed ' + str(kk) + ' to ' + str(newvalue)) self.currparams[kk] = newvalue if new == FIXEDIDX: self.blocked = True for param in self.contr.keys(): if param == kk or self.contr[param].active != FIXEDIDX: continue self.contr[param].active = 1 self.currparams[param] = self.config[param][0] self.var = kk varyingparam = False for kkk, vvv in self.currparams.items(): if vvv == -1: varyingparam = True break if not varyingparam: self.var = None self.update_plot() if self.blocked: self.blocked = False my_radio_changed = partial(on_radio_changed, kk=k) params = ['varying'] + list(map(str, self.config[k])) buttonisactive = FIXEDIDX if self.var == k else idx0 self.contr[k] = RadioButtonGroup(labels=params, active=buttonisactive) self.contr[k].on_change('active', my_radio_changed) self.currparams[k] = params[idx0] r = Row(widgetbox(Div(text='{}:'.format(titles[k]))), self.contr[k]) stacked.append(r) self.currparams[self.var] = -1 adjwidget = Column(*stacked) self.guirow.children[0] = adjwidget
div.background = `rgb(${r}, ${g}, ${b})` """) red.js_on_change('value', cb) green.js_on_change('value', cb) blue.js_on_change('value', cb) return Row(children=[red, green, blue, div]) sliders = Row(children=[ Column(children=[ slider, disabled_slider, range_slider, date_slider, date_range_slider, only_value_slider, no_title_slider, ]), color_picker(), ]) doc = Document() doc.add_root(sliders) if __name__ == "__main__": doc.validate() filename = "sliders.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "sliders")) print("Wrote %s" % filename)
start=-30, end=0, value=exponents[par_name], step=1, title='{0}: Exponent'.format(par_name)) elif par_name == 'Shunt Resistance' or par_name == 'Series Resistance': sliders['{0} exponent'.format(par_name)] = Slider( start=-2, end=20, value=exponents[par_name], step=1, title='{0}: Exponent'.format(par_name)) #Loop through callbacks and look for activity for w in [sliders[key] for key in sliders]: w.on_change('value', update_plot) #Define layout of resulting web side plots = Column(children=[plot_fit_by_eye]) plots_log = Column(children=[plot_fit_by_eye_log]) inputs_sliders_prefactors = Column(children=[ sliders['{0} prefactor'.format(par_name)] for par_name in parameter_names ]) inputs_sliders_exponents = Column(children=[ sliders['{0} exponent'.format(par_name)] for par_name in parameter_names if par_name != 'Ideality Factor' ]) inputs_sliders = Row( children=[inputs_sliders_prefactors, inputs_sliders_exponents]) inputs = Column(children=[inputs_sliders]) curdoc().add_root(Row(children=[plots, plots_log, inputs]))
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
# yScaleSlider.on_change('value', resize_y_scale) # timeSlider.on_change('value', change_time_window) # annotationTextInput.on_change('value', annotate_selection) ####################### #### 9. INITIALIZE #### ####################### jump_forward() print(alarms_df.iloc[current_alarm_number]) ################################################### #### 10. Add plot and widgets to the document. #### ################################################### curdoc().add_root( Column( bpViewer, hrViewer, spo2Viewer, ppgViewer, ppgButtonGroup, ppgViewer2, qosButtonGroup, ekgViewer, ekgButtonGroup, Row(pageIndicator, bckButton, fwdButton), Row(alarmIndicator, bckAlarmButton, fwdAlarmButton), # Row(pageIndicator, bckButton, fwdButton,alarmIndicator, bckAlarmButton, fwdAlarmButton) ))
def test_Row(): check_props_with_responsive(Row()) check_children_prop(Row) check_widget_wrapped_in_widget_box(HBox)
'y', source=source_data, legend='Measured Data', color='blue') plot_fit_by_eye_log.scatter('x', 'y', source=source_data_log, legend='Measured Data', color='blue') plot_fit_by_eye.line('x', 'y', source=source_fit_by_eye, line_width=3, legend='Fit', color='black') plot_fit_by_eye_log.line('x', 'y', source=source_fit_by_eye_log, line_width=3, legend='Fit', color='black') #Place legends plot_fit_by_eye.legend.location = 'top_left' plot_fit_by_eye_log.legend.location = 'top_left' #Define layout of resulting web side plots = Column(children=[plot_fit_by_eye]) plots_log = Column(children=[plot_fit_by_eye_log]) curdoc().add_root(Row(children=[plots, plots_log]))
editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] table = DataTable(source=source, columns=columns, editable=True, width=800) widgets = Column(children=[ Row(children=[ Column(children=[ click_button, disabled_button, toggle, dropdown, dropdown_split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, ]), Column(children=[ text_input, autocomplete_input, select, multi_select, slider, range_slider, date_slider, date_range_slider, spinner, color_picker, date_picker, paragraph, div, pre_text, ]), tabs, ]), table, ]) doc = Document() doc.add_root(widgets) if __name__ == "__main__": doc.validate()
def create_download_simple(): from bokeh.io import output_file, show from bokeh.resources import CDN from bokeh.embed import file_html from bokeh.embed import autoload_static from bokeh.resources import INLINE from bokeh.resources import Resources # from jinja2 import Template import jinja2 global cv, indx, controls, selectsrc, xval, yval, plt_name, xcol, ycol, ccol, rcol, server_prefix, Periodic_color, frac, alphas, pss title = 'Sketchmap for ' + appname + ': Colored with ' + ccol.value + ' Point Size Variation: ' + rcol.value Periodic_color = False style = 'smapstyle' if len(grid.active) > 0: style = None if len(periodic_checkbox.active) > 0: Periodic_color = True p1, p2, table = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2., alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_width=550, table_height=300, title='', Periodic_color=Periodic_color, frac_load=frac.value, style=style, marker=[marker.value]) spacer1 = Spacer(width=200, height=10) spacer2 = Spacer(width=200, height=20) plotpanel_static = Row( p1, Column(spacer1, Row(Spacer(width=200), p2), spacer2, table)) js, tag = autoload_static(plotpanel_static, Resources(mode='inline'), "") if (sys.version_info[0] < 3): js = js.decode("utf-8") #need this for python 2.7 but not python 3.3 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = appname + "/templates/offline-template-minimal.html" #print TEMPLATE_FILE template = templateEnv.get_template(TEMPLATE_FILE) html = template.render(js_resources=js, div=tag, appname=appname, title=title, server_prefix=server_prefix) # html = file_html(plotpanel_static, CDN, "my plot") fbase = appname + '-sketchmap_' + xcol.value + '-' + ycol.value + '-' + ccol.value + '-' + rcol.value + '-' + plt_name.value + '-f' + str( frac.value) + '-ps' + str(pss.value) + 'a' + str(alphas.value) if Periodic_color: fbase = fbase + '_Periodic' fname = os.path.join(server_prefix, 'static', fbase + '-minimal.html') # if (os.path.isfile(fname)): os.remove(fname) if (sys.version_info[0] < 3): f = open(fname, 'w') #python 2.7 else: f = open(fname, 'wb') #python 3.3 f.write(html.encode("utf-8")) f.close() return fname, fbase
def main(dfile, pcol, app_name, title='Sketch-map', pointsize=10, jmol_settings=""): global cv, controls, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, ps, jmolsettings, appname appname = app_name ps = pointsize jmolsettings = jmol_settings #initialise data datafile = join(appname, 'data', dfile) cv = smap(name=title) cv.read(datafile) n = len(cv.data) columns = [i for i in cv.columns] # set up selection options xcol = Select(title='X-Axis', value=columns[pcol[0] - 1], options=columns, width=50) ycol = Select(title='Y-Axis', value=columns[pcol[1] - 1], options=columns, width=50) roptions = ['None'] for option in columns: roptions.append(option) rcol = Select(title='Size', value='None', options=roptions, width=50) ccol = Select(title='Color', value=columns[pcol[2] - 1], options=roptions, width=50) plt_name = Select(title='Palette', width=50, value='Inferno256', options=[ "Magma256", "Plasma256", "Spectral6", "Inferno256", "Viridis256", "Greys256" ]) xm = widgetbox(xcol, width=210, sizing_mode='fixed') ym = widgetbox(ycol, width=210, sizing_mode='fixed') cm = widgetbox(ccol, width=210, sizing_mode='fixed') rm = widgetbox(rcol, width=210, sizing_mode='fixed') pm = widgetbox(plt_name, width=210, sizing_mode='fixed') controls = Row(xm, ym, cm, rm, pm, width=1050, sizing_mode='scale_width') # create plot and slider p1, p2 = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=10, minps=4, alpha=0.6, pw=700, ph=600, Hover=False, toolbar_location=None, table=False, table_width=550, table_height=400, title='', add_colorbar=False) create_cover_image(appname, p1)
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, ]), WidgetBox(children=[ tabs, ], width=400), ]) doc = Document()
def test_Row() -> None: check_props_with_sizing_mode(Row()) check_children_prop(Row)
merge_tools=True) date_range_slider = DateRangeSlider( start=data['time'].iloc[0], end=data['time'].iloc[-1], value=(data['time'].iloc[0], data['time'].iloc[-1]), format='%d/%m@%H:%M', step=1, width=95 * (len(word_barplots) - 1) - 40, # padded bar_color='purple') play_button = Button(label='Run', width=75, button_type='success') play_button.on_click(update) bottom_layout = Row(children=[ date_range_slider, play_button, ]) svg_layout = Row(svg_div, width=450, height=380) arroba_layout = Row(children=[ ghost_fig, svg_layout, user_barplot, mention_barplot, ]) heatmap_layout = Column(children=[ keycluster_select, neigh_heatmap, ])
def test_Row(): check_props_with_sizing_mode(Row()) check_children_prop(Row) check_widget_wrapped_in_widget_box(Row)
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
green, p2, ], width=400) test_slider = IonRangeSlider(slider_type='double', start=0, end=77, values=[1, 2, 3.123123, 40.1234], prettify=round) sliders = Row(children=[ Column(children=[ default_slider, slider, disabled_slider, range_slider, only_value_slider, no_title_slider, prettified_slider, string_slider ]), Column(children=[ color_picker(), color_picker_python(), ]) ]) doc = curdoc() doc.add_root(sliders) save(doc) #if __name__ == "__main__": # doc.validate() # filename = "ion_range_sliders.html" # with open(filename, "w") as f: # f.write(file_html(doc, INLINE, "ion_range_sliders")) # print("Wrote %s" % filename)
def create_gui(self): self.guirow = Row(widgetbox(), widgetbox()) bp.curdoc().add_root(self.guirow) bp.curdoc().title = 'Simulation results of {}'.format(self.resdir)