x = [3, 4, 6, 12, 10, 1] y = [7, 1, 3, 4, 1, 6] c = ['blue', 'blue', 'blue', 'blue', 'blue', 'blue'] source = ColumnDataSource(data=dict(x=x, y=y, color=c)) plot_figure = figure(title='Dropdown', plot_height=450, plot_width=600, tools="save,reset", toolbar_location="below") plot_figure.scatter('x', 'y', color='color', source=source, size=10) menu = [("Red", "red"), ("Green", "green")] dropdown = Dropdown(label="Choose color for plot", menu=menu) def dropdown_click(attr, old, new): active_dropdown = dropdown.value ##Getting dropdown value if active_dropdown == 'red': c = ['red', 'red', 'red', 'red', 'red', 'red'] elif active_dropdown == 'green': c = ['green', 'green', 'green', 'green', 'green', 'green'] source.data = dict(x=x, y=y, color=c) dropdown.on_change('value', dropdown_click) layout = row(dropdown, plot_figure)
thread = Thread(target=blocking_task) thread.start() def make_plot(): #fig = make_facies_log_plotmake_fa(source.to_df(), facies_colors) #fig.savefig("app/static/mpl_fig.png") print(source.to_df().keys()) #print(source.to_df().color.unique(), source.to_df().cluster.unique()) #source.to_df().to_pickle("app/static/5_wells_p_30_no_pca_with_clusters.pkl") run_button = Button(label="Run Dim-Red") #This is our Cluster making hack cluster_button = Button(label="Add Cluster") menu = [(key, "_".join(key.lower().split(" "))) for key in df.keys()] dropdown = Dropdown(label="Available Logs", button_type="warning", menu=menu) def function_to_call(attr, old, new): print(dropdown.value) dropdown.on_change('value', function_to_call) dropdown.on_click(function_to_call) i = 1 def callback(): global i i = i + 1 source.callback = CustomJS(args=dict(colors=colors, clusters=i), code=""" var inds = cb_obj.getv('selected')['1d'].indices; var d1 = cb_obj.data; if (inds.length == 0) { return; }
def update_data_on_dropdown(): print "In Update" tuple_params = get_params() data_src = pd.ExcelFile('Data2.xlsx').parse(tuple_params[0] + ' - ' + tuple_params[1]) #data_src = pd.read_csv('Data1.csv') bokeh_source = ColumnDataSource(data_src) return ColumnDataSource(data_src) #Adding the elements --- Interactions cntry_list = [("Phillippines", "PH"), ("Vietnam", "VN"), ("Australia", "AU")] cntry_selector = Dropdown(label="Country Selector", button_type="primary", menu=cntry_list) scenario_list = [("A4", "A4"), ("B1", "B1"), ("B3", "B3")] scenario_selector = Dropdown(label="Scenario Selector", button_type="primary", menu=scenario_list) # Defining Data Control Functions controls = [cntry_selector, scenario_selector] for control in controls: control.on_change('value', lambda attr, old, new: update_data_on_dropdown()) #Build Data
def modify_doc(doc): parameters = polymer.getparameter(ie) bs = int(parameters['BS']) try: nblk = int(parameters['NBLK']) except: nblk = 1 ns = int(parameters['NS']) try: dw = parameters['DW'] * 1e-6 #dwell time is in [mu s] except: dw = 1 temperature = parameters['TEMP'] fid = pd.DataFrame(polymer.getdata(ie), index=np.linspace(dw, dw * bs * nblk, bs * nblk), columns=['real', 'im']) / ns fid['magnitude'] = ( fid['real']**2 + fid['im']**2)**0.5 # last two lines may represent a seperate method tau = np.logspace(-3, np.log10(5 * parameters['T1MX']), nblk) #as a dummy startpoint = int(0.05 * bs) - 1 endpoint = int(0.1 * bs) phi = np.zeros(nblk) for blk in range(nblk): start = startpoint + blk * bs end = endpoint + blk * bs phi[blk] = fid['magnitude'].iloc[start:end].sum() / (endpoint - startpoint) df = pd.DataFrame(data=np.c_[tau, phi], columns=['tau', 'phi']) source_fid = ColumnDataSource(data=ColumnDataSource.from_df(fid)) source_df = ColumnDataSource(data=ColumnDataSource.from_df(df)) p1 = figure(plot_width=300, plot_height=300) p1.line('index', 'im', source=source_fid, color='blue') p1.line('index', 'real', source=source_fid, color='green') p1.line('index', 'magnitude', source=source_fid, color='red') p2 = figure(plot_width=300, plot_height=300) p2.circle_cross('tau', 'phi', source=source_df, color="navy") menu = [("Experiment nr {:4d}".format(ie), "{:4d}".format(ie)) for ie in range(1, nr_experiments + 1)] dropdown = Dropdown(label="choose experiment number", menu=menu) def callback(attr, old, new): ie = int(new) parameters = polymer.getparameter(ie) bs = int(parameters['BS']) try: nblk = int(parameters['NBLK']) except: nblk = 1 ns = int(parameters['NS']) try: dw = parameters['DW'] * 1e-6 #dwell time is in [mu s] except: dw = 1 temperature = parameters['TEMP'] fid = pd.DataFrame(polymer.getdata(ie), index=np.linspace(dw, dw * bs * nblk, bs * nblk), columns=['real', 'im']) / ns fid['magnitude'] = ( fid['real']**2 + fid['im']** 2)**0.5 # last two lines may represent a seperate method tau = np.logspace(-3, np.log10(5 * parameters['T1MX']), nblk) #as a dummy startpoint = int(0.05 * bs) - 1 endpoint = int(0.1 * bs) phi = np.zeros(nblk) for blk in range(nblk): start = startpoint + blk * bs end = endpoint + blk * bs phi[blk] = fid['magnitude'].iloc[start:end].sum() / (endpoint - startpoint) df = pd.DataFrame(data=np.c_[tau, phi], columns=['tau', 'phi']) source_fid.data = ColumnDataSource.from_df(fid) source_df.data = ColumnDataSource.from_df(df) dropdown.on_change('value', callback) doc.add_root(column(dropdown, p1, p2))
#Ejemplo de un boton boton = Button(label="Ejemplo-Boton", button_type="success") #Ejemplo de un checkBox para multiples botones multiBoton = CheckboxButtonGroup(labels=["Boton 1", "Boton 2", "Boton 3"], active=[0, 1]) #Ejemplo de un Standard para un checkBox checkboxBoton = CheckboxGroup(labels=["Opcion A", "Opcion B", "Opcion C"], active=[0, 1]) #Ejemplo de un menu desplegable menu = [("Opcion A", "item_1"), ("Opcion B", "item_2"), None, ("Opcion C", "item_3")] desplegable = Dropdown(label="Boton desplegable", button_type="warning", menu=menu) #Ejemplo de una canasta de seleccion multiSeleccion = MultiSelect(title="Multiseleccionador de opciones:", value=["foo", "quux"], options=[("foo", "Opcion 1"), ("bar", "Opcion 2"), ("baz", "Opcion 3"), ("quux", "Opcion 4")]) #Ejemplo de un grupo de radioBotones radioBotones = RadioGroup(labels=["Opcion 1", "Opcion 2", "Opcion 3"], active=0) #Ejemplo de una canasta de seleccion seleccionador = Select(title="Opciones:",
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets text = TextInput(title="Custom function", value='Enter f(x)') offset = Slider(title="Offset", value=0.0, start=-5.0, end=5.0, step=0.1) amplitude = Slider(title="Amplitude", value=1.0, start=-3.0, end=3.0, step=0.01) Speed = Slider(title="Speed", value=250, start=100, end=250) Delay = Slider(title="Delay", value=1, start=1, end=100) CurveList = [("Sin", "C1"), ("Poly", "C2"), ("Abs", "C3"), ("inv/inf", "C5"), ("Frq", "C6"), ("Custom", "C4")] dropdown = Dropdown(label="Curve Lists", button_type="warning", menu=CurveList) button = Button(label="Run ", button_type="success") def update_title(attrname, old, new): plot.title.text = text.value x = np.linspace(-4 * np.pi, 4 * np.pi, N) text.on_change('value', update_title) div = Div(width=1000) def change_output(attr, old, new):
def plot(self): def update(): self.refresh_ticks += 1 self.query(self.selected_color, self.selected_year, self.selected_month) self.hot_map_update() self.trip_hour_update() self.trip_distance_update() self.trip_fare_update() self.tasks_stat_update() # self.resource_usage_update() def on_select(): BOROUGHS_CODE = {v: k for k, v in NYCBorough.BOROUGHS.items()} self.selected_color = 'green' if color.active == 1 else 'yellow' pickup.label = 'Pickups' if pickup.active else 'Dropoffs' self.selected_type = pickup.label self.selected_borough = BOROUGHS_CODE[borough.value] borough.label = borough.value self.selected_year = int(year.value) self.selected_month = int(month.value) def on_submit(): self.logger.debug('submit (%s, %s, %s, %s, %s)' % \ (self.selected_type, NYCBorough.BOROUGHS[self.selected_borough], self.selected_color, self.selected_year, self.selected_month)) self.tasks.create_tasks( self.selected_color, self.selected_year, self.selected_month) cwd = os.path.dirname(__file__) desc = Div(text=open( os.path.join(cwd, "description.html")).read(), width=1000) # Create input controls color = RadioButtonGroup(labels=['Yellow', 'Green'], active=1) color.on_change('active', lambda attr, old, new: on_select()) pickup = Toggle(label='Pickups', button_type="primary", active=True) pickup.on_change('active', lambda attr, old, new: on_select()) # BUG: Dropdown menu value cannot be integer, i.e., ('Mahattan', '1') borough_menu = [('All Boroughs', 'All Boroughs'), None, ('Manhattan', 'Manhattan'), ('Bronx', 'Bronx'), ('Brooklyn', 'Brooklyn'), ('Queens', 'Queens'), ('Staten Island', 'Staten Island')] # https://github.com/bokeh/bokeh/issues/4915 borough = Dropdown(label="Boroughs", button_type="warning", menu=borough_menu, value='All Boroughs') borough.on_change('value', lambda attr, old, new: on_select()) year = Select(title="Year:", value=str(self.selected_year), options=[str(y) for y in range(MIN_DATE['green'].year, MAX_DATE['green'].year+1)]) year.on_change('value', lambda attr, old, new: on_select()) month = Select(title="Month:", value=str(self.selected_month), options=[str(m) for m in range(1, 13)]) month.on_change('value', lambda attr, old, new: on_select()) submit = Button(label="Submit", button_type="success") submit.on_click(on_submit) controls = [color, pickup, borough, year, month, submit] self.query(self.selected_color, self.selected_year, self.selected_month) self.hot_map_init() self.trip_hour_init() self.trip_distance_init() self.trip_fare_init() self.tasks_stat_init() self.resource_usage_init() rightdown_row = row([self.trip_distance, self.trip_fare]) right_column = column([self.trip_hour, rightdown_row]) inputs = widgetbox(*controls, width=140, sizing_mode="fixed") l = layout([ [desc], [inputs, self.hot_map, right_column], [self.tasks_stat, self.resource_usage], ], sizing_mode="fixed") curdoc().add_root(l) curdoc().add_periodic_callback(update, 5000) curdoc().title = "NYC Taxi Data Explorer"
def expenses_tab(df, x_name, y_name, measure, t_count): def make_dataset(category_list): details = pd.DataFrame() for cat in category_list: subset = df[df[x_name] == cat] details = details.append(subset) by_category = details.groupby(x_name)[measure].agg(['sum', 'count']).reset_index()\ .rename(columns={'sum': y_name}).sort_values(by=y_name, ascending=False) by_category[ 'Percentage'] = by_category[y_name] / by_category[y_name].sum() by_category['angle'] = by_category['Percentage'] * 2 * np.pi by_category['Percentage'] = by_category['Percentage'] * 100 by_category['color'] = viridis(len(category_list)) return ColumnDataSource(by_category), ColumnDataSource(details) def style(p): # Title p.title.align = 'center' p.title.text_font_size = '20pt' p.title.text_font = 'serif' # Axis titles p.xaxis.axis_label_text_font_size = '14pt' p.xaxis.axis_label_text_font_style = 'bold' p.yaxis.axis_label_text_font_size = '14pt' p.yaxis.axis_label_text_font_style = 'bold' # Tick labels p.xaxis.major_label_text_font_size = '12pt' p.yaxis.major_label_text_font_size = '12pt' # Vertical Names p.xaxis.major_label_orientation = np.pi / 4 return p def make_plot(src): # Create the blank plot p = figure(x_range=src.data[x_name], plot_width=1000, plot_height=600, title=x_name + ' vs ' + y_name, x_axis_label=x_name, y_axis_label=y_name) # Setting the second y axis range name and range p.extra_y_ranges = { "Occurance": Range1d(start=0, end=src.data['count'].max()) } # Adding the second axis to the plot. p.add_layout(LinearAxis(y_range_name="Occurance"), 'right') p.vbar(source=src, x=x_name, bottom=0, top=y_name, width=0.9, fill_color='color', line_color='black', fill_alpha=0.75, hover_fill_alpha=1.0, hover_fill_color='grey') p.line(x=x_name, y=t_count, source=src, line_width=1.2, line_color='black', y_range_name="Occurance") # Hover tool referring to our own data field using @ and # a position on the graph using $ h = HoverTool( tooltips=[(y_name, '@' + y_name), ('Count of transactions', '@' + t_count)]) # Add the hover tool to the graph p.add_tools(h) # Style the plot p = style(p) return p def make_table(tbl_src): columns = [ TableColumn(field=col, title=col) for col in list(tbl_src.data.keys())[1:] ] data_table = DataTable(source=tbl_src, columns=columns, width=600, height=600) return data_table def make_pie_chart(src): # Create the blank plot pie = figure(plot_height=600, title="Percentage per " + x_name, toolbar_location=None, tools="hover", x_range=(-0.5, 1.0)) pie.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), legend=x_name, source=src, fill_color='color', line_color='black', fill_alpha=0.75, hover_fill_alpha=1.0, hover_fill_color='grey') pie.axis.axis_label = None pie.axis.visible = False pie.grid.grid_line_color = None h = HoverTool(tooltips=[( 'Percentage', '@Percentage'), (y_name, '@' + y_name), ('Count of transactions', '@' + t_count)]) # Add the hover tool to the graph pie.add_tools(h) # Style the plot pie = style(pie) return pie # def update(attr, old, new): def update(event): '''https://stackoverflow.com/questions/60715996/bokeh-2-0-dropdown-missing-value-attribute''' categories_to_plot = event.item new_src, new_tbl_src = make_dataset([categories_to_plot]) # src.data.update(new_src.data) tbl_src.data.update(new_tbl_src.data) # categories and colors available_categories = list(set(df[x_name])) print(available_categories) dropdown = Dropdown(label="Category", button_type="warning", menu=available_categories) # dropdown.on_change('value', update) dropdown.on_click(update) # Initial categories and data source src, tbl_src = make_dataset(available_categories) p = make_plot(src) pie = make_pie_chart(src) data_table = make_table(tbl_src) # Put controls in a single element controls = WidgetBox(dropdown) # Create a row layout # layout = column(p, controls, data_table) # right = column(controls, data_table) # left = column(pie, p) right = column(p) left = column(pie, controls, data_table) layout = row(left, right) # Make a tab with the layout tab = Panel(child=layout, title='Expenses') return tab
p.title.align = 'center' p.title.text_color = Viridis256[50] p.title.text_font = 'helvetica' p.title.text_font_style = 'bold' p.title.text_font_size = '16pt' # x-axis p.xaxis.axis_label = 'Weight' p.xaxis.axis_label_text_color = Viridis256[150] # y-axis p.yaxis.axis_label = 'Horsepower' p.yaxis.axis_label_text_color = Viridis256[150] # setup widget menu = [(b.capitalize(), b) for b in autompg.brand.unique()] dropdown = Dropdown(label='Brand', menu=menu) # callback to widgets def callback(attr, old, new): brand = dropdown.value source.data = ColumnDataSource.from_df(autompg.loc[autompg.brand == brand]) dropdown.on_change('value', callback) # arrange plots and widgets in layouts layout = column(dropdown, p) curdoc().add_root(layout)
functional_telescope_area = 0 functional_object_type = 0 functional_object_x = [] functional_object_y = [] functional_redshift = default_redshift ''' widget factory TODO: check for float values... I guess? ''' # radio button groups widget_telescope_sizes = RadioButtonGroup(labels=string_telescope_sizes, active=0) widget_object_types = RadioButtonGroup(labels=string_object_types, active=default_object_types) widget_galaxy_type = Dropdown(label=string_title[12],menu=string_galaxy_types) widget_mag_type = RadioButtonGroup(labels=string_magnitude_three,active=0) widget_grating_types = RadioButtonGroup(labels=string_grating_types, active=0) widget_moon_days = RadioButtonGroup(labels=string_moon_days, active=0) # TODO: need title for this, would be string_title[7] widget_binned_pixel_scale_mode = RadioButtonGroup(labels=string_binned_pixel_scale_modes, active=0) # dropdown menus widget_types_types = Dropdown(label=string_object_types_types[0],menu=string_star_types) # TODO: dynamically set these widget_filters = Dropdown(label='Filter',menu=string_filters_menu,width=100) # text input widget_mag_input = TextInput(value=default_magnitude_two,title=string_suffixes[0].title(),width=75) widget_redshift = TextInput(value=str(default_redshift), title=string_title[3]) widget_seeing = TextInput(value=default_seeing, title=string_title[5]) widget_slit_width = TextInput(value=default_slit_width, title=string_title[6]) widget_binned_pixel_scale = TextInput(value=default_binned_pixel_scale,title=string_binned_pixel_scale_manual) # TODO: hide on default # sliders widget_exposure_time = Slider(start=default_exposure_time_start, end=default_exposure_time_end,
tkRoot.withdraw() # Close the root window fout = tkFileDialog.asksaveasfilename(initialdir=database_dir, initialfile='stackplt-' + PlotID + '.npy') if fout: imgdict np.save(fout, imgdict) Div_info.text = """<p>Stack-plot saved to <b>{}</b></p>.""".format( fout) else: pass menu_stackplt = [("Open", "Open"), ("Save As", "Save As")] DropDn_stackplt = Dropdown( label="File", menu=menu_stackplt, width=config_main['plot_config']['tab_MkPlot']['button_wdth_small']) DropDn_stackplt.on_change('value', DropDn_stackplt_handler) BUT_exit = Button( label='Exit', width=config_main['plot_config']['tab_MkPlot']['button_wdth'], button_type='danger') BUT_exit.on_click(exit_update) # todo dump stackplt data lout = row(column(p_img, p_imgprofile), column(RadioButG_XYswitch, DropDn_stackplt, BUT_exit, Div_info)) curdoc().add_root(lout) curdoc().title = "StackPlt"
def Gulmay_Output_Graph(conn): ############################################################################ #################### CREATE THE DATA FOR THE GRAPH ######################### output_file( "Gulmay_Output_Graph.html" ) #???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? # Use the connection passed to the function to read the data into a # dataframe via an SQL query df = pd.read_sql( 'select [gulmay session ID], [output], ' \ '[chamber and electrometer], [Dose rate],' \ '[energy], [T/P factor], [Temp], [Press]' \ 'from [gulmay output]', conn ) # Going to want to turn the 'gulmay session id' into a date. Will do it at # the top to speed up and simplify callbacks later df.loc[:, 'gulmay session id'] = df.loc[:, 'gulmay session id'].str.slice( stop=10) df.loc[:, 'gulmay session id'] = pd.to_datetime(df.loc[:, 'gulmay session id']) # Create a list of the fields using the dataframe TableFields = (list(df.columns)) ############################################################################ ################## CREATE DROPDOWNS FOR CHANGING AXIS ###################### menu = [ ] # ???????????? don't think this is actually needed ??????????????????????????????????????????????????????????????????????????????????????????????? # The dropdown function needs an extra elelment of the form 'item_i' so this # counter is to provide this i = 1 for field in TableFields: menu.append((field, 'item_' + str(i))) i = i + 1 dropdown = Dropdown(label='Fields', button_type='warning', menu=menu) # The select funtion will be used to create dropdown lists to change the # x and y axis # The select function doesn't need the extra element of the form item_i # First make a select menu for changing the x_axis from the list of # avialible fields menu_x = [] for field in TableFields: menu_x.append(field) select_x = Select(title='Fields available:', value='gulmay session id', options=menu_x) # Need to do the same for the y_axis so just copy the x_axis accross and # make a select function (much quicker than running the loop again and # could probably copy accross the select function but done this way for # clarity of code) menu_y = menu_x select_y = Select(title='Fields available:', value='output', options=menu_y) ############################################################################ ########################### CREATE THE PLOT ################################ # Create a sub dataframe to make things easier later. This sub_df contains # an 'x', 'y' and a couple of other useful data-points Sub_df = df[[ 'gulmay session id', 'output', 'chamber and electrometer', 'energy' ]] Sub_df.columns = ['x', 'y', 'ChamberCombination', 'Energy'] # When making the ColumnDataSource convert the dataframe to a dictionary. # This seems to help with the callback functions. # https://zduey.github.io/snippets/streaming-stock-data-with-bokeh/ # https://stackoverflow.com/questions/44829730/error-thrown-from-periodic-callback-valueerrormust-stream-updates-to-all-exis src = ColumnDataSource(Sub_df.to_dict(orient='list')) # Create the basics of the plot p1 = figure( title='Gulmay Output Results', x_axis_label='Energy', y_axis_label='Something (mm)', plot_height=800, plot_width=1600, ) # Plot the actual data p1.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m', '%a%d']) p1.scatter(source=src, x='x', y='y', fill_alpha=0.4, size=12, legend_label='RecordDate') # Create a hover tool and add it to the plot hover = HoverTool(tooltips=[('Date', '@x{%F}'), ('(x,y)', '($x, $y)'), ('Chamber Comb.', '@ChamberCombination')], formatters={'x': 'datetime'}) p1.add_tools(hover) # Create a layout layout = column([select_x, select_y, p1]) # Within the callback function 'old' is the previos value. (I.e. if the # select function is changed from 'Output' to 'T/P Correction', then # 'old' = 'Output' and 'new' = 'T/P Correction') def callback_x(attr, old, new): Sub_df_new = df[[ new, 'gulmay session id', 'chamber and electrometer', 'energy' ]] Sub_df_new.columns = ['x', 'y', 'Chamber', 'Energy'] # When making the ColumnDataSource convert the dataframe to a dictionary. # This seems to help with the callback functions. # https://zduey.github.io/snippets/streaming-stock-data-with-bokeh/ # https://stackoverflow.com/questions/44829730/error-thrown-from-periodic-callback-valueerrormust-stream-updates-to-all-exis src.data = Sub_df_new.to_dict(orient='list') def callback_y(attr, old, new): print(attr) print(old) print(new) Sub_df_new = df[[old, new, 'chamber and electrometer', 'energy']] Sub_df_new.columns = ['x', 'y', 'Chamber', 'Energy'] # When making the ColumnDataSource convert the dataframe to a dictionary. # This seems to help with the callback functions. # https://zduey.github.io/snippets/streaming-stock-data-with-bokeh/ # https://stackoverflow.com/questions/44829730/error-thrown-from-periodic-callback-valueerrormust-stream-updates-to-all-exis src.data = Sub_df_new.to_dict(orient='list') select_x.on_change('value', callback_x) select_y.on_change('value', callback_y) # Return a panel displaying the created plot and a title for the tab return Panel(child=layout, title='PDD')
c_map = CategoricalColorMapper( factors=["setosa","virginica","versicolor"], palette=["blue","green","red"] ) data = ColumnDataSource(data={ "x": df["sepal_length"], "y": df["sepal_width"], "x1": df["petal_length"], "y1": df["petal_width"], "target": df["target"] }) p1 = figure(title="鳶尾花資料集-花萼") p1.circle(x="x", y="y", source=data, size=15, color={"field": "target", "transform": c_map}, legend="target") p2 = figure(title="鳶尾花資料集-花瓣") p2.circle(x="x1", y="y1", source=data, size=15, color={"field": "target", "transform": c_map}, legend="target") menu = [("setosa","1"),("virginica","2"),("versicolor","3")] mnu1 = Dropdown(label="鳶尾花種類", menu=menu) mnu2 = Dropdown(label="鳶尾花種類", menu=menu) tab1 = Panel(child=column(mnu1,p1), title="花萼") tab2 = Panel(child=column(mnu2,p2), title="花瓣") tabs = Tabs(tabs=[tab1, tab2]) show(tabs)
if color_interval: source_interval_patch = ColumnDataSource(data=dict(x_patch=[], y_patch=[])) source_interval_bound = ColumnDataSource( data=dict(x_min=[], x_max=[], y_minmax=[])) ####################### # INTERACTIVE WIDGETS # ####################### # text input window for function f(x,y) to be transformed f_input = TextInput(value=sample_functions[sample_function_id][0], title="x(t):") #TODO: add Latex title for text inputs # dropdown menu for selecting one of the sample functions sample_fun_input_f = Dropdown( label="choose a sample function x(t) or enter one above", menu=sample_f_names, width=200) # text input window for T0 (Sampling interval length) t0_input = TextInput(value='1', title=u"T\u2080 (Interval)") # text input window for N (Number of sample points) N_input = TextInput(value='2^6', title=u"N (Number of sample points, max = 10\u2075)") # button to show the solution nyquist_label_default = "show sampling- and Nyquist-frequency" nyquist_button = CheckboxButtonGroup(labels=[nyquist_label_default], active=[], sizing_mode="fixed", width=240, height=32) ###########
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())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
def _create_ui_components() -> (Figure, ColumnDataSource): # pylint: disable=too-many-statements global asp_table_source, asp_filter_src, op_table_source, op_filter_src global stats, aspects, tabs, lexicons_dropdown stats = pd.DataFrame(columns=["Quantity", "Score"]) aspects = pd.Series([]) def new_col_data_src(): return ColumnDataSource({"file_contents": [], "file_name": []}) large_text = HTMLTemplateFormatter(template="""<div><%= value %></div>""") def data_column(title): return TableColumn(field=title, title='<span class="header">' + title + "</span>", formatter=large_text) asp_table_columns = [ data_column("Term"), data_column("Alias1"), data_column("Alias2"), data_column("Alias3"), ] op_table_columns = [ data_column("Term"), data_column("Score"), data_column("Polarity") ] asp_table_source = empty_table("Term", "Alias1", "Alias2", "Alias3") asp_filter_src = empty_table("Term", "Alias1", "Alias2", "Alias3") asp_src = new_col_data_src() op_table_source = empty_table("Term", "Score", "Polarity", "Polarity") op_filter_src = empty_table("Term", "Score", "Polarity", "Polarity") op_src = new_col_data_src() asp_table = DataTable( source=asp_table_source, selectable="checkbox", columns=asp_table_columns, editable=True, width=600, height=500, ) op_table = DataTable( source=op_table_source, selectable="checkbox", columns=op_table_columns, editable=True, width=600, height=500, ) asp_examples_box = _create_examples_table() op_examples_box = _create_examples_table() asp_layout = layout([[asp_table, asp_examples_box]]) op_layout = layout([[op_table, op_examples_box]]) asp_tab = Panel(child=asp_layout, title="Aspect Lexicon") op_tab = Panel(child=op_layout, title="Opinion Lexicon") tabs = Tabs(tabs=[asp_tab, op_tab], width=700, css_classes=["mytab"]) lexicons_menu = [("Open", "open"), ("Save", "save")] lexicons_dropdown = Dropdown( label="Edit Lexicons", button_type="success", menu=lexicons_menu, width=140, height=31, css_classes=["mybutton"], ) train_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")] train_dropdown = Dropdown( label="Extract Lexicons", button_type="success", menu=train_menu, width=162, height=31, css_classes=["mybutton"], ) inference_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")] inference_dropdown = Dropdown( label="Classify", button_type="success", menu=inference_menu, width=140, height=31, css_classes=["mybutton"], ) text_status = TextInput(value="Select training data", title="Train Run Status:", css_classes=["statusText"]) text_status.visible = False train_src = new_col_data_src() infer_src = new_col_data_src() with open(join(SOLUTION_DIR, "dropdown.js")) as f: args = dict( clicked=lexicons_dropdown, asp_filter=asp_filter_src, op_filter=op_filter_src, asp_src=asp_src, op_src=op_src, tabs=tabs, text_status=text_status, train_src=train_src, infer_src=infer_src, train_clicked=train_dropdown, infer_clicked=inference_dropdown, opinion_lex_generic="", ) code = f.read() args["train_clicked"] = train_dropdown train_dropdown.js_on_change("value", CustomJS(args=args, code=code)) args["train_clicked"] = inference_dropdown inference_dropdown.js_on_change("value", CustomJS(args=args, code=code)) args["clicked"] = lexicons_dropdown lexicons_dropdown.js_on_change("value", CustomJS(args=args, code=code)) def update_filter_source(table_source, filter_source): df = table_source.to_df() sel_inx = sorted(table_source.selected.indices) df = df.iloc[sel_inx, 1:] new_source = ColumnDataSource(df) filter_source.data = new_source.data def update_examples_box(data, examples_box, old, new): examples_box.source.data = {"Examples": []} unselected = list(set(old) - set(new)) selected = list(set(new) - set(old)) if len(selected) <= 1 and len(unselected) <= 1: examples_box.source.data.update({ "Examples": [str(data.iloc[unselected[0], i]) for i in range(4, 24)] if len(unselected) != 0 else [str(data.iloc[selected[0], i]) for i in range(4, 24)] }) def asp_selected_change(_, old, new): global asp_filter_src, asp_table_source, aspects_data update_filter_source(asp_table_source, asp_filter_src) update_examples_box(aspects_data, asp_examples_box, old, new) def op_selected_change(_, old, new): global op_filter_src, op_table_source, opinions_data update_filter_source(op_table_source, op_filter_src) update_examples_box(opinions_data, op_examples_box, old, new) def read_csv(file_src, headers=False, index_cols=False, readCSV=True): if readCSV: raw_contents = file_src.data["file_contents"][0] if len(raw_contents.split(",")) == 1: b64_contents = raw_contents else: # remove the prefix that JS adds b64_contents = raw_contents.split(",", 1)[1] file_contents = base64.b64decode(b64_contents) return pd.read_csv( io.BytesIO(file_contents), encoding="ISO-8859-1", keep_default_na=False, na_values={None}, engine="python", index_col=index_cols, header=0 if headers else None, ) return file_src def read_parsed_files(file_content, file_name): try: # remove the prefix that JS adds b64_contents = file_content.split(",", 1)[1] file_content = base64.b64decode(b64_contents) with open(SENTIMENT_OUT / file_name, "w") as json_file: data_dict = json.loads(file_content.decode("utf-8")) json.dump(data_dict, json_file) except Exception as e: print(str(e)) # pylint: disable=unused-argument def train_file_callback(attr, old, new): global train_data SENTIMENT_OUT.mkdir(parents=True, exist_ok=True) train = TrainSentiment(parse=True, rerank_model=None) if len(train_src.data["file_contents"]) == 1: train_data = read_csv(train_src, index_cols=0) file_name = train_src.data["file_name"][0] raw_data_path = SENTIMENT_OUT / file_name train_data.to_csv(raw_data_path, header=False) print("Running_SentimentTraining on data...") train.run(data=raw_data_path) else: f_contents = train_src.data["file_contents"] f_names = train_src.data["file_name"] raw_data_path = SENTIMENT_OUT / train_src.data["file_name"][ 0].split("/")[0] if not os.path.exists(raw_data_path): os.makedirs(raw_data_path) for f_content, f_name in zip(f_contents, f_names): read_parsed_files(f_content, f_name) print("Running_SentimentTraining on data...") train.run(parsed_data=raw_data_path) text_status.value = "Lexicon extraction completed" with io.open(AcquireTerms.acquired_aspect_terms_path, "r") as fp: aspect_data_csv = fp.read() file_data = base64.b64encode(str.encode(aspect_data_csv)) file_data = file_data.decode("utf-8") asp_src.data = { "file_contents": [file_data], "file_name": ["nameFile.csv"] } out_path = LEXICONS_OUT / "generated_opinion_lex_reranked.csv" with io.open(out_path, "r") as fp: opinion_data_csv = fp.read() file_data = base64.b64encode(str.encode(opinion_data_csv)) file_data = file_data.decode("utf-8") op_src.data = { "file_contents": [file_data], "file_name": ["nameFile.csv"] } def show_analysis() -> None: global stats, aspects, plot, source, tabs plot, source = _create_plot() events_table = _create_events_table() # pylint: disable=unused-argument def _events_handler(attr, old, new): _update_events(events_table, events_type.active) # Toggle display of in-domain / All aspect mentions events_type = RadioButtonGroup( labels=["All Events", "In-Domain Events"], active=0) analysis_layout = layout([[plot], [events_table]]) # events_type display toggle disabled # analysis_layout = layout([[plot],[events_type],[events_table]]) analysis_tab = Panel(child=analysis_layout, title="Analysis") tabs.tabs.insert(2, analysis_tab) tabs.active = 2 events_type.on_change("active", _events_handler) source.selected.on_change("indices", _events_handler) # pylint: disable=no-member # pylint: disable=unused-argument def infer_file_callback(attr, old, new): # run inference on input data and current aspect/opinion lexicons in view global infer_data, stats, aspects SENTIMENT_OUT.mkdir(parents=True, exist_ok=True) df_aspect = pd.DataFrame.from_dict(asp_filter_src.data) aspect_col_list = ["Term", "Alias1", "Alias2", "Alias3"] df_aspect = df_aspect[aspect_col_list] df_aspect.to_csv(SENTIMENT_OUT / "aspects.csv", index=False, na_rep="NaN") df_opinion = pd.DataFrame.from_dict(op_filter_src.data) opinion_col_list = ["Term", "Score", "Polarity", "isAcquired"] df_opinion = df_opinion[opinion_col_list] df_opinion.to_csv(SENTIMENT_OUT / "opinions.csv", index=False, na_rep="NaN") solution = SentimentSolution() if len(infer_src.data["file_contents"]) == 1: infer_data = read_csv(infer_src, index_cols=0) file_name = infer_src.data["file_name"][0] raw_data_path = SENTIMENT_OUT / file_name infer_data.to_csv(raw_data_path, header=False) print("Running_SentimentInference on data...") text_status.value = "Running classification on data..." stats = solution.run( data=raw_data_path, aspect_lex=SENTIMENT_OUT / "aspects.csv", opinion_lex=SENTIMENT_OUT / "opinions.csv", ) else: f_contents = infer_src.data["file_contents"] f_names = infer_src.data["file_name"] raw_data_path = SENTIMENT_OUT / infer_src.data["file_name"][ 0].split("/")[0] if not os.path.exists(raw_data_path): os.makedirs(raw_data_path) for f_content, f_name in zip(f_contents, f_names): read_parsed_files(f_content, f_name) print("Running_SentimentInference on data...") text_status.value = "Running classification on data..." stats = solution.run( parsed_data=raw_data_path, aspect_lex=SENTIMENT_OUT / "aspects.csv", opinion_lex=SENTIMENT_OUT / "opinions.csv", ) aspects = pd.read_csv(SENTIMENT_OUT / "aspects.csv", encoding="utf-8")["Term"] text_status.value = "Classification completed" show_analysis() # pylint: disable=unused-argument def asp_file_callback(attr, old, new): global aspects_data, asp_table_source aspects_data = read_csv(asp_src, headers=True) # Replaces None values by empty string aspects_data = aspects_data.fillna("") new_source = ColumnDataSource(aspects_data) asp_table_source.data = new_source.data asp_table_source.selected.indices = list(range(len(aspects_data))) # pylint: disable=unused-argument def op_file_callback(attr, old, new): global opinions_data, op_table_source, lexicons_dropdown, df_opinion_generic df = read_csv(op_src, headers=True) # Replaces None values by empty string df = df.fillna("") # Placeholder for generic opinion lexicons from the given csv file df_opinion_generic = df[df["isAcquired"] == "N"] # Update the argument value for the callback customJS lexicons_dropdown.js_property_callbacks.get("change:value")[0].args[ "opinion_lex_generic"] = df_opinion_generic.to_dict(orient="list") opinions_data = df[df["isAcquired"] == "Y"] new_source = ColumnDataSource(opinions_data) op_table_source.data = new_source.data op_table_source.selected.indices = list(range(len(opinions_data))) # pylint: disable=unused-argument def txt_status_callback(attr, old, new): print("Status: " + new) text_status.on_change("value", txt_status_callback) asp_src.on_change("data", asp_file_callback) # pylint: disable=no-member asp_table_source.selected.on_change("indices", asp_selected_change) op_src.on_change("data", op_file_callback) op_table_source.selected.on_change("indices", op_selected_change) # pylint: disable=no-member train_src.on_change("data", train_file_callback) infer_src.on_change("data", infer_file_callback) return layout( [[_create_header(train_dropdown, inference_dropdown, text_status)], [tabs]])
# Plot corresponding tangent vector quiver_constraint = my_bokeh_utils.Quiver(plot, fix_at_middle=False, line_width=2, color='red') # Plot mark at position on constraint function plot.cross(x='x', y='y', color='red', size=10, line_width=2, source=source_mark) # object that detects, if a position in the plot is clicked on interactor = my_bokeh_utils.Interactor(plot) # adds callback function to interactor, if position in plot is clicked, call on_selection_change interactor.on_click(on_selection_change) # text input window for objective function f(x,y) to be optimized f_input = TextInput(value=lagrange_settings.f_init, title="f(x,y):") f_input.on_change('value', f_changed) # dropdown menu for selecting one of the sample functions sample_fun_input_f = Dropdown(label="choose a sample function f(x,y) or enter one below", menu=lagrange_settings.sample_f_names) sample_fun_input_f.on_click(sample_fun_input_f_changed) # text input window for side condition g(x,y)=0 g_input = TextInput(value=lagrange_settings.g_init, title="g(x,y):") g_input.on_change('value', g_changed) # dropdown menu for selecting one of the sample functions sample_fun_input_g = Dropdown(label="choose a sample function g(x,y) or enter one below", menu=lagrange_settings.sample_g_names) sample_fun_input_g.on_click(sample_fun_input_g_changed) # calculate data init_data() # refresh quiver field all 100ms
var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }""" button.callback = CustomJS(args=dict(source=source), code=js_download) #Create dropdown button for auxilary data menu = [("Temperature", "temperature"), ("Laser current", "laser_current")] dropdown = Dropdown(label="Select data", button_type="danger", menu=menu, value='temperature') dropdown.on_change('value', update_plot) #add figure to curdoc and configure callback lay_out = layout([[radio_button_group, slider], [f_photo], [f_aux], [dropdown, button]]) curdoc().add_root(lay_out) curdoc().add_periodic_callback(update, 1000) #updates each 1000ms
button = Button(label="Button (enabled) - has click event", button_type="primary") button.on_click(button_handler) button_disabled = Button(label="Button (disabled) - no click event", button_type="primary", disabled=True) button_disabled.on_click(button_handler) toggle = Toggle(label="Toggle button", button_type="success") toggle.on_click(toggle_handler) 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") dropdown.on_click(dropdown_handler) 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) 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_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) data = dict( dates=[date(2014, 3, i + 1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) multi_select = MultiSelect(title="Option:", value=["foo", "quux"], options=[("foo", "Foo"), ("bar", "BAR"), ("baz", "bAz"), ("quux", "quux")]) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) select = Select(title="Option:", value="foo", options=["foo", "bar", "baz", "quux"])
"y": df["sepal_width"], "x1": df["petal_length"], "y1": df["petal_width"], "target": df["target"] }) p1 = figure(title="鳶尾花資料集-花萼") p1.circle(x="x", y="y", source=data, size=15, color={ "field": "target", "transform": c_map }, legend="target") p2 = figure(title="鳶尾花資料集-花瓣") p2.circle(x="x1", y="y1", source=data, size=15, color={ "field": "target", "transform": c_map }, legend="target") menu = [("setosa", "1"), ("virginica", "2"), ("versicolor", "3")] mnu = Dropdown(label="鳶尾花種類", menu=menu) layout = gridplot([mnu, None], [p1, p2]) show(layout)
# TAB1 population view ----------------------------------------------------------------------- TAB1 population view # file loading and update file_source_tree.on_change('data', file_callback_tree) file_source_populations.on_change('data', file_callback_populations) file_source_patient.on_change('data', file_callback_pat) file_source_clinical.on_change('data', file_callback_clinical) # upload tree files menu_tree = [("Upload cluster coordinates", "coordinates"), ("Upload graph edges", "edges")] tree_dropdown = Dropdown(label="Upload tree structure", button_type="warning", menu=menu_tree, css_classes=['dropdowns']) tree_dropdown.callback = CustomJS(args=dict(file_source=file_source_tree), code=open(join(dirname(__file__), "static/js/upload.js")).read()) # upload patients data upload_patients = Button(label="upload patients data") upload_patients.js_on_click(CustomJS(args=dict(file_source=file_source_patient), code=open(join(dirname(__file__), "static/js/upload_multiple.js")).read())) # upload population list upload_populations = Button(label="upload population list") upload_populations.js_on_click(CustomJS(args=dict(file_source=file_source_populations), code=open(join(dirname(__file__), "static/js/upload.js")).read())) # select patient patient = Select(title='Patient', value='None', options=['None'] + df_viz.columns.tolist())
def overview(states): state_x = [(code, states[code]["lons"]) for code in states] state_xsTest = sorted(state_x, key=lambda x: x[0]) state_xf = [i[1] for i in state_xsTest] state_y = [(code, states[code]["lats"]) for code in states] state_ysTest = sorted(state_y, key=lambda x: x[0]) state_yf = [i[1] for i in state_ysTest] summ['plot'] = summ['percent'].copy() summ['true'] = summ['percent'].copy() colors = bokeh.palettes.Blues9[::-1] mapper = LinearColorMapper(palette=colors, nan_color='white', low=0., high=100.) ticker = FixedTicker(ticks=[0, 50, 100]) cbar = ColorBar(color_mapper=mapper, ticker=ticker, label_standoff=12, border_line_color=None, location=(0, 0)) source = ColumnDataSource(data=dict(x=state_xf, y=state_yf, plot=summ['plot'], true=summ['true'], user=summ['user'], job=summ['job'], JobPerUser=summ['jobPerUser'], percent=summ['percent'], state=summ['state'])) p = figure(tools="pan, zoom_in, zoom_out, hover, save,reset", toolbar_location="right", plot_width=800, plot_height=450) #title='Overview of the job market', p.title.text_font_size = '20pt' p.patches('x', 'y', source=source, fill_color={ 'field': 'plot', 'transform': mapper }, fill_alpha=0.7, line_color="grey", line_width=2, line_alpha=0.3) p.add_layout(cbar, 'right') ##################call back callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var f = cb_obj.value var max_val = 0 var min_val = 0 cb_obj['attributes']['label'] = f; for (i = 0; i < data['x'].length; i++) { data['plot'][i] = data[f][i] } for (i=0;i < data['x'].length;i++){ if(data['plot'][i] > max_val){ max_val = data['plot'][i]; } } for (i=0;i < data['x'].length;i++){ data['true'][i] = data['plot'][i] data['plot'][i] = 100. * (data['plot'][i])/ (max_val) } source.change.emit(); """) ################### menu = [('User Number', 'user'), ('Job Number', 'job'), ('Jobs Per User', 'JobPerUser'), ('Percent: job application habit', 'percent')] dropdown = Dropdown(label='Select', button_type="warning", menu=menu) dropdown.js_on_change('value', callback) hover = p.select_one(HoverTool) hover.point_policy = 'follow_mouse' hover.tooltips = [("State", '@state'), ('value', '@true')] layout1 = row(p, dropdown) df1 = df[:8] data = dict(UserID=df1['UserID'], Title=df1['Title'], Description=df1['Description'], Requirements=df1['Requirements'], City=df1['City'], State=df1['State']) source = ColumnDataSource(data) columns = [ TableColumn(field="UserID", title="UserID"), TableColumn(field="Title", title="Title"), TableColumn(field="City", title="City"), TableColumn(field="State", title="State"), TableColumn(field="Description", title="Description"), TableColumn(field="Requirements", title="Requirements") ] data_table = DataTable(source=source, columns=columns, width=1000, height=230) layout2 = row(data_table) script, divs = components({'plot': layout1, 'table': layout2}) return render_template('index.html', script=script, div=divs)
def scatter_tab(population): def make_dataset(gender_list=list(['Male']), age_start=2, age_end=26, weight_start=10, weight_end=218, height_start=80, height_end=200, bmi_start=11.2, bmi_end=67.3, bin_width=25, x_axis='SESSION_IQR', y_axis='SESSION_STD'): gender_list = sorted(gender_list) plot_population = pd.DataFrame( columns=[x_axis, y_axis, 'gender', 'color']) if len(gender_list) == 0: plot_population = pd.DataFrame( columns=[x_axis, y_axis, 'gender', 'color']) else: for i, gender_name in enumerate(gender_list): if gender_name == 'All': subset = population else: subset = population[population['GENDER2'] == gender_name] subset = subset[(subset.AGE > age_start) & (subset.AGE < age_end) & (subset.WEIGHT > weight_start) & (subset.WEIGHT < weight_end) & (subset.HEIGHT > height_start) & (subset.HEIGHT < height_end) & (subset.BMI > bmi_start) & (subset.BMI < bmi_end)] arr_df = pd.DataFrame({ 'SEQN': subset['SEQN'], x_axis: subset[x_axis], y_axis: subset[y_axis] }) arr_df['gender'] = gender_name arr_df['color'] = Category20_16[i] arr_df = arr_df[['SEQN', x_axis, y_axis, 'gender', 'color']] if gender_name == "Male": arr_df1 = arr_df elif gender_name == "Female": arr_df2 = arr_df else: arr_df3 = arr_df if len(gender_list) == 1: plot_population = arr_df plot_population = plot_population.sort_values(['gender', 'SEQN']) plot_population = plot_population[[ 'SEQN', x_axis, y_axis, 'gender', 'color' ]] plot_population = plot_population.reset_index(drop=True) elif len(gender_list) == 2: if gender_list[0] == "Female": plot_population = arr_df1.append(arr_df2, ignore_index=True) plot_population = plot_population.sort_values( ['gender', 'SEQN']) plot_population = plot_population.reset_index(drop=True) elif gender_list[1] == "Female": plot_population = arr_df3.append(arr_df2, ignore_index=True) plot_population = plot_population.sort_values( ['gender', 'SEQN']) plot_population = plot_population.reset_index(drop=True) else: plot_population = arr_df1.append(arr_df3, ignore_index=True) plot_population = plot_population.sort_values( ['gender', 'SEQN']) plot_population = plot_population.reset_index(drop=True) elif len(gender_list) == 3: plot_population = arr_df1.append(arr_df2, ignore_index=True) plot_population = plot_population.append(arr_df3, ignore_index=True) plot_population = plot_population.sort_values(['gender', 'SEQN']) plot_population = plot_population.reset_index(drop=True) return ColumnDataSource(plot_population) def make_plot(src): p = figure() menu = [( 'Raw Curve Sequence Number', 'RAW_CURVE', ), ('Force Vital Capacity (ml)', 'FVC_MAX'), ('Force Vital Capacity (ml) at 1sec', 'FEV1'), ('Force Vital Capacity (ml) at 3sec', 'FEV3'), ('Force Vital Capacity (ml) at 6sec', 'FEV6'), ('Peak expiratory flow (ml)', 'PEAK_EXPIRATORY'), ('Max-Mid expiratory flow (ml)', 'MAX_MID_EXPIRATORY'), ('Pseudo PSU', 'PSEUDO_PSU'), ('Age (years)', 'AGE'), ('Gender', 'GENDER2'), ('Height (cm)', 'HEIGHT'), ('Weight (kg)', 'WEIGHT'), ('Body mass index (kg/m2)', 'BMI'), ('Session best FVC', 'SESSION_BEST'), ('Session mean FVC', 'SESSION_MEAN'), ('Session std FVC', 'SESSION_STD'), ('Session median FVC', 'SESSION_MEDIAN'), ('Session iqr FVC', 'SESSION_IQR'), ('Session minimum FVC', 'SESSION_MINIMUM'), ('Session maximum FVC', 'SESSION_MAXIMUM'), ('Session max distance FVC', 'SESSION_MAX_DISTANCE'), ('Session median distance FVC', 'SESSION_MEDIAN_DISTANCE')] if len(src.column_names) == 5: for i in range(22): if menu[i][1] == src.column_names[1]: titulo_x = menu[i][0] titulo_y = menu[i][0] break xs = src.column_names[1] ys = src.column_names[1] gs = src.column_names[2] zs = src.column_names[3] x_title = titulo_x.title() y_title = titulo_y.title() kw = dict() kw['title'] = "%s vs %s" % (x_title, y_title) # Blank plot with correct labels p = figure(plot_width=700, plot_height=700, background_fill_color="#2E3332", **kw) p.xaxis.axis_label = x_title p.yaxis.axis_label = y_title # Quad glyphs to create a histogram p.circle(source=src, x=xs, y=ys, size=7, color=zs, legend=gs, fill_alpha=0.7) # if len(src.column_names) == 6: for i in range(22): if menu[i][1] == src.column_names[1]: titulo_x = menu[i][0] if menu[i][1] == src.column_names[2]: titulo_y = menu[i][0] xs = src.column_names[1] ys = src.column_names[2] gs = src.column_names[3] zs = src.column_names[4] x_title = titulo_x.title() y_title = titulo_y.title() kw = dict() kw['title'] = "%s vs %s" % (x_title, y_title) # Blank plot with correct labels p = figure(plot_width=700, plot_height=700, background_fill_color="#2E3332", **kw) p.xaxis.axis_label = x_title p.yaxis.axis_label = y_title # Quad glyphs to create a histogram p.circle(source=src, x=xs, y=ys, size=7, color=zs, legend=gs, fill_alpha=0.7) return p def update(): genders_to_plot = [ select_gender.labels[i] for i in select_gender.active ] new_src = make_dataset(genders_to_plot, age_start=age_select.value[0], age_end=age_select.value[1], weight_start=weight_select.value[0], weight_end=weight_select.value[1], height_start=height_select.value[0], height_end=height_select.value[1], bmi_start=bmi_select.value[0], bmi_end=bmi_select.value[1], x_axis=select_x.value, y_axis=select_y.value) layout.children[1] = make_plot(new_src) #gender selection available_gender = list(['Male', 'Female', 'All']) available_gender.sort() gender_colors = Category20_16 gender_colors.sort() select_gender = CheckboxGroup(labels=list(['Male', 'Female', 'All']), active=[0, 1, 2]) select_gender.on_change('active', lambda attr, old, new: update()) #age range select age_select = RangeSlider(start=1, end=25, value=(1, 28), step=1, title='Range of Age') age_select.on_change('value', lambda attr, old, new: update()) #weight range weight_select = RangeSlider(start=10, end=200, value=(10, 200), step=1, title='Range of Weight') weight_select.on_change('value', lambda attr, old, new: update()) #height range select height_select = RangeSlider(start=80, end=200, value=(80, 200), step=1, title='Range of Height') height_select.on_change('value', lambda attr, old, new: update()) #BMI range select bmi_select = RangeSlider(start=10, end=60, value=(10, 60), step=0.5, title='Range of Body Mass Index') bmi_select.on_change('value', lambda attr, old, new: update()) menu = [( 'Raw Curve Sequence Number', 'RAW_CURVE', ), ('Force Vital Capacity (ml)', 'FVC_MAX'), ('Force Vital Capacity (ml) at 1sec', 'FEV1'), ('Force Vital Capacity (ml) at 3sec', 'FEV3'), ('Force Vital Capacity (ml) at 6sec', 'FEV6'), ('Peak expiratory flow (ml)', 'PEAK_EXPIRATORY'), ('Max-Mid expiratory flow (ml)', 'MAX_MID_EXPIRATORY'), ('Pseudo PSU', 'PSEUDO_PSU'), ('Age (years)', 'AGE'), ('Gender', 'GENDER2'), ('Height (cm)', 'HEIGHT'), ('Weight (kg)', 'WEIGHT'), ('Body mass index (kg/m2)', 'BMI'), ('Session best FVC', 'SESSION_BEST'), ('Session mean FVC', 'SESSION_MEAN'), ('Session std FVC', 'SESSION_STD'), ('Session median FVC', 'SESSION_MEDIAN'), ('Session iqr FVC', 'SESSION_IQR'), ('Session minimum FVC', 'SESSION_MINIMUM'), ('Session maximum FVC', 'SESSION_MAXIMUM'), ('Session max distance FVC', 'SESSION_MAX_DISTANCE'), ('Session median distance FVC', 'SESSION_MEDIAN_DISTANCE')] #select x axis select_x = Dropdown(label='X Axis', button_type="warning", value='SESSION_IQR', menu=menu) select_x.on_change('value', lambda attr, old, new: update()) #select y axis select_y = Dropdown(label='Y Axis', button_type="warning", value='SESSION_STD', menu=menu) select_y.on_change('value', lambda attr, old, new: update()) # Initial carriers and data source initial_gender = [select_gender.labels[i] for i in select_gender.active] src = make_dataset(initial_gender, age_start=age_select.value[0], age_end=age_select.value[1], weight_start=weight_select.value[0], weight_end=weight_select.value[1], height_start=height_select.value[0], height_end=height_select.value[1], bmi_start=bmi_select.value[0], bmi_end=bmi_select.value[1], x_axis=select_x.value, y_axis=select_y.value) # p = make_plot(src) # Put controls in a single element controls = WidgetBox(select_gender, age_select, weight_select, bmi_select, height_select, select_x, select_y) # Create a row layout layout = row(controls, make_plot(src)) # Make a tab with the layout tab2 = Panel(child=layout, title='Scatter') update() return tab2
#build all widget objects and aggregate them in a grid plot for each panel (according to job board origin). for idx, origin in enumerate(origin_source): cv_input[origin] = FileInput(accept='.txt') location_select[origin] = RadioButtonGroup( labels=location_choice, active=0, css_classes=['custom_group_button_bokeh']) text = template_div.format(site_name=origin, number=total_job_numbers[idx], total=total_job_numbers[idx]) div_job_number[origin] = Div(text=text, height=50) select_1[origin] = Dropdown(value=age_max, label='Publication date', css_classes=['custom_button_bokeh'], menu=[("All", age_max), ("Less than 1 day", "1"), ("Less than 3 days", "3"), ("Less than 7 days", "7"), ("Less than 14 days", "14"), ("Less than 30 days", "30")]) # WARNING for Dropdown button, use value param. to set default value (and not default_value param. !!!) select_2[origin] = CheckboxGroup(labels=job_cat_labels, active=list(range(len(job_cat_labels)))) select_3[origin] = RangeSlider(title="Salary(k€)", start=min_salary[idx], end=max_salary[idx], step=5, value=(min_salary[idx], max_salary[idx]))
def table_tab(df): source = ColumnDataSource(data=dict()) def update(): current = df if select_gender.value == "Male": current = df[(df['GENDER2'] == 'Male')] elif select_gender.value == "Female": current = df[(df['GENDER2'] == 'Female')] elif select_gender.value == "All": current = df current = current[(current['HEIGHT'] >= height_select.value[0]) & (current['HEIGHT'] <= height_select.value[1]) & (current['WEIGHT'] >= weight_select.value[0]) & (current['WEIGHT'] <= weight_select.value[1]) & (current['AGE'] >= age_select.value[0]) & (current['AGE'] <= age_select.value[1]) & (current['BMI'] >= bmi_select.value[0]) & (current['BMI'] <= bmi_select.value[1])].dropna() source.data = { 'SEQN': current.SEQN, 'RAW_CURVE': current.RAW_CURVE, 'FVC_MAX': current.FVC_MAX, 'FEV1': current.FEV1, 'FEV3': current.FEV3, 'FEV6': current.FEV6, 'PEAK_EXPIRATORY': current.PEAK_EXPIRATORY, 'MAX_MID_EXPIRATORY': current.MAX_MID_EXPIRATORY, 'PSEUDO_PSU': current.PSEUDO_PSU, 'AGE': current.AGE, 'GENDER2': current.GENDER2, 'GENDER': current.GENDER, 'HEIGHT': current.HEIGHT, 'WEIGHT': current.WEIGHT, 'BMI': current.BMI, 'SESSION_BEST': current.SESSION_BEST, 'SESSION_MEAN': current.SESSION_MEAN, 'SESSION_STD': current.SESSION_STD, 'SESSION_MEDIAN': current.SESSION_MEDIAN, 'SESSION_IQR': current.SESSION_IQR, 'SESSION_MINIMUM': current.SESSION_MINIMUM, 'SESSION_MAXIMUM': current.SESSION_MAXIMUM, 'SESSION_MAX_DISTANCE': current.SESSION_MAX_DISTANCE, 'SESSION_MEDIAN_DISTANCE': current.SESSION_MEDIAN_DISTANCE } menu = [("All", "All"), ("Male", "Male"), ("Female", "Female")] select_gender = Dropdown(label="Gender Selection", button_type="warning", menu=menu) select_gender.on_change('value', lambda attr, old, new: update()) #height range select height_select = RangeSlider(title="Range of Height", start=80, end=200, value=(80, 200), step=0.5) height_select.on_change('value', lambda attr, old, new: update()) #height range select age_select = RangeSlider(title="Range of Age", start=1, end=28, value=(1, 28), step=1) age_select.on_change('value', lambda attr, old, new: update()) #weight range select weight_select = RangeSlider(title="Range of Weight", start=10, end=200, value=(10, 200), step=1) weight_select.on_change('value', lambda attr, old, new: update()) #height range select bmi_select = RangeSlider(title="Range of Body Mass Index", start=10, end=60, value=(10, 60), step=0.5) bmi_select.on_change('value', lambda attr, old, new: update()) button = Button(label="Download", button_type="success") button.callback = CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read()) columns = [ TableColumn(field='SEQN', title='SEQN'), TableColumn(field='FVC_MAX', title='FVC (ml)'), TableColumn(field='AGE', title='AGE (years)'), TableColumn(field='GENDER2', title='GENDER'), TableColumn(field='HEIGHT', title='HEIGHT (cm)'), TableColumn(field='BMI', title='BMI'), TableColumn(field="SESSION_BEST", title='SESSION MAXIMUM (ml)') ] data_table = DataTable(source=source, columns=columns, width=1000) # Put controls in a single element controls = WidgetBox(select_gender, age_select, weight_select, bmi_select, height_select, button) # Create a row layout layout = row(controls, data_table) # Make a tab with the layout tab = Panel(child=layout, title='Summary Table') update() return tab
plot4.line('x', 'y', source=source4, line_width=3, line_alpha=0.6) plot5.line('x', 'y', source=source5, line_width=3, line_alpha=0.6) a = 1.7 / 3.0 theta = np.arange(0, 2 * np.pi + 2 * np.pi * 0.01, 2 * np.pi * 0.01) x = np.arcsin(0.7) R = 1.7 + a * np.cos(theta + x * np.sin(theta)) Z = 1.8 * a * np.sin(theta) source3 = ColumnDataSource(data=dict(x=R, y=Z)) plot3.line('x', 'y', source=source3, line_width=3, line_alpha=0.6) tokamaks = [("DIII_D", "d3d"), ("JET", "JET"), ("ITER steady-state", "ITERSS"), ("ARC", "ARC"), ("CAT-DEMO", "CAT-DEMO"), ("ARIES ACT 2", "ACT2")] starting_tok = Dropdown(label="Starting Tokamak", button_type="warning", menu=tokamaks) majorRadius = Slider(title="Major Radius", value=1.7, start=0.5, end=10.0, step=0.1, callback_policy='mouseup') Bt = Slider(title="Bt", value=2.2, start=1.0, end=12.0, step=0.1, callback_policy='mouseup') delta = Slider(title="triangularity",
return price, column(price, row(volume, stochastic, macd)) # %% search_symbol = AutocompleteInput(title="Query Symbol", completions=symbol_list) plot, plot_layout = plot_stock(stock_code) stock_symbol = TextInput(title="Stock Symbol:", value="AGL.AX") porfolio_list = [("AGL.AX", "AGL.AX"), ("AIZ.AX", "AIZ.AX"), ("IFN.AX", "IFN.AX"), ("NAB.AX", "NAB.AX")] porfolio = Dropdown(label="Select from porfolio", button_type="primary", menu=porfolio_list) def update_day(attrname, old, new): offset = int(day_offset.value) new_stock = stock.iloc[-offset:] new_source = ColumnDataSource(new_stock) source.data = new_source.data def update_stock(attrname, old, new): global stock new_stock_symbol = stock_symbol.value plot.title.text = new_stock_symbol stock = get_stock(new_stock_symbol)
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())")) 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: click ' + this.toString())")) dropdown.js_on_event("menu_item_click", CustomJS(code="console.log('dropdown: ' + this.item, 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): click ' + this.toString())")) dropdown_disabled.js_on_event("menu_item_click", CustomJS(code="console.log('dropdown(disabled): ' + this.item, this.toString())")) dropdown_split = Dropdown(label="Split button", split=True, button_type="danger", menu=menu) dropdown_split.js_on_click(CustomJS(code="console.log('dropdown(split): click ' + this.toString())")) dropdown_split.js_on_event("menu_item_click", CustomJS(code="console.log('dropdown(split): ' + this.item, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: active=' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
NumberEditor, SelectEditor, ) from bokeh.plotting import figure from bokeh.sampledata.iris import flowers from bokeh.sampledata.autompg2 import autompg2 as mpg 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"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, split=True) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) text_input = TextInput(placeholder="Enter value ...")
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)) 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.on_click(lambda value: print('dropdown_split: %s' % value)) #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value)) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())"))
def __init__(self, sources, categories, dvhs, rad_bio, roi_viewer, time_series, correlation, regression, mlc_analyzer, custom_title, data_tables): self.sources = sources self.selector_categories = categories.selector self.range_categories = categories.range self.correlation_variables = categories.correlation_variables self.dvhs = dvhs self.rad_bio = rad_bio self.roi_viewer = roi_viewer self.time_series = time_series self.correlation = correlation self.regression = regression self.mlc_analyzer = mlc_analyzer self.uids = {n: [] for n in GROUP_LABELS} self.allow_source_update = True self.current_dvh = [] self.anon_id_map = [] self.colors = itertools.cycle(palette) # !!!!!!!!!!!!!!!!!!!!!!!!!!!! # Selection Filter UI objects # !!!!!!!!!!!!!!!!!!!!!!!!!!!! category_options = list(self.selector_categories) category_options.sort() # Add Current row to source self.add_selector_row_button = Button(label="Add Selection Filter", button_type="primary", width=200) self.add_selector_row_button.on_click(self.add_selector_row) # Row self.selector_row = Select(value='1', options=['1'], width=50, title="Row") self.selector_row.on_change('value', self.selector_row_ticker) # Category 1 self.select_category1 = Select(value="ROI Institutional Category", options=category_options, width=300, title="Category 1") self.select_category1.on_change('value', self.select_category1_ticker) # Category 2 cat_2_sql_table = self.selector_categories[ self.select_category1.value]['table'] cat_2_var_name = self.selector_categories[ self.select_category1.value]['var_name'] self.category2_values = DVH_SQL().get_unique_values( cat_2_sql_table, cat_2_var_name) self.select_category2 = Select(value=self.category2_values[0], options=self.category2_values, width=300, title="Category 2") self.select_category2.on_change('value', self.select_category2_ticker) # Misc self.delete_selector_row_button = Button(label="Delete", button_type="warning", width=100) self.delete_selector_row_button.on_click(self.delete_selector_row) self.group_selector = CheckboxButtonGroup( labels=["Group 1", "Group 2"], active=[0], width=180) self.group_selector.on_change('active', self.ensure_selector_group_is_assigned) self.selector_not_operator_checkbox = CheckboxGroup(labels=['Not'], active=[]) self.selector_not_operator_checkbox.on_change( 'active', self.selector_not_operator_ticker) # !!!!!!!!!!!!!!!!!!!!!!!!!!!! # Range Filter UI objects # !!!!!!!!!!!!!!!!!!!!!!!!!!!! category_options = list(self.range_categories) category_options.sort() # Add Current row to source self.add_range_row_button = Button(label="Add Range Filter", button_type="primary", width=200) self.add_range_row_button.on_click(self.add_range_row) # Row self.range_row = Select(value='', options=[''], width=50, title="Row") self.range_row.on_change('value', self.range_row_ticker) # Category self.select_category = Select(value=options.SELECT_CATEGORY_DEFAULT, options=category_options, width=240, title="Category") self.select_category.on_change('value', self.select_category_ticker) # Min and max self.text_min = TextInput(value='', title='Min: ', width=150) self.text_min.on_change('value', self.min_text_ticker) self.text_max = TextInput(value='', title='Max: ', width=150) self.text_max.on_change('value', self.max_text_ticker) # Misc self.delete_range_row_button = Button(label="Delete", button_type="warning", width=100) self.delete_range_row_button.on_click(self.delete_range_row) self.group_range = CheckboxButtonGroup(labels=["Group 1", "Group 2"], active=[0], width=180) self.group_range.on_change('active', self.ensure_range_group_is_assigned) self.range_not_operator_checkbox = CheckboxGroup(labels=['Not'], active=[]) self.range_not_operator_checkbox.on_change( 'active', self.range_not_operator_ticker) self.query_button = Button(label="Query", button_type="success", width=100) self.query_button.on_click(self.update_data) # define Download button and call download.js on click menu = [("All Data", "all"), ("Lite", "lite"), ("Only DVHs", "dvhs"), ("Anonymized DVHs", "anon_dvhs")] self.download_dropdown = Dropdown(label="Download", button_type="default", menu=menu, width=100) self.download_dropdown.callback = CustomJS( args=dict(source=sources.dvhs, source_rxs=sources.rxs, source_plans=sources.plans, source_beams=sources.beams), code=open(join(dirname(__file__), "download.js")).read()) self.layout = column( Div(text="<b>DVH Analytics v%s</b>" % options.VERSION), row(custom_title['1']['query'], Spacer(width=50), custom_title['2']['query'], Spacer(width=50), self.query_button, Spacer(width=50), self.download_dropdown), Div(text="<b>Query by Categorical Data</b>", width=1000), self.add_selector_row_button, row(self.selector_row, Spacer(width=10), self.select_category1, self.select_category2, self.group_selector, self.delete_selector_row_button, Spacer(width=10), self.selector_not_operator_checkbox), data_tables.selection_filter, Div(text="<hr>", width=1050), Div(text="<b>Query by Numerical Data</b>", width=1000), self.add_range_row_button, row(self.range_row, Spacer(width=10), self.select_category, self.text_min, Spacer(width=30), self.text_max, Spacer(width=30), self.group_range, self.delete_range_row_button, Spacer(width=10), self.range_not_operator_checkbox), data_tables.range_filter)
'show arc length parametrization'], active=[0, 1]) parametrization_input.on_click(parametrization_change) # slider controlling the current parameter t t_value_input = Slider(title="parameter t", name='parameter t', value=arc_settings.t_value_init, start=arc_settings.t_value_min, end=arc_settings.t_value_max, step=arc_settings.t_value_step) t_value_input.on_change('value', t_value_change) # text input for the x component of the curve x_component_input = TextInput(value=arc_settings.x_component_input_msg, title="curve x") x_component_input.on_change('value', curve_change) # text input for the y component of the curve y_component_input = TextInput(value=arc_settings.y_component_input_msg, title="curve y") y_component_input.on_change('value', curve_change) # dropdown menu for selecting one of the sample curves sample_curve_input = Dropdown(label="choose a sample function pair or enter one below", menu=arc_settings.sample_curve_names) sample_curve_input.on_click(sample_curve_change) # initialize plot toolset = "crosshair,pan,reset,resize,save,wheel_zoom" # Generate a figure container plot = Figure(plot_height=400, plot_width=400, tools=toolset, title="Arc length parametrization", x_range=[arc_settings.x_min_view, arc_settings.x_max_view], y_range=[arc_settings.y_min_view, arc_settings.y_max_view]) # Plot the line by the x,y values in the source property plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend='curve') # quiver related to normal length parametrization quiver = 2*[None]
# setup tooltips tooltips = [('index', '@index'), ('Sepal Length', '@sepal_length'), ('Sepal Width', '@sepal_width'), ('Species', '@species')] # setup plot p = figure(plot_width=400, plot_height=400, tooltips=tooltips) p.circle('sepal_length', 'sepal_width', size=10, color='blue', alpha=0.5, source=source) # setup widget menu = [(s.capitalize(), s) for s in flowers.species.unique()] dropdown = Dropdown(label='Species', menu=menu) # callback to widgets def callback(attr, old, new): species = dropdown.value source.data = ColumnDataSource.from_df( flowers.loc[flowers.species == species]) dropdown.on_change('value', callback) # arrange plots and widgets in layouts layout = column(dropdown, p) curdoc().add_root(layout)
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) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler)
p2.segment('x', 'sdplus', 'x', 'sdminus', source = s2, line_width = 2) p2.circle('x', 'y', color = 'color', source = s2, size = 12, alpha = 0.65) p3 = figure(width = 600, height = 400, title = 'Plot of Area vs. Area', x_axis_label = 'Area (um^2)', y_axis_label = 'Area (um^2)') p3.segment('x', 'ysdplus', 'x', 'ysdminus', source = s3, line_width = 2) p3.segment('xsdplus', 'y', 'xsdminus', 'y', source = s3, line_width = 2) p3.circle('x', 'y', color = 'color', source = s3, size = 12, alpha = 0.65) # Set up widgets kneighb = Slider(title = 'Number of nearest neighbors to average', value = 1, start = 1, end = (k - 1), step = 1) radio_button_group1 = RadioButtonGroup(labels=["NN Distance", "NN Index"], active = 0) radio_button_group2 = RadioButtonGroup(labels=["Average", "NN Difference", "NN Difference Index"], active=0) menu = [('Area', 'Area'), ('Coherency', 'Coherency'), ('Orientaiton', 'Orientation')] dropdown = Dropdown(label = 'Lower Right Parameter', menu = menu, value = 'Area') menu2 = [('Area', 'Area'), ('Coherency', 'Coherency'), ('Orientaiton', 'Orientation'), ('Distance', 'Distance')] x3drop = Dropdown(label = 'Lower Left X-axis', menu = menu2, value = 'Area') y3drop = Dropdown(label = 'Lower Left Y-axis', menu = menu2, value = 'Area') pTXT = Paragraph(text = """Welcome to the interactive Nearest Neighbor data explorer. The first toggle controls the top right plot, selecting average NN distance in microns, or NN Index (normalized by the number of domains). The next menus control the lower two plots: select which parameter to be plotted with the dropdown menus, and use the toggle to pick average value, average NN difference, or NN difference index. Green points are constant flow series, Pink are constant volume series. Error bars are 1/4 standard deviation.""") w = widgetbox(pTXT, radio_button_group1, dropdown, x3drop, y3drop, radio_button_group2) #Set up callbacks def update_data(attrname, old, new): ks = kneighb.value