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 = HBox(children=[year_select, location_select]) layout = VBox(children=[controls, pyramid(), population()]) return layout
def check_children_prop(layout_callable): ## component subclasses are layouts, widgets and plots components = [HBox(), VBox(), 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 plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400): """ Make two panel plot to summary noise analysis with estimated flux scale """ d = pickle.load(open(mergepkl)) ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width / 2, plot_height=plot_height) fluxscale = calcfluxscale(d, imstd, flagfrac) logger.info('Median image noise is {0:.3} Jy.'.format(fluxscale * imstd)) ncum, imnoise = plotnoisecum(noisepkl, fluxscale=fluxscale, plot_width=plot_width / 2, plot_height=plot_height) hndle = show(HBox(ndist, ncum, width=plot_width, height=plot_height)) return imnoise
:return: """ global windowInSecs, totalPages windowInSecs = new totalPages = int(ppgDataFrame['time'].size / (windowInSecs * fs)) - 1 jumpSlider.end = totalPages fwdButton.on_click(jump_forward) bckButton.on_click(jump_backward) jumpSlider.on_change('value', slide_to_page) yScaleSlider.on_change('value', resize_y_scale) timeSlider.on_change('value', change_time_window) annotationTextInput.on_change('value', annotate_selection) ppgDataSource.on_change('selected', selection_change) ppgLineMarkersDataSource.on_change('selected', selection_change) #### Initialize #### jump_forward() #### Add plot and widgets to the document. #### curdoc().add_root(Column( mainViewer, HBox(pageIndicator, annotationTextInput, bckButton, fwdButton), HBox(yScaleSlider, timeSlider, jumpSlider), ) )
def test_HBox(): check_props(HBox()) check_children_prop(HBox) check_widget_wrapped_in_widget_box(HBox)
for(j = 0; j < count.length; j++){ if (num == 0){ temp = 0; }else{ temp = count[j]; } count[j] = temp + data1[careerarea_selector_name][j]; } } } source1.trigger('change'); source2.trigger('change'); """) ###################################################### #Deploy widget, call back ###################################################### career_area_bar.add_tools(TapTool(renderers=[bar], callback=callback_career)) select_experience = Select( title="Select postings that require experience of:", value='All', options=['All', 'None', 'At least 1 year', 'At least 2 year'], callback=callback_experience) #Display data multi_filter = VBox(widgetbox(select_experience), career_area_bar) tot = HBox(multi_filter, gridplot([[mp]])) show(tot)
def templateRateCorrelation(state): DEFAULT_X = ['Amount Requested', 'Annual Income', 'Debt To Income Ratio'] dati = pd.read_csv(DATA + 'accepted_less_col_small_' + state + '.csv', header=0) amnt = dati['amnt'] income = dati['income'] dti = dati['dti'] rate = dati['rate'] / 100 source = ColumnDataSource( data={'x': amnt, 'y': rate, 'Amount Requested': amnt, 'Annual Income': income, 'Debt To Income Ratio': dti, 'Rate_per_100': rate * 100} ) codex = """ var data = source.get('data'); data['x'] = data[cb_obj.get('value')];// // var r = data[cb_obj.get('value')]; // var {var} = data[cb_obj.get('value')]; // //window.alert( "{var} " + cb_obj.get('value') + {var} ); // for (i = 0; i < r.length; i++) {{ // {var}[i] = r[i] ; // data['{var}'][i] = r[i]; // }} source.trigger('change'); """ callbackx = CustomJS(args=dict(source=source), code=codex) TOOLS = "pan,wheel_zoom,reset,hover,save" plot = Figure(title=None, height=400, width=600, tools=TOOLS) # Make a line and connect to data source plot.circle(x="x", y="y", line_color="#0062cc", line_width=6, line_alpha=0.6, source=source) plot.yaxis.axis_label = 'Loan Rate' plot.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") xaxis_select = Select(title="Label X axis:", value="Amount", options=DEFAULT_X, callback=callbackx) hover = plot.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ ("Rate", "@Rate_per_100{1.11}%"), ("Amount Requested", "@{Amount Requested}{1.11}"), ("Annual Income", "@{Annual Income}{1.11}"), ("Debt To Income Ratio", "@{Debt To Income Ratio}{1.11}%") ] # Layout widgets next to the plot controls = VBox(xaxis_select) layout = HBox(controls, plot, width=800) # show(layout) script_corr, div_corr = components(layout) return script_corr, div_corr
def plotall(data, circleinds=[], crossinds=[], edgeinds=[], htmlname=None, noiseplot=None, url_path='plots', fileroot=None): """ Create interactive plot (preserving links between panels) from data dictionary data has keys of snr, time, dm, sizes, key and more. Optional index arguments are used to filter full data set. This can be used to remove bad segments or apply different symbols to subsets. url_path is path difference to png files for taptool. ('../plots' for jupyter notebook, 'plots' for public page) fileroot is the sdm file name used as root for all png files. """ # set up data dictionary if not circleinds: circleinds = calcinds(data, np.abs(data['snrs']).min()) if not crossinds: crossinds = calcinds(data, -1 * np.abs(data['snrs']).min()) TOOLS = "hover,tap,pan,box_select,wheel_zoom,reset" # set ranges datalen = len(data['dm']) inds = circleinds + crossinds + edgeinds dm = [data['dm'][i] for i in inds] dm_min = min(min(dm), max(dm) / 1.2) dm_max = max(max(dm), min(dm) * 1.2) time = [data['time'][i] for i in inds] time_min = min(time) time_max = max(time) l1 = [data['l1'][i] for i in inds] l1_min = min(l1) l1_max = max(l1) m1 = [data['m1'][i] for i in inds] m1_min = min(m1) m1_max = max(m1) specstd = [data['specstd'][i] for i in inds] specstd_min = min(specstd) specstd_max = max(specstd) imkur = [data['imkur'][i] for i in inds] imkur_min = min(imkur) imkur_max = max(imkur) # create figures dmt = Figure(plot_width=950, plot_height=500, toolbar_location="left", x_axis_label='Time (s; relative)', y_axis_label='DM (pc/cm3)', x_range=(time_min, time_max), y_range=(dm_min, dm_max), webgl=True, tools=TOOLS) loc = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='l1 (rad)', y_axis_label='m1 (rad)', x_range=(l1_min, l1_max), y_range=(m1_min, m1_max), tools=TOOLS, webgl=True) stat = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='Spectral std', y_axis_label='Image kurtosis', x_range=(specstd_min, specstd_max), y_range=(imkur_min, imkur_max), tools=TOOLS, webgl=True) norm = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='SNR observed', y_axis_label='SNR expected', tools=TOOLS, webgl=True) # create positive symbol source and add glyphs source = ColumnDataSource( data=dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) for (key, value) in data.iteritems()})) dmt.circle('time', 'dm', size='sizes', fill_color='colors', line_color=None, fill_alpha=0.2, source=source) loc.circle('l1', 'm1', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source) stat.circle('specstd', 'imkur', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source) norm.circle('abssnr', 'zs', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source) # create negative symbol source and add glyphs if crossinds: sourceneg = ColumnDataSource( data=dict({(key, tuple([value[i] for i in crossinds])) for (key, value) in data.iteritems()})) dmt.cross('time', 'dm', size='sizes', fill_color='colors', line_alpha=0.3, source=sourceneg) loc.cross('l1', 'm1', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg) stat.cross('specstd', 'imkur', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg) norm.cross('abssnr', 'zs', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg) # create linked symbol source and add glyphs if edgeinds: sourceedge = ColumnDataSource( data=dict({(key, tuple([value[i] for i in edgeinds])) for (key, value) in data.iteritems()})) dmt.circle('time', 'dm', size='sizes', line_color='colors', fill_color='colors', line_alpha=0.5, fill_alpha=0.2, source=sourceedge) loc.circle('l1', 'm1', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2) stat.circle('specstd', 'imkur', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2) norm.circle('abssnr', 'zs', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2) hover = dmt.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')]) hover = loc.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')]) hover = stat.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')]) hover = norm.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')]) if url_path and fileroot: url = '{}/cands_{}[email protected]'.format(url_path, fileroot) taptool = dmt.select(type=TapTool) taptool.callback = OpenURL(url=url) taptool = loc.select(type=TapTool) taptool.callback = OpenURL(url=url) taptool = stat.select(type=TapTool) taptool.callback = OpenURL(url=url) taptool = norm.select(type=TapTool) taptool.callback = OpenURL(url=url) # this approach does not preserve links between panels # dmt = plotdmt(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # maybe add size? # loc = plotloc(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # stat = plotstat(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # norm = plotnorm(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # arrange figures top = HBox(dmt, width=950) middle = HBox(loc, stat, width=950) if noiseplot: bottom = HBox(norm, noiseplot, width=950) else: bottom = HBox(norm, width=950) combined = VBox(top, middle, bottom, width=950) if htmlname: output_file(htmlname) save(combined) else: return combined
yScaleSlider.on_change('value', resize_y_scale) timeSlider.on_change('value', change_time_window) annotationTextInput.on_change('value', annotate_selection) ####################### #### 9. INITIALIZE #### ####################### jump_forward() ################################################### #### 10. Add plot and widgets to the document. #### ################################################### curdoc().add_root( Column( vitalViewer, vitalViewer2, vitalViewer3, vitalViewer4, vitalViewer5, ppgViewer, ekgViewer, ekgButtonGroup, ppgButtonGroup, qosButtonGroup, HBox(pageIndicator, bckButton, fwdButton), # VBox(HBox(ekgButtonGroup, ppgButtonGroup, qosButtonGroup), HBox(pageIndicator, bckButton, fwdButton)), HBox(yScaleSlider, timeSlider, jumpSlider), ))
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:") slider.on_change('value', on_slider_value_change) text = TextInput(value=str(expr), title="Expression:") text.on_change('value', on_text_value_change) inputs = HBox(children=[slider, text]) layout = VBox(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()
def plot_datatable(df): df = df.copy() # deal with some atomic mass values of the form '[98]' df['atomic mass'] = df['atomic mass'].str.extract('([\d\.]+)').astype( float) columns = [ TableColumn(field='atomic number', title='Atomic Number'), TableColumn(field='symbol', title='Symbol'), TableColumn(field='name', title='Name'), TableColumn(field='metal', title='Type'), TableColumn(field='atomic mass', title='Atomic Mass') ] column_names = [tc.field for tc in columns] source = ColumnDataSource(df[column_names]) original_source = ColumnDataSource(df) data_table = DataTable(source=source, columns=columns, height=600, editable=False) widget_callback_code = """ var filtered_data = filtered_source.get('data'); var original_data = original_source.get('data'); var element_type = element_type_select.get('value'); var min_mass = min_mass_slider.get('value'); // now construct the new data object based on the filtered values for (var key in original_data) { filtered_data[key] = []; for (var i = 0; i < original_data[key].length; ++i) { if ((element_type === "ALL" || original_data["metal"][i] === element_type) && (original_data['atomic mass'][i] >= min_mass)) { filtered_data[key].push(original_data[key][i]); } } } target_obj.trigger('change'); filtered_source.trigger('change'); """ # define the filter widgets, without callbacks for now element_type_list = ['ALL'] + df['metal'].unique().tolist() element_type_select = Select(title="Element Type:", value=element_type_list[0], options=element_type_list) min_mass_slider = Slider(start=0, end=df['atomic mass'].max(), value=1, step=1, title="minimum atomic mass") # now define the callback objects now that the filter widgets exist arg_dct = dict(filtered_source=source, original_source=original_source, element_type_select=element_type_select, min_mass_slider=min_mass_slider, target_obj=data_table) generic_callback = CustomJS(args=arg_dct, code=widget_callback_code) # connect the callbacks to the filter widgets element_type_select.callback = generic_callback min_mass_slider.callback = generic_callback # create a button to collect the filtered results # for now, just send json to new window send_button_callback_code = """ var filtered_data = filtered_source.get('data'); var action_items = []; for (var i = 0; i < filtered_data['atomic number'].length; ++i) { var item = new Object(); for (var key in filtered_data) { item[key] = filtered_data[key][i] } action_items.push(item); } var new_window = window.open("data:text/html," + encodeURIComponent(JSON.stringify(action_items)), "_blank", "location=yes,height=570,width=520,scrollbars=yes,status=yes"); new_window.focus(); """ send_button_callback = CustomJS(args=dict(filtered_source=source), code=send_button_callback_code) send_button = Button(label="Send", type="success", callback=send_button_callback) input_widgets = HBox(children=[ HBox(children=[ element_type_select, ]), HBox(children=[min_mass_slider]), HBox(children=[send_button]), ]) p = vplot(input_widgets, data_table) show(p)
def create(self): 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) 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 = VBox(children=[ manufacturer_select, model_select, transmission_select, drive_select, class_select ]) top_panel = HBox(children=[controls, plot]) layout = VBox(children=[top_panel, data_table]) return layout