#sdate_range_slider = DateRangeSlider(title="Date Range: ", start=datetime.datetime(2017, 1, 1,1), end=datetime.datetime(2017, 2, 7,2), value=(datetime.datetime(2017, 9, 7,1), datetime.datetime(2017, 9, 7,2)),step=1) #sdate_range_slider.on_change("value", my_slider_handler) #sdate_range_slider = DateSlider(title="Date Range: ", start=datetime.datetime(2017, 1, 1,1), end=datetime.datetime(2019, 9, 7,2), value=(datetime.datetime(2017, 9, 7,1), datetime.datetime(2017, 9, 7,2)), step=1) date_range_radio = RadioButtonGroup( name='Date Range Filter', labels=["Date Range Filter On", "Date Range Filter Off"], active=0) idle_range_radio = RadioButtonGroup( name='Idle Range Filter', labels=["Idle Range Filte On", "Idle Range Filte Off"], active=1) checkbox_group = CheckboxGroup( labels=["Cumulative Date Filter", "Fine Date Filter"], active=[0]) hour_range_slider = RangeSlider(start=0, end=360, value=(0, 150), step=1, title="Hour Slider") alpha_range_slider = Slider(start=0, end=1, value=0.4, step=.1, title="Spot Transparency") size_range_slider = Slider(start=4, end=50, value=4, step=1, title="Spot Size")
def setup_widgets(self): # Initial selections # Test/var/backend combination (we select all first elements at init) if not self.data.empty: self.tests = self.data\ .index.get_level_values("test").drop_duplicates().tolist() self.vars = self.data.loc[self.tests[0]]\ .index.get_level_values("variable").drop_duplicates().tolist() self.backends = self.data.loc[self.tests[0], self.vars[0]]\ .index.get_level_values("vfc_backend").drop_duplicates().tolist() else: self.tests = ["None"] self.vars = ["None"] self.backends = ["None"] # Custom JS callback that will be used client side to filter selections filter_callback_js = """ selector.options = options.filter(e => e.includes(cb_obj.value)); """ # Test selector widget # Number of runs to display # The dict structure allows us to get int value from the display string # in O(1) self.n_runs_dict = { "Last 3 runs": 3, "Last 5 runs": 5, "Last 10 runs": 10, "All runs": 0 } # Contains all options strings n_runs_display = list(self.n_runs_dict.keys()) # Will be used when updating plots (contains actual number to diplay) self.current_n_runs = self.n_runs_dict[n_runs_display[1]] # Selector widget self.widgets["select_test"] = Select(name="select_test", title="Test :", value=self.tests[0], options=self.tests) self.doc.add_root(self.widgets["select_test"]) self.widgets["select_test"].on_change("value", self.update_test) self.widgets["select_test"].on_change("options", self.update_test) # Filter widget self.widgets["test_filter"] = TextInput(name="test_filter", title="Tests filter:") self.widgets["test_filter"].js_on_change( "value", CustomJS(args=dict(options=self.tests, selector=self.widgets["select_test"]), code=filter_callback_js)) self.doc.add_root(self.widgets["test_filter"]) # Number of runs to display self.widgets["select_n_runs"] = Select(name="select_n_runs", title="Display :", value=n_runs_display[1], options=n_runs_display) self.doc.add_root(self.widgets["select_n_runs"]) self.widgets["select_n_runs"].on_change("value", self.update_n_runs) # Variable selector widget self.widgets["select_var"] = Select(name="select_var", title="Variable :", value=self.vars[0], options=self.vars) self.doc.add_root(self.widgets["select_var"]) self.widgets["select_var"].on_change("value", self.update_var) self.widgets["select_var"].on_change("options", self.update_var) # Backend selector widget self.widgets["select_backend"] = Select(name="select_backend", title="Verificarlo backend :", value=self.backends[0], options=self.backends) self.doc.add_root(self.widgets["select_backend"]) self.widgets["select_backend"].on_change("value", self.update_backend) # Outliers filtering checkbox self.widgets["outliers_filtering_compare"] = CheckboxGroup( name="outliers_filtering_compare", labels=["Filter outliers"], active=[]) self.doc.add_root(self.widgets["outliers_filtering_compare"]) self.widgets["outliers_filtering_compare"]\ .on_change("active", self.update_outliers_filtering)
def plot(tables, output_filename): ''' This is the plot function that uses Bokeh functions and widgets to make an interactive hexagon plot. This function recieves: - tables: dictionary with tables used to create arrays of repeated x, y coordinates (depending on the counts) for the hexagon plot. - output_filename: filename of .html output in the plots folder The coordinate arrays are used to create a pandas dataframe with Bokeh functions. This dataframe contains the q, r coordinates and counts used to plot the hexagons. To this dataframe, extra information is added (e.g. most common chemicals), which is displayed in the hover tooltip. Gaussian blur is added to copies of this dataframe and given as input to the Bokeh slider widget. Other widgets are added as well, for saturation, normalisation etc. Bokeh allows to customize these widges with javascript code. The hexagon plot is saved as a .html file and also shown in the browser. ''' file_name = 'plots/' + str(output_filename) + '.html' output_file(file_name) # Blur and saturation values BLUR_MAX = 3 BLUR_STEP_SIZE = 1 SATURATION_MAX = 5 SATURATION_STEP_SIZE = 0.25 # First, create array for plot properties ( ratio, size of hexagons etc.) default_term = list(tables.keys())[0] x, y, ids = create_array(tables[default_term]['table'], normalisation=False) # Hexagon plot properties length = len(x) orientation = 'flattop' ratio = ((max(y) - min(y)) / (max(x) - min(x))) size = 10 / ratio h = sqrt(3) * size h = h * ratio title = 'Hexbin plot for ' + str( length) + ' annotated chemicals with query ' + str(default_term) # make figure p = figure(title=title, x_range=[min(x) - 0.5, max(x) + 0.5], y_range=[0 - (h / 2), max(y) + 100], tools="wheel_zoom,reset,save", background_fill_color='#440154') p.grid.visible = False p.xaxis.axis_label = "log(P)" p.yaxis.axis_label = "mass in Da" p.xaxis.axis_label_text_font_style = 'normal' p.yaxis.axis_label_text_font_style = 'normal' # source for plot term_to_source, term_to_metadata, options = make_plot_sources( tables, size, ratio, orientation, BLUR_MAX, BLUR_STEP_SIZE) # start source for plot, this is the source that is first displayed in the hexagon figure x, y, ids = create_array(tables[default_term]['table'], normalisation=False) df = hexbin(x, y, ids, size, aspect_scale=ratio, orientation=orientation) df = add_counts(df, tables[default_term]['table']) source = ColumnDataSource(df) metadata = term_to_metadata[default_term] metadata = return_html(metadata) # color mapper mapper = linear_cmap('scaling', 'Viridis256', 0, max(source.data['scaling'])) # plot hex = p.hex_tile(q="q", r="r", size=size, line_color=None, source=source, aspect_scale=ratio, orientation=orientation, fill_color=mapper) # HOVER TOOLTIPS = return_tooltip() code_callback_hover = return_code('hover') callback_hover = CustomJS(code=code_callback_hover) hover = HoverTool(tooltips=TOOLTIPS, callback=callback_hover, show_arrow=False) p.add_tools(hover) # WIDGETS slider1 = Slider(start=1, end=SATURATION_MAX, value=1, step=SATURATION_STEP_SIZE, title="Saturation", width=100) slider2 = Slider(start=0, end=BLUR_MAX, value=0, step=BLUR_STEP_SIZE, title="Blur", width=100) checkbox = CheckboxGroup(labels=["TFIDF"], active=[]) radio_button_group = RadioGroup(labels=["Viridis256", "Greys256"], active=0) button = Button(label="Metadata", button_type="default", width=100) multi_select = MultiSelect(title=output_filename, value=[default_term], options=options, width=100, height=300) # WIDGETS CODE FOR CALLBACK code_callback_slider1 = return_code('slider1') code_callback_slider2 = return_code('slider2') code_callback_checkbox = return_code('checkbox') code_callback_rbg = return_code('rbg') code_callback_button = return_code('button') code_callback_ms = return_code('multi_select') # WIDGETS CALLBACK callback_slider1 = CustomJS(args={ 'source': source, 'mapper': mapper }, code=code_callback_slider1) callback_slider2 = CustomJS(args={ 'source': source, 'mapper': mapper, 'slider1': slider1, 'multi_select': multi_select, 'checkbox': checkbox, 'term_to_source': term_to_source, 'step_size': BLUR_STEP_SIZE }, code=code_callback_slider2) callback_checkbox = CustomJS(args={ 'source': source, 'term_to_source': term_to_source, 'multi_select': multi_select, 'step_size': BLUR_STEP_SIZE, 'slider1': slider1, 'slider2': slider2, 'mapper': mapper }, code=code_callback_checkbox) callback_radio_button_group = CustomJS(args={ 'p': p, 'mapper': mapper, 'Viridis256': Viridis256, 'Greys256': Greys256 }, code=code_callback_rbg) callback_button = CustomJS(args={ 'term_to_metadata': term_to_metadata, 'multi_select': multi_select }, code=code_callback_button) callback_ms = CustomJS(args={ 'source': source, 'term_to_source': term_to_source, 'checkbox': checkbox, 'metadata': metadata, 'step_size': BLUR_STEP_SIZE, 'slider2': slider2, 'slider1': slider1, 'p': p, 'mapper': mapper }, code=code_callback_ms) # # WIDGETS INTERACTION slider1.js_on_change('value', callback_slider1) slider2.js_on_change('value', callback_slider2) checkbox.js_on_change('active', callback_checkbox) radio_button_group.js_on_change('active', callback_radio_button_group) button.js_on_event(events.ButtonClick, callback_button) multi_select.js_on_change("value", callback_ms) # LAYOUT layout = row( multi_select, p, column(slider1, slider2, checkbox, radio_button_group, button)) show(layout)
def create(): doc = curdoc() det_data = {} cami_meta = {} def proposal_textinput_callback(_attr, _old, new): nonlocal cami_meta proposal = new.strip() for zebra_proposals_path in pyzebra.ZEBRA_PROPOSALS_PATHS: proposal_path = os.path.join(zebra_proposals_path, proposal) if os.path.isdir(proposal_path): # found it break else: raise ValueError(f"Can not find data for proposal '{proposal}'.") file_list = [] for file in os.listdir(proposal_path): if file.endswith(".hdf"): file_list.append((os.path.join(proposal_path, file), file)) file_select.options = file_list cami_meta = {} proposal_textinput = TextInput(title="Proposal number:", width=210) proposal_textinput.on_change("value", proposal_textinput_callback) def upload_button_callback(_attr, _old, new): nonlocal cami_meta with io.StringIO(base64.b64decode(new).decode()) as file: cami_meta = pyzebra.parse_h5meta(file) file_list = cami_meta["filelist"] file_select.options = [(entry, os.path.basename(entry)) for entry in file_list] upload_div = Div(text="or upload .cami file:", margin=(5, 5, 0, 5)) upload_button = FileInput(accept=".cami", width=200) upload_button.on_change("value", upload_button_callback) def update_image(index=None): if index is None: index = index_spinner.value current_image = det_data["data"][index] proj_v_line_source.data.update(x=np.arange(0, IMAGE_W) + 0.5, y=np.mean(current_image, axis=0)) proj_h_line_source.data.update(x=np.mean(current_image, axis=1), y=np.arange(0, IMAGE_H) + 0.5) image_source.data.update( h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], ) image_source.data.update(image=[current_image]) if main_auto_checkbox.active: im_min = np.min(current_image) im_max = np.max(current_image) display_min_spinner.value = im_min display_max_spinner.value = im_max image_glyph.color_mapper.low = im_min image_glyph.color_mapper.high = im_max if "mf" in det_data: metadata_table_source.data.update(mf=[det_data["mf"][index]]) else: metadata_table_source.data.update(mf=[None]) if "temp" in det_data: metadata_table_source.data.update(temp=[det_data["temp"][index]]) else: metadata_table_source.data.update(temp=[None]) gamma, nu = calculate_pol(det_data, index) omega = np.ones((IMAGE_H, IMAGE_W)) * det_data["omega"][index] image_source.data.update(gamma=[gamma], nu=[nu], omega=[omega]) def update_overview_plot(): h5_data = det_data["data"] n_im, n_y, n_x = h5_data.shape overview_x = np.mean(h5_data, axis=1) overview_y = np.mean(h5_data, axis=2) overview_plot_x_image_source.data.update(image=[overview_x], dw=[n_x], dh=[n_im]) overview_plot_y_image_source.data.update(image=[overview_y], dw=[n_y], dh=[n_im]) if proj_auto_checkbox.active: im_min = min(np.min(overview_x), np.min(overview_y)) im_max = max(np.max(overview_x), np.max(overview_y)) proj_display_min_spinner.value = im_min proj_display_max_spinner.value = im_max overview_plot_x_image_glyph.color_mapper.low = im_min overview_plot_y_image_glyph.color_mapper.low = im_min overview_plot_x_image_glyph.color_mapper.high = im_max overview_plot_y_image_glyph.color_mapper.high = im_max frame_range.start = 0 frame_range.end = n_im frame_range.reset_start = 0 frame_range.reset_end = n_im frame_range.bounds = (0, n_im) scan_motor = det_data["scan_motor"] overview_plot_y.axis[1].axis_label = f"Scanning motor, {scan_motor}" var = det_data[scan_motor] var_start = var[0] var_end = var[-1] + (var[-1] - var[0]) / (n_im - 1) scanning_motor_range.start = var_start scanning_motor_range.end = var_end scanning_motor_range.reset_start = var_start scanning_motor_range.reset_end = var_end # handle both, ascending and descending sequences scanning_motor_range.bounds = (min(var_start, var_end), max(var_start, var_end)) def file_select_callback(_attr, old, new): nonlocal det_data if not new: # skip empty selections return # Avoid selection of multiple indicies (via Shift+Click or Ctrl+Click) if len(new) > 1: # drop selection to the previous one file_select.value = old return if len(old) > 1: # skip unnecessary update caused by selection drop return det_data = pyzebra.read_detector_data(new[0]) if cami_meta and "crystal" in cami_meta: det_data["ub"] = cami_meta["crystal"]["UB"] index_spinner.value = 0 index_spinner.high = det_data["data"].shape[0] - 1 index_slider.end = det_data["data"].shape[0] - 1 zebra_mode = det_data["zebra_mode"] if zebra_mode == "nb": metadata_table_source.data.update(geom=["normal beam"]) else: # zebra_mode == "bi" metadata_table_source.data.update(geom=["bisecting"]) update_image(0) update_overview_plot() file_select = MultiSelect(title="Available .hdf files:", width=210, height=250) file_select.on_change("value", file_select_callback) def index_callback(_attr, _old, new): update_image(new) index_slider = Slider(value=0, start=0, end=1, show_value=False, width=400) index_spinner = Spinner(title="Image index:", value=0, low=0, width=100) index_spinner.on_change("value", index_callback) index_slider.js_link("value_throttled", index_spinner, "value") index_spinner.js_link("value", index_slider, "value") plot = Plot( x_range=Range1d(0, IMAGE_W, bounds=(0, IMAGE_W)), y_range=Range1d(0, IMAGE_H, bounds=(0, IMAGE_H)), plot_height=IMAGE_PLOT_H, plot_width=IMAGE_PLOT_W, toolbar_location="left", ) # ---- tools plot.toolbar.logo = None # ---- axes plot.add_layout(LinearAxis(), place="above") plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") # ---- grid lines plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph image_source = ColumnDataSource( dict( image=[np.zeros((IMAGE_H, IMAGE_W), dtype="float32")], h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], gamma=[np.zeros((1, 1))], nu=[np.zeros((1, 1))], omega=[np.zeros((1, 1))], x=[0], y=[0], dw=[IMAGE_W], dh=[IMAGE_H], )) h_glyph = Image(image="h", x="x", y="y", dw="dw", dh="dh", global_alpha=0) k_glyph = Image(image="k", x="x", y="y", dw="dw", dh="dh", global_alpha=0) l_glyph = Image(image="l", x="x", y="y", dw="dw", dh="dh", global_alpha=0) gamma_glyph = Image(image="gamma", x="x", y="y", dw="dw", dh="dh", global_alpha=0) nu_glyph = Image(image="nu", x="x", y="y", dw="dw", dh="dh", global_alpha=0) omega_glyph = Image(image="omega", x="x", y="y", dw="dw", dh="dh", global_alpha=0) plot.add_glyph(image_source, h_glyph) plot.add_glyph(image_source, k_glyph) plot.add_glyph(image_source, l_glyph) plot.add_glyph(image_source, gamma_glyph) plot.add_glyph(image_source, nu_glyph) plot.add_glyph(image_source, omega_glyph) image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") plot.add_glyph(image_source, image_glyph, name="image_glyph") # ---- projections proj_v = Plot( x_range=plot.x_range, y_range=DataRange1d(), plot_height=150, plot_width=IMAGE_PLOT_W, toolbar_location=None, ) proj_v.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") proj_v.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="below") proj_v.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_v.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_v_line_source = ColumnDataSource(dict(x=[], y=[])) proj_v.add_glyph(proj_v_line_source, Line(x="x", y="y", line_color="steelblue")) proj_h = Plot( x_range=DataRange1d(), y_range=plot.y_range, plot_height=IMAGE_PLOT_H, plot_width=150, toolbar_location=None, ) proj_h.add_layout(LinearAxis(), place="above") proj_h.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="left") proj_h.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_h.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_h_line_source = ColumnDataSource(dict(x=[], y=[])) proj_h.add_glyph(proj_h_line_source, Line(x="x", y="y", line_color="steelblue")) # add tools hovertool = HoverTool(tooltips=[ ("intensity", "@image"), ("gamma", "@gamma"), ("nu", "@nu"), ("omega", "@omega"), ("h", "@h"), ("k", "@k"), ("l", "@l"), ]) box_edit_source = ColumnDataSource(dict(x=[], y=[], width=[], height=[])) box_edit_glyph = Rect(x="x", y="y", width="width", height="height", fill_alpha=0, line_color="red") box_edit_renderer = plot.add_glyph(box_edit_source, box_edit_glyph) boxedittool = BoxEditTool(renderers=[box_edit_renderer], num_objects=1) def box_edit_callback(_attr, _old, new): if new["x"]: h5_data = det_data["data"] x_val = np.arange(h5_data.shape[0]) left = int(np.floor(new["x"][0])) right = int(np.ceil(new["x"][0] + new["width"][0])) bottom = int(np.floor(new["y"][0])) top = int(np.ceil(new["y"][0] + new["height"][0])) y_val = np.sum(h5_data[:, bottom:top, left:right], axis=(1, 2)) else: x_val = [] y_val = [] roi_avg_plot_line_source.data.update(x=x_val, y=y_val) box_edit_source.on_change("data", box_edit_callback) wheelzoomtool = WheelZoomTool(maintain_focus=False) plot.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), hovertool, boxedittool, ) plot.toolbar.active_scroll = wheelzoomtool # shared frame ranges frame_range = Range1d(0, 1, bounds=(0, 1)) scanning_motor_range = Range1d(0, 1, bounds=(0, 1)) det_x_range = Range1d(0, IMAGE_W, bounds=(0, IMAGE_W)) overview_plot_x = Plot( title=Title(text="Projections on X-axis"), x_range=det_x_range, y_range=frame_range, extra_y_ranges={"scanning_motor": scanning_motor_range}, plot_height=400, plot_width=IMAGE_PLOT_W - 3, ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_x.toolbar.logo = None overview_plot_x.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_x.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_x.add_layout(LinearAxis(axis_label="Coordinate X, pix"), place="below") overview_plot_x.add_layout(LinearAxis(axis_label="Frame", major_label_orientation="vertical"), place="left") # ---- grid lines overview_plot_x.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_x.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_x_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[IMAGE_W], dh=[1])) overview_plot_x_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_x.add_glyph(overview_plot_x_image_source, overview_plot_x_image_glyph, name="image_glyph") det_y_range = Range1d(0, IMAGE_H, bounds=(0, IMAGE_H)) overview_plot_y = Plot( title=Title(text="Projections on Y-axis"), x_range=det_y_range, y_range=frame_range, extra_y_ranges={"scanning_motor": scanning_motor_range}, plot_height=400, plot_width=IMAGE_PLOT_H + 22, ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_y.toolbar.logo = None overview_plot_y.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_y.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_y.add_layout(LinearAxis(axis_label="Coordinate Y, pix"), place="below") overview_plot_y.add_layout( LinearAxis( y_range_name="scanning_motor", axis_label="Scanning motor", major_label_orientation="vertical", ), place="right", ) # ---- grid lines overview_plot_y.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_y.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_y_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[IMAGE_H], dh=[1])) overview_plot_y_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_y.add_glyph(overview_plot_y_image_source, overview_plot_y_image_glyph, name="image_glyph") roi_avg_plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_height=150, plot_width=IMAGE_PLOT_W, toolbar_location="left", ) # ---- tools roi_avg_plot.toolbar.logo = None # ---- axes roi_avg_plot.add_layout(LinearAxis(), place="below") roi_avg_plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="left") # ---- grid lines roi_avg_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) roi_avg_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) roi_avg_plot_line_source = ColumnDataSource(dict(x=[], y=[])) roi_avg_plot.add_glyph(roi_avg_plot_line_source, Line(x="x", y="y", line_color="steelblue")) cmap_dict = { "gray": Greys256, "gray_reversed": Greys256[::-1], "plasma": Plasma256, "cividis": Cividis256, } def colormap_callback(_attr, _old, new): image_glyph.color_mapper = LinearColorMapper(palette=cmap_dict[new]) overview_plot_x_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) overview_plot_y_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) colormap = Select(title="Colormap:", options=list(cmap_dict.keys()), width=210) colormap.on_change("value", colormap_callback) colormap.value = "plasma" STEP = 1 def main_auto_checkbox_callback(state): if state: display_min_spinner.disabled = True display_max_spinner.disabled = True else: display_min_spinner.disabled = False display_max_spinner.disabled = False update_image() main_auto_checkbox = CheckboxGroup(labels=["Main Auto Range"], active=[0], width=145, margin=[10, 5, 0, 5]) main_auto_checkbox.on_click(main_auto_checkbox_callback) def display_max_spinner_callback(_attr, _old_value, new_value): display_min_spinner.high = new_value - STEP image_glyph.color_mapper.high = new_value display_max_spinner = Spinner( low=0 + STEP, value=1, step=STEP, disabled=bool(main_auto_checkbox.active), width=100, height=31, ) display_max_spinner.on_change("value", display_max_spinner_callback) def display_min_spinner_callback(_attr, _old_value, new_value): display_max_spinner.low = new_value + STEP image_glyph.color_mapper.low = new_value display_min_spinner = Spinner( low=0, high=1 - STEP, value=0, step=STEP, disabled=bool(main_auto_checkbox.active), width=100, height=31, ) display_min_spinner.on_change("value", display_min_spinner_callback) PROJ_STEP = 0.1 def proj_auto_checkbox_callback(state): if state: proj_display_min_spinner.disabled = True proj_display_max_spinner.disabled = True else: proj_display_min_spinner.disabled = False proj_display_max_spinner.disabled = False update_overview_plot() proj_auto_checkbox = CheckboxGroup(labels=["Projections Auto Range"], active=[0], width=145, margin=[10, 5, 0, 5]) proj_auto_checkbox.on_click(proj_auto_checkbox_callback) def proj_display_max_spinner_callback(_attr, _old_value, new_value): proj_display_min_spinner.high = new_value - PROJ_STEP overview_plot_x_image_glyph.color_mapper.high = new_value overview_plot_y_image_glyph.color_mapper.high = new_value proj_display_max_spinner = Spinner( low=0 + PROJ_STEP, value=1, step=PROJ_STEP, disabled=bool(proj_auto_checkbox.active), width=100, height=31, ) proj_display_max_spinner.on_change("value", proj_display_max_spinner_callback) def proj_display_min_spinner_callback(_attr, _old_value, new_value): proj_display_max_spinner.low = new_value + PROJ_STEP overview_plot_x_image_glyph.color_mapper.low = new_value overview_plot_y_image_glyph.color_mapper.low = new_value proj_display_min_spinner = Spinner( low=0, high=1 - PROJ_STEP, value=0, step=PROJ_STEP, disabled=bool(proj_auto_checkbox.active), width=100, height=31, ) proj_display_min_spinner.on_change("value", proj_display_min_spinner_callback) def hkl_button_callback(): index = index_spinner.value h, k, l = calculate_hkl(det_data, index) image_source.data.update(h=[h], k=[k], l=[l]) hkl_button = Button(label="Calculate hkl (slow)", width=210) hkl_button.on_click(hkl_button_callback) def events_list_callback(_attr, _old, new): doc.events_list_spind.value = new events_list = TextAreaInput(rows=7, width=830) events_list.on_change("value", events_list_callback) doc.events_list_hdf_viewer = events_list def add_event_button_callback(): diff_vec = [] p0 = [1.0, 0.0, 1.0] maxfev = 100000 wave = det_data["wave"] ddist = det_data["ddist"] gamma = det_data["gamma"][0] omega = det_data["omega"][0] nu = det_data["nu"][0] chi = det_data["chi"][0] phi = det_data["phi"][0] scan_motor = det_data["scan_motor"] var_angle = det_data[scan_motor] x0 = int(np.floor(det_x_range.start)) xN = int(np.ceil(det_x_range.end)) y0 = int(np.floor(det_y_range.start)) yN = int(np.ceil(det_y_range.end)) fr0 = int(np.floor(frame_range.start)) frN = int(np.ceil(frame_range.end)) data_roi = det_data["data"][fr0:frN, y0:yN, x0:xN] cnts = np.sum(data_roi, axis=(1, 2)) coeff, _ = curve_fit(gauss, range(len(cnts)), cnts, p0=p0, maxfev=maxfev) m = cnts.mean() sd = cnts.std() snr_cnts = np.where(sd == 0, 0, m / sd) frC = fr0 + coeff[1] var_F = var_angle[math.floor(frC)] var_C = var_angle[math.ceil(frC)] frStep = frC - math.floor(frC) var_step = var_C - var_F var_p = var_F + var_step * frStep if scan_motor == "gamma": gamma = var_p elif scan_motor == "omega": omega = var_p elif scan_motor == "nu": nu = var_p elif scan_motor == "chi": chi = var_p elif scan_motor == "phi": phi = var_p intensity = coeff[1] * abs( coeff[2] * var_step) * math.sqrt(2) * math.sqrt(np.pi) projX = np.sum(data_roi, axis=(0, 1)) coeff, _ = curve_fit(gauss, range(len(projX)), projX, p0=p0, maxfev=maxfev) x_pos = x0 + coeff[1] projY = np.sum(data_roi, axis=(0, 2)) coeff, _ = curve_fit(gauss, range(len(projY)), projY, p0=p0, maxfev=maxfev) y_pos = y0 + coeff[1] ga, nu = pyzebra.det2pol(ddist, gamma, nu, x_pos, y_pos) diff_vector = pyzebra.z1frmd(wave, ga, omega, chi, phi, nu) d_spacing = float(pyzebra.dandth(wave, diff_vector)[0]) diff_vector = diff_vector.flatten() * 1e10 dv1, dv2, dv3 = diff_vector diff_vec.append(diff_vector) if events_list.value and not events_list.value.endswith("\n"): events_list.value = events_list.value + "\n" events_list.value = ( events_list.value + f"{x_pos} {y_pos} {intensity} {snr_cnts} {dv1} {dv2} {dv3} {d_spacing}" ) add_event_button = Button(label="Add spind event") add_event_button.on_click(add_event_button_callback) metadata_table_source = ColumnDataSource( dict(geom=[""], temp=[None], mf=[None])) num_formatter = NumberFormatter(format="0.00", nan_format="") metadata_table = DataTable( source=metadata_table_source, columns=[ TableColumn(field="geom", title="Geometry", width=100), TableColumn(field="temp", title="Temperature", formatter=num_formatter, width=100), TableColumn(field="mf", title="Magnetic Field", formatter=num_formatter, width=100), ], width=300, height=50, autosize_mode="none", index_position=None, ) # Final layout import_layout = column(proposal_textinput, upload_div, upload_button, file_select) layout_image = column( gridplot([[proj_v, None], [plot, proj_h]], merge_tools=False)) colormap_layout = column( colormap, main_auto_checkbox, row(display_min_spinner, display_max_spinner), proj_auto_checkbox, row(proj_display_min_spinner, proj_display_max_spinner), ) layout_controls = column( row(metadata_table, index_spinner, column(Spacer(height=25), index_slider)), row(add_event_button, hkl_button), row(events_list), ) layout_overview = column( gridplot( [[overview_plot_x, overview_plot_y]], toolbar_options=dict(logo=None), merge_tools=True, toolbar_location="left", ), ) tab_layout = row( column(import_layout, colormap_layout), column(layout_overview, layout_controls), column(roi_avg_plot, layout_image), ) return Panel(child=tab_layout, title="hdf viewer")
def __init__(self, image_views, disp_min=0, disp_max=1000, colormap="plasma"): """Initialize a colormapper. Args: image_views (ImageView): Associated streamvis image view instances. disp_min (int, optional): Initial minimal display value. Defaults to 0. disp_max (int, optional): Initial maximal display value. Defaults to 1000. colormap (str, optional): Initial colormap. Defaults to 'plasma'. """ lin_colormapper = LinearColorMapper( palette=cmap_dict[colormap], low=disp_min, high=disp_max ) log_colormapper = LogColorMapper(palette=cmap_dict[colormap], low=disp_min, high=disp_max) for image_view in image_views: image_view.image_glyph.color_mapper = lin_colormapper color_bar = ColorBar( color_mapper=lin_colormapper, location=(0, -5), orientation="horizontal", height=15, width=100, padding=5, ) self.color_bar = color_bar # ---- selector def select_callback(_attr, _old, new): if new in cmap_dict: lin_colormapper.palette = cmap_dict[new] log_colormapper.palette = cmap_dict[new] high_color.color = cmap_dict[new][-1] select = Select( title="Colormap:", value=colormap, options=list(cmap_dict.keys()), default_size=100 ) select.on_change("value", select_callback) self.select = select # ---- auto toggle button def auto_toggle_callback(state): if state: display_min_spinner.disabled = True display_max_spinner.disabled = True else: display_min_spinner.disabled = False display_max_spinner.disabled = False auto_toggle = CheckboxGroup(labels=["Auto Colormap Range"], default_size=145) auto_toggle.on_click(auto_toggle_callback) self.auto_toggle = auto_toggle # ---- scale radiobutton group def scale_radiobuttongroup_callback(selection): if selection == 0: # Linear for image_view in image_views: image_view.image_glyph.color_mapper = lin_colormapper color_bar.color_mapper = lin_colormapper color_bar.ticker = BasicTicker() else: # Logarithmic if self.disp_min > 0: for image_view in image_views: image_view.image_glyph.color_mapper = log_colormapper color_bar.color_mapper = log_colormapper color_bar.ticker = LogTicker() else: scale_radiobuttongroup.active = 0 scale_radiobuttongroup = RadioGroup( labels=["Linear", "Logarithmic"], active=0, default_size=145 ) scale_radiobuttongroup.on_click(scale_radiobuttongroup_callback) self.scale_radiobuttongroup = scale_radiobuttongroup # ---- display max value def display_max_spinner_callback(_attr, _old_value, new_value): self.display_min_spinner.high = new_value - STEP if new_value <= 0: scale_radiobuttongroup.active = 0 lin_colormapper.high = new_value log_colormapper.high = new_value display_max_spinner = Spinner( title="Max Display Value:", low=disp_min + STEP, value=disp_max, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) display_max_spinner.on_change("value", display_max_spinner_callback) self.display_max_spinner = display_max_spinner # ---- display min value def display_min_spinner_callback(_attr, _old_value, new_value): self.display_max_spinner.low = new_value + STEP if new_value <= 0: scale_radiobuttongroup.active = 0 lin_colormapper.low = new_value log_colormapper.low = new_value display_min_spinner = Spinner( title="Min Display Value:", high=disp_max - STEP, value=disp_min, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) display_min_spinner.on_change("value", display_min_spinner_callback) self.display_min_spinner = display_min_spinner # ---- high color def high_color_callback(_attr, _old_value, new_value): lin_colormapper.high_color = new_value log_colormapper.high_color = new_value high_color = ColorPicker( title="High Color:", color=cmap_dict[colormap][-1], default_size=90 ) high_color.on_change("color", high_color_callback) self.high_color = high_color # ---- mask color def mask_color_callback(_attr, _old_value, new_value): lin_colormapper.nan_color = new_value log_colormapper.nan_color = new_value mask_color = ColorPicker(title="Mask Color:", color="gray", default_size=90) mask_color.on_change("color", mask_color_callback) self.mask_color = mask_color
b=i.split('/') a.append(date(int(b[2])+2000,int(b[0]),int(b[1]))) plottimeline['Dates'].append('20'+b[2]+'-'+b[0]+'-'+b[1]) plottimeline['Date'] = np.array(a, dtype=np.datetime64) palette = [cc.glasbey_dark[i] for i in range(255)] # Set up widgets # Enable default countries a=[] for i,name in enumerate(list(population)): if name in default_countries: a.append(i) checkbox = CheckboxGroup(labels=list(population), active=a) btn_clear = Button(label="Clear countries", button_type="success") btng_main = CheckboxButtonGroup(labels=[ "Active", "Conf", "Recov", "Dead", "aPop"], active=[0]) slide_c_period = Slider(start=len(window), end=14, value=(c_period), step=1, title="Cont. period") # test data # name='Estonia' # print(list(zip(COV_active[name],COV_lastP[name]))) # print(COV_conf[name]) def plot_t(): source = ColumnDataSource(data=plottimeline) # Set up plot plot = figure(x_axis_type='datetime', y_axis_type='log', plot_height=800, plot_width=1600, title="My test", tools="crosshair,pan,reset,save,box_zoom,wheel_zoom")
def __init__(self, sv_rt): """Initialize a stream control widget. """ doc = curdoc() self.receiver = doc.receiver self.stats = doc.stats self.jf_adapter = doc.jf_adapter self._sv_rt = sv_rt # connect toggle button def toggle_callback(_active): if _active or not self._prev_image_buffer: self.prev_image_slider.disabled = True else: self.prev_image_slider.disabled = False self._update_toggle_view() toggle = Toggle(label="Connect", button_type="primary", tags=[True], default_size=145) toggle.js_on_change("tags", CustomJS(code=js_backpressure_code)) toggle.on_click(toggle_callback) self.toggle = toggle # data type select datatype_select = Select( title="Data type:", value="Image", options=["Image", "Gains"], default_size=145 ) self.datatype_select = datatype_select # conversion options conv_opts_div = Div(text="Conversion options:", margin=(5, 5, 0, 5)) conv_opts_cbg = CheckboxGroup( labels=["Mask", "Gap pixels", "Geometry"], active=[0, 1, 2], default_size=145 ) self.conv_opts_cbg = conv_opts_cbg self.conv_opts = column(conv_opts_div, conv_opts_cbg) # double pixels handling double_pixels_div = Div(text="Double pixels:", margin=(5, 5, 0, 5)) double_pixels_rg = RadioGroup(labels=DP_LABELS, active=0, default_size=145) self.double_pixels_rg = double_pixels_rg self.double_pixels = column(double_pixels_div, double_pixels_rg) # rotate image select rotate_values = ["0", "90", "180", "270"] rotate_image = Select( title="Rotate image (deg):", value=rotate_values[0], options=rotate_values, default_size=145, ) self.rotate_image = rotate_image # show only events self.show_only_events_toggle = CheckboxGroup(labels=["Show Only Events"], default_size=145) # Previous Image slider self._prev_image_buffer = deque(maxlen=60) def prev_image_slider_callback(_attr, _old, new): sv_rt.metadata, sv_rt.image = self._prev_image_buffer[new] # TODO: fix this workaround sv_rt.aggregated_image = sv_rt.image prev_image_slider = Slider( start=0, end=59, value_throttled=0, step=1, title="Previous Image", disabled=True, ) prev_image_slider.on_change("value_throttled", prev_image_slider_callback) self.prev_image_slider = prev_image_slider doc.add_periodic_callback(self._update_toggle_view, 1000)
def __init__(self, parent, dataset, parameters): self.parent = parent self.dataset = dataset # Set up the controls self.tools = Selector( name="Beverages", descr="Choose a plotting tool", kind="tools", css_classes=["tools"], entries={"Deli-LATTE": tools.DeliLATTE}, default="None", none_allowed=True, ) self.data = Selector( name="Main Dishes", descr="Choose a dataset", kind="datasets", css_classes=["data"], entries={ "Test data": "test", # "TOI Catalog": "toi", # "Confirmed Planets": "confirmed", }, default="Test data", ) self.xaxis = Selector( name="Build-Your-Own", descr="Choose the parameters to plot", kind="parameters", css_classes=["build-your-own"], entries=parameters, default="ra", title="X Axis", ) self.yaxis = Selector( kind="parameters", css_classes=["build-your-own"], entries=parameters, default="dist", title="Y Axis", ) self.size = Selector( name="Sides", descr="Choose additional parameters to plot", kind="parameters", css_classes=["sides"], entries=parameters, default="None", title="Marker Size", none_allowed=True, ) self.color = Selector( kind="parameters", css_classes=["sides"], entries=parameters, default="None", title="Marker Color", none_allowed=True, ) self.checkbox_labels = [ "Flip x-axis", "Flip y-axis ", "Log scale x-axis", "Log scale y-axis", ] self.specials = Selector( name="Specials", descr="Choose a special", kind="specials", css_classes=["specials"], entries={}, default="None", none_allowed=True, ) self.checkbox_group = CheckboxGroup(labels=self.checkbox_labels, active=[]) self.source = ColumnDataSource( data=dict(x=[], y=[], size=[], color=[])) # Register the callbacks for control in [self.xaxis, self.yaxis, self.size, self.color]: control.widget.on_change("value", self.param_callback) self.tools.widget.on_change("value", self.tool_callback) self.data.widget.on_change("value", self.data_callback) self.checkbox_group.on_click(self.checkbox_callback) # Setup the plot self.setup_plot() # Load and display the data self.param_callback(None, None, None)
# Set up CheckboxGroup def checkbox_group_update(attrname): start_year = range_slider.value[0] end_year = range_slider.value[1] update_data(start_year, end_year) LABELS = [ "Residential", "Vacant Land", "Commercial", "Entertainment", "Community Services", "Industrial", "Public Services", "Parks" ] default = [0] checkbox_group = CheckboxGroup(labels=LABELS, active=default, margin=(5, 5, 5, 5), inline=True) checkbox_group.on_click(checkbox_group_update) # create layout layout = layout( [ [div], [range_slider], [checkbox_group], [p], ], sizing_mode="stretch_width", margin=(10, 50, 10, 50), )
def build_widgets(): """""" check_labels = [] jump_list = [] check_active = [] app_data['label_mp'] = {} for k, v in enumerate(app_data['label_dt'].items()): app_data['label_mp'][v[0]] = k check_labels.append(v[1]) if v[1] in cfg_lo: if cfg_lo[v[1]] == 'True': check_active.append(k) jump_list.append((v[1], str(v[0]))) else: print( "label {v} is in your bulk-file but not defined in config.ini". format(v=v[1])) check_active.append(k) if len(check_active) == len(check_labels): filter_toggle_active = 0 elif len(check_active) == 0: filter_toggle_active = 1 else: filter_toggle_active = None wdg = app_data['wdg_dict'] wdg['duration'] = PreText(text="Duration: {d} seconds".format( d=app_data['app_vars']['duration']), css_classes=['duration_pre']) wdg['navigation_label'] = Div( text='Navigation:', css_classes=['navigation-dropdown', 'help-text']) wdg['navigation_text'] = Div( text= """Use the <code><b>Jump to ...</b></code> buttons to find the next or previous event type. """, css_classes=['navigation-drop']) wdg['jump_next'] = Dropdown(label="Jump to next", button_type="primary", menu=jump_list, css_classes=['jump-block']) wdg['jump_prev'] = Dropdown(label="Jump to previous", button_type="primary", menu=jump_list) wdg['export_label'] = Div(text='Export data:', css_classes=['export-dropdown', 'help-text']) wdg['export_text'] = Div( text= """Export data, as a read file, from the current position. These are written to the output directory specified in your config file. """, css_classes=['export-drop']) wdg['save_read_file'] = Button(label="Save read file", button_type="success", css_classes=[]) wdg['bulkfile_info'] = Div(text='Bulkfile info', css_classes=['bulkfile-dropdown', 'caret-down']) wdg['bulkfile_help'] = Div( text='Bulkfile info help:', css_classes=['bulkfile-help-dropdown', 'help-text', 'bulkfile-drop']) wdg['bulkfile_help_text'] = Div( text= """This contains basic information about the experiment that is recorded in the bulk-fast5-file. """, css_classes=['bulkfile-help-drop']) wdg['bulkfile_text'] = Div(text="", css_classes=['bulkfile-drop']) for k, v in app_data['app_vars']['attributes'].items(): for entry in v: wdg['bulkfile_text'].text += '<b>{f}:</b> <br><code>{val}</code><br>'.format( f=entry[0], val=app_data['app_vars'][entry[0]]) wdg['label_options'] = Div(text='Select annotations', css_classes=['filter-dropdown', 'caret-down']) wdg['filter_help'] = Div( text='filter help:', css_classes=['filter-help-dropdown', 'help-text', 'filter-drop']) wdg['filter_help_text'] = Div( text= """Select which bulkfile annotations should be rendered on the chart. 'Display annotations' will turn all annotations on or off. """, css_classes=['filter-help-drop']) wdg['toggle_annotations'] = Toggle( label="Display annotations", button_type="danger", css_classes=['toggle_button_g_r', 'filter-drop'], active=True) wdg['toggle_mappings'] = Toggle( label="Display mappings", button_type="danger", css_classes=['toggle_button_g_r', 'filter-drop'], active=True) wdg['filter_toggle_group'] = RadioButtonGroup( labels=["Select all", "Select none"], active=filter_toggle_active, css_classes=['filter-drop']) wdg['label_filter'] = CheckboxGroup(labels=check_labels, active=check_active, css_classes=['filter-drop']) wdg['plot_options'] = Div(text='Plot adjustments', css_classes=['adjust-dropdown', 'caret-down']) wdg['adjust_help'] = Div( text='adjust help:', css_classes=['adjust-help-dropdown', 'help-text', 'adjust-drop']) wdg['adjust_help_text'] = Div( text= """Adjust chart parameters, such as width, height and where annotations are rendered. These are set in the config.ini, where the default values can be edited. """, css_classes=['adjust-help-drop']) wdg['po_width'] = TextInput(title='Plot Width (px)', value=cfg_po['plot_width'], css_classes=['adjust-drop']) wdg['po_height'] = TextInput(title='Plot Height (px)', value=cfg_po['plot_height'], css_classes=['adjust-drop']) wdg['label_height'] = TextInput(title="Annotation height (y-axis)", value=cfg_po['label_height'], css_classes=['adjust-drop']) wdg['po_y_max'] = TextInput(title="y max", value=cfg_po['y_max'], css_classes=['adjust-drop', 'toggle_y_target']) wdg['po_y_min'] = TextInput(title="y min", value=cfg_po['y_min'], css_classes=['adjust-drop', 'toggle_y_target']) wdg['toggle_y_axis'] = Toggle( label="Fixed Y-axis", button_type="danger", css_classes=['toggle_button_g_r', 'adjust-drop', 'toggle_y_axis'], active=False) wdg['toggle_smoothing'] = Toggle( label="Smoothing", button_type="danger", css_classes=['toggle_button_g_r', 'adjust-drop'], active=True) wdg['label_filter'].on_change('active', update_checkboxes) wdg['filter_toggle_group'].on_change('active', update_toggle) wdg['jump_next'].on_click(next_update) wdg['jump_prev'].on_click(prev_update) wdg['save_read_file'].on_click(export_data) for name in toggle_inputs: wdg[name].on_click(toggle_button) for name in int_inputs: wdg[name].on_change('value', is_input_int) return wdg
p.xaxis.major_label_text_font_size = '12pt' p.yaxis.axis_label_text_font_size = '12pt' p.yaxis.major_label_text_font_size = '12pt' return p def get_dataset(carrier_list): subset = by_carrier[by_carrier['name'].isin(carrier_list)] new_src = ColumnDataSource(subset) return new_src def update(attr, old, new): carrier_list = [available_carriers[i] for i in carrier_select.active] new_src = get_dataset(carrier_list) src.data.update(new_src.data) carrier_select = CheckboxGroup(labels=available_carriers, active=[0]) carrier_select.on_change('active', update) src = get_dataset([available_carriers[i] for i in carrier_select.active]) p = make_plot(src) layout = row(carrier_select, p) tab = Panel(child=layout, title='Histogram') tabs = Tabs(tabs=[tab]) curdoc().add_root(tabs)
source=df_capitals, fill_color='red', line_color='red', size=4.5) capitals_tooltips = """ <div> <div> <span style="font-size: 12px;">@CapitalName_x, @{Country/Region}</span> </div> </div> """ plot.add_tools( HoverTool(renderers=[capitals_glyph], tooltips=capitals_tooltips)) capitals_checkbox = CheckboxGroup(labels=['Show capitals'], active=[0]) def show_capitals_callback(active): """ Callback function for the 'Show capitals' checkbox. If the checkbox is active, show the countries' capitals and hover tool. Otherwise, hide them. """ if active: capitals_glyph.visible = True else: capitals_glyph.visible = False capitals_checkbox.on_click(show_capitals_callback)
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, selectable=True) checkbox = CheckboxGroup(labels=[str(i) for i in data["dates"]]) button = Button(label="Log") source_code = """ var inds = cb_obj.selected['1d'].indices; checkbox.active = inds; checkbox.change.emit() """ checkbox_code = """ source.selected['1d'].indices = cb_obj.active; """ button_code = """
def createMaleableInputs(): currWeightSlider = Slider(title="Base weight", value=inputDict['currWeight'] * 2.205, start=0, end=400, step=1) intWeightSlider = Slider(title="Int weight", value=inputDict['intWeight'] * 2.205, start=0, end=400, step=1) currSmokerCheckbox = CheckboxGroup(labels=["Base smoking"], active=[]) intSmokerCheckbox = CheckboxGroup(labels=["Int smoking"], active=[]) currWaterSlider = Slider(title="Base cups of water", value=3, start=0, end=20, step=1) intWaterSlider = Slider(title="Int cups of water", value=3, start=0, end=20, step=1) alcoholdFrequencyList = [ 'daily', '3-4 times a week', 'Once or twice a week', 'Once or twice a month', 'No more than once a month' ] currAlcohol_freqeuncySelector = Select(title="Base alcohol frequency", options=alcoholdFrequencyList, value='3-4 times a week') intAlcohol_freqeuncySelector = Select(title="Int alcohol frequency", options=alcoholdFrequencyList, value='3-4 times a week') currDailyScreenTimeSlider = Slider(title="Base screen time", value=inputDict['currDailyScreenTime'], start=0, end=300, step=10) intDailyScreenTimeSlider = Slider(title="Int screen time", value=inputDict['intDailyScreenTime'], start=0, end=300, step=10) currActivityLevelSlider = Slider(title="Base activity level", value=2, start=1, end=5, step=1) intActivityLevelSlider = Slider(title="Int activity", value=2, start=1, end=5, step=1) currHours_of_sleepSlider = Slider(title="Base sleep (hrs)", value=7, start=1, end=14, step=1) intHours_of_sleepSlider = Slider(title="Int sleep (hrs)", value=7, start=1, end=14, step=1) currCarboSlider = Slider(title="Base carbs (g)", value=inputDict['currCarbo'], start=0, end=600, step=20) intCarboSlider = Slider(title="Int carbs (g)", value=inputDict['intCarbo'], start=0, end=600, step=20) currFatSlider = Slider(title="Base fat (g)", value=inputDict['currFat'], start=0, end=120, step=5) intFatSlider = Slider(title="Int fat (g)", value=inputDict['intFat'], start=0, end=120, step=5) currProtnSlider = Slider(title="Base protein (g)", value=inputDict['currProtn'], start=0, end=120, step=5) intProtnSlider = Slider(title="Int protein (g)", value=inputDict['intProtn'], start=0, end=120, step=5) currMaleableInputs = [ currWeightSlider, currWaterSlider, currAlcohol_freqeuncySelector, currDailyScreenTimeSlider, currActivityLevelSlider, currHours_of_sleepSlider, currCarboSlider, currFatSlider, currProtnSlider ] # currMaleableInputsLayout = column(Div(text='Current lifestyle',style={'font-size': '200%', 'font-weight':'bold', 'color': 'black'}), # currWeightSlider, currSmokerCheckbox, currWaterSlider, currAlcohol_freqeuncySelector, currDailyScreenTimeSlider, # currActivityLevelSlider, currHours_of_sleepSlider, currCarboSlider, currFatSlider, currProtnSlider) currMaleableInputsLayout = column( Div(text='Current weight/lifestyle', style={ 'font-size': '200%', 'font-weight': 'bold', 'color': 'black' }), currWeightSlider, currDailyScreenTimeSlider, currCarboSlider, currFatSlider, currProtnSlider) intMaleableInputs = [ intWeightSlider, intSmokerCheckbox, intWaterSlider, intAlcohol_freqeuncySelector, intDailyScreenTimeSlider, intActivityLevelSlider, intHours_of_sleepSlider, intCarboSlider, intFatSlider, intProtnSlider ] # intMaleableInputsLayout = column(Div(text='Intervention',style={'font-size': '200%', 'font-weight':'bold', 'color': 'black'}), # intWeightSlider, intSmokerCheckbox, intWaterSlider, intAlcohol_freqeuncySelector, intDailyScreenTimeSlider, # intActivityLevelSlider, intHours_of_sleepSlider, intCarboSlider, intFatSlider, intProtnSlider) intMaleableInputsLayout = column( Div(text='Intervention', style={ 'font-size': '200%', 'font-weight': 'bold', 'color': 'red' }), intWeightSlider, intDailyScreenTimeSlider, intCarboSlider, intFatSlider, intProtnSlider) return currMaleableInputs, currMaleableInputsLayout, intMaleableInputs, intMaleableInputsLayout, currWeightSlider, currSmokerCheckbox, currWaterSlider, currAlcohol_freqeuncySelector, currDailyScreenTimeSlider, currActivityLevelSlider, currHours_of_sleepSlider, currCarboSlider, currFatSlider, currProtnSlider, intWeightSlider, intSmokerCheckbox, intWaterSlider, intAlcohol_freqeuncySelector, intDailyScreenTimeSlider, intActivityLevelSlider, intHours_of_sleepSlider, intCarboSlider, intFatSlider, intProtnSlider
x='year', y='temperature', source=source, # here we assign the data color={ 'field': 'country', 'transform': colormap }, # assign the colors: this is a dictionary with the keys field and transform, transform has to be a mapper object fill_alpha=0.2, size=10) # transparency and size of the circles # STEP 6: add elements to the interactive graph # SLIDER ELEMENT slider_month = Slider(start=1, end=12, step=1, value=1, title='Month to plot') # CHECKBOX ELEMENT checkbox_selection = CheckboxGroup( labels=list(data.Country.unique()), active=[0, 1, 2, 3, 4, 5] ) # default checkboxes to be active when opening the plot, right now: the 6 countries will be #active = [0, 3, 5]) # default checkboxes to be active when opening the plot, right now: the 6 countries will be def update(attrname, old, new): # Get the current slider value print( slider_month.value ) # this line should be commented, it's jut here to show the behaviour of the slider k = slider_month.value # Get the current checkbox slections print( checkbox_selection.active ) # this line should be commented, it's jut here to show the behaviour of the checkbox
def __init__(self, chart_title, x_axis_label, y_axis_label, x_data, y_data, x_axis_type='linear', y_axis_type='linear', tooltips=None, formatters=None, tail=False, tail_threshold=0): cb_height = 595 cb_width = 160 # The country we're looking at default_countries = [ 'France', 'United Kingdom', 'China', 'US', 'Brazil', 'Australia', 'India', 'Sweden', 'Germany', 'Russia', 'Philippines', 'Nigeria', 'Saudi Arabia', 'South Africa', 'Mexico', 'Spain' ] country_data = CovidData() checkboxes = CheckboxGroup(labels=country_data.menu, sizing_mode='fixed', height=cb_height, width=cb_width) plot = figure(title=chart_title, x_axis_label=x_axis_label, y_axis_label=y_axis_label, x_axis_type=x_axis_type, y_axis_type=y_axis_type, tools='pan, wheel_zoom, reset', active_drag='pan', active_scroll='wheel_zoom', sizing_mode='stretch_both') def AddDefaultCountries(): for country in default_countries: index = checkboxes.labels.index(country) checkboxes.active.append(index) def SelectCountry(attr, old, new): now_selected = list(set(new) - set(old)) was_selected = list(set(old) - set(new)) if now_selected: country = checkboxes.labels[now_selected[0]] if country_data.glyph_dict[country] == None: country_df = country_data.GetDataFrame(country) if tail == True: country_df = country_data.GetTail( country, x_data, y_data, tail_threshold) country_cds = ColumnDataSource(country_df) country_data.glyph_dict[country] = plot.line( x=x_data, y=y_data, source=country_cds, name=country, line_color=country_data.colour_dict[country], line_width=1) for tool in plot.tools: if type(tool).__name__ == 'HoverTool': plot.tools.remove(tool) # Create a hover tool hover_tool = HoverTool() # Set the tooltips hover_tool.tooltips = tooltips # Formatter for dates hover_tool.formatters = formatters # Add the tooltip plot.add_tools(hover_tool) country_data.glyph_dict[country].visible = True elif was_selected: country = checkboxes.labels[was_selected[0]] country_data.glyph_dict[country].visible = False checkboxes.on_change('active', SelectCountry) Column = column(checkboxes, sizing_mode='fixed', height=cb_height, width=cb_width, css_classes=['scrollable']) Row = row(Column, plot) Row.sizing_mode = 'stretch_both' AddDefaultCountries() curdoc().add_root(Row)
def __init__(self, nplots, plot_height=350, plot_width=700, lower=0, upper=1000, nbins=100): """Initialize histogram plots. Args: nplots (int): Number of histogram plots that will share common controls. plot_height (int, optional): Height of plot area in screen pixels. Defaults to 350. plot_width (int, optional): Width of plot area in screen pixels. Defaults to 700. lower (int, optional): Initial lower range of the bins. Defaults to 0. upper (int, optional): Initial upper range of the bins. Defaults to 1000. nbins (int, optional): Initial number of the bins. Defaults to 100. """ # Histogram plots self.plots = [] self._plot_sources = [] for ind in range(nplots): plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_height=plot_height, plot_width=plot_width, toolbar_location="left", ) # ---- tools plot.toolbar.logo = None # share 'pan', 'boxzoom', and 'wheelzoom' tools between all plots if ind == 0: pantool = PanTool() boxzoomtool = BoxZoomTool() wheelzoomtool = WheelZoomTool() plot.add_tools(pantool, boxzoomtool, wheelzoomtool, SaveTool(), ResetTool()) # ---- axes plot.add_layout(LinearAxis(), place="below") plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="left") # ---- grid lines plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- quad (single bin) glyph plot_source = ColumnDataSource(dict(left=[], right=[], top=[])) plot.add_glyph( plot_source, Quad(left="left", right="right", top="top", bottom=0, fill_color="steelblue"), ) self.plots.append(plot) self._plot_sources.append(plot_source) self._counts = [] self._empty_counts() # Histogram controls # ---- histogram range toggle button def auto_toggle_callback(state): if state: # Automatic lower_spinner.disabled = True upper_spinner.disabled = True else: # Manual lower_spinner.disabled = False upper_spinner.disabled = False auto_toggle = CheckboxGroup(labels=["Auto Hist Range"], active=[0], default_size=145) auto_toggle.on_click(auto_toggle_callback) self.auto_toggle = auto_toggle # ---- histogram lower range def lower_spinner_callback(_attr, _old_value, new_value): self.upper_spinner.low = new_value + STEP self._empty_counts() lower_spinner = Spinner( title="Lower Range:", high=upper - STEP, value=lower, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) lower_spinner.on_change("value", lower_spinner_callback) self.lower_spinner = lower_spinner # ---- histogram upper range def upper_spinner_callback(_attr, _old_value, new_value): self.lower_spinner.high = new_value - STEP self._empty_counts() upper_spinner = Spinner( title="Upper Range:", low=lower + STEP, value=upper, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) upper_spinner.on_change("value", upper_spinner_callback) self.upper_spinner = upper_spinner # ---- histogram number of bins def nbins_spinner_callback(_attr, _old_value, _new_value): self._empty_counts() nbins_spinner = Spinner(title="Number of Bins:", low=1, value=nbins, default_size=145) nbins_spinner.on_change("value", nbins_spinner_callback) self.nbins_spinner = nbins_spinner # ---- histogram log10 of counts toggle button def log10counts_toggle_callback(state): self._empty_counts() for plot in self.plots: if state: plot.yaxis[0].axis_label = "log⏨(Counts)" else: plot.yaxis[0].axis_label = "Counts" log10counts_toggle = CheckboxGroup(labels=["log⏨(Counts)"], default_size=145) log10counts_toggle.on_click(log10counts_toggle_callback) self.log10counts_toggle = log10counts_toggle
# Create pandas Data Frame from CSV file df = pd.read_csv('student-por.csv') ########################################################################################################## # Create Pie Chart to display the Gender Frequency of the Students pie_data = df.groupby('sex').size().reset_index(name='count') angle = pie_data['count']/pie_data['count'].sum() * 2*pi color = ['cyan','lightgreen'] sex = ['M','F'] pie_chart = figure(title="Gender(Male Vs Female)", toolbar_location='right', x_range=(-0.5, 1.0)) columnData = ColumnDataSource(data= dict(angle=angle,color = color,sex=sex,data = pie_data)) checkbox_group = CheckboxGroup( labels=["GP", "MS"], active=[0, 1]) def updatepie(attr,old,new): if len(new) == 1: print(new[0]) if new[0] == 0: tempData = df[(df['school']== 'GP')] pie_data = tempData.groupby('sex').size().reset_index(name='count') angle = pie_data['count']/pie_data['count'].sum() * 2*pi columnData.data['angle'] = angle columnData.data['data'] = pie_data print(new[0]) elif new[0] == 1: tempData = df[(df['school']== 'MS')] pie_data = tempData.groupby('sex').size().reset_index(name='count') angle = pie_data['count']/pie_data['count'].sum() * 2*pi
elif tr.days.value < 10: dur = '{:.0f}'.format(tr.hours).replace(' ', '') else: dur = '{:.0f}'.format(tr.days).replace(' ', '') return tst.iso.replace(' ', 'T').replace('-', '').replace( ':', '').split('.')[0] + '_' + dur Text_PlotID.value = getPlotID() wavelngth_list = [ "goes", "HMI_Magnetogram", "1700", "1600", "304", "171", "193", "211", "335", "94", "131", "All" ] Wavelngth_checkbox = CheckboxGroup( labels=wavelngth_list, active=[0], width=config_main['plot_config']['tab_aiaBrowser']['button_wdth']) serieslist = {} for ll in wavelngth_list: if ll == "HMI_Magnetogram": serieslist[ll] = 'hmi.M_45s' elif ll in ["1700", "1600"]: serieslist[ll] = 'aia.lev1_uv_24s' elif ll in ['goes', 'All', 'None']: serieslist[ll] = '' else: serieslist[ll] = 'aia.lev1_euv_12s' def Wavelngth_checkbox_change(attrname, old, new): labelsactive = [
from bokeh.io import output_file, show, curdoc from bokeh.layouts import column, row from bokeh.models import CheckboxGroup def checkbox_handler(new): print('Checkbox button option ' + str(new) + 'selected.') checkbox_group = CheckboxGroup(labels=['Option 1', 'Option 2', 'Option 3'], active=[0]) checkbox_group.on_click(checkbox_handler) controls = column(checkbox_group) curdoc().add_root(row(controls))
p.add_tools(hover) p.yaxis.formatter = NumeralTickFormatter(format="0.0 a") p.legend.location = "top_left" return p def update(attr, old, new): companies_to_plot = [company_selection.labels[i] for i in company_selection.active] new_src = make_dataset(companies_to_plot) src.data.update(new_src.data) def company(state): available_companies = df_companies.loc[df_companies['state'] == state][:] sort_companies = list(set(available_companies['company'][:20])) sort_companies.sort() return sort_companies company_selection = CheckboxGroup(labels=company('California'), active = [0, 1]) company_selection.on_change('active', update) initial_companies = [company_selection.labels[i] for i in company_selection.active] company_colors = Category20_16 company_colors.sort() src = make_dataset(initial_companies) plot_state = make_plot(src) controls = WidgetBox(company_selection, width = 200) l1 = row(controls, plot_state) if plot_title == '1': r = row([plot, tplot], sizing_mode='stretch_height') doc.add_root(column(r, l1)) else: l = column(plot, row(splot, tplot), row(numco_plot, sales_plot))
def create_layout(self): # create figure self.x_range = Range1d(start=self.model.map_extent[0], end=self.model.map_extent[2], bounds=None) self.y_range = Range1d(start=self.model.map_extent[1], end=self.model.map_extent[3], bounds=None) self.fig = Figure(tools='wheel_zoom,pan', x_range=self.x_range, lod_threshold=None, plot_width=self.model.plot_width, plot_height=self.model.plot_height, background_fill_color='black', y_range=self.y_range) self.fig.min_border_top = 0 self.fig.min_border_bottom = 10 self.fig.min_border_left = 0 self.fig.min_border_right = 0 self.fig.axis.visible = False self.fig.xgrid.grid_line_color = None self.fig.ygrid.grid_line_color = None # add tiled basemap self.tile_source = WMTSTileSource(url=self.model.basemap) self.tile_renderer = TileRenderer(tile_source=self.tile_source) self.fig.renderers.append(self.tile_renderer) # add datashader layer self.image_source = ImageSource( url=self.model.service_url, extra_url_vars=self.model.shader_url_vars) self.image_renderer = DynamicImageRenderer( image_source=self.image_source) self.fig.renderers.append(self.image_renderer) # add label layer self.label_source = WMTSTileSource(url=self.model.labels_url) self.label_renderer = TileRenderer(tile_source=self.label_source) self.fig.renderers.append(self.label_renderer) # Add a hover tool self.model.legend_side_vbox = VBox() self.model.legend_bottom_vbox = VBox() # add ui components controls = [] axes_select = Select.create(name='Axes', options=self.model.axes) axes_select.on_change('value', self.on_axes_change) controls.append(axes_select) self.field_select = Select.create(name='Field', options=self.model.fields) self.field_select.on_change('value', self.on_field_change) controls.append(self.field_select) self.aggregate_select = Select.create( name='Aggregate', options=self.model.aggregate_functions) self.aggregate_select.on_change('value', self.on_aggregate_change) controls.append(self.aggregate_select) transfer_select = Select.create(name='Transfer Function', options=self.model.transfer_functions) transfer_select.on_change('value', self.on_transfer_function_change) controls.append(transfer_select) color_ramp_select = Select.create(name='Color Ramp', options=self.model.color_ramps) color_ramp_select.on_change('value', self.on_color_ramp_change) controls.append(color_ramp_select) spread_size_slider = Slider(title="Spread Size (px)", value=0, start=0, end=10, step=1) spread_size_slider.on_change('value', self.on_spread_size_change) controls.append(spread_size_slider) hover_size_slider = Slider(title="Hover Size (px)", value=8, start=4, end=30, step=1) hover_size_slider.on_change('value', self.on_hover_size_change) controls.append(hover_size_slider) controls.append(self.model.legend_side_vbox) # add map components basemap_select = Select.create(name='Basemap', value='Imagery', options=self.model.basemaps) basemap_select.on_change('value', self.on_basemap_change) image_opacity_slider = Slider(title="Opacity", value=100, start=0, end=100, step=1) image_opacity_slider.on_change('value', self.on_image_opacity_slider_change) basemap_opacity_slider = Slider(title="Basemap Opacity", value=100, start=0, end=100, step=1) basemap_opacity_slider.on_change('value', self.on_basemap_opacity_slider_change) show_labels_chk = CheckboxGroup(labels=["Show Labels"], active=[0]) show_labels_chk.on_click(self.on_labels_change) map_controls = [ basemap_select, basemap_opacity_slider, image_opacity_slider, show_labels_chk ] self.controls = VBox(width=200, height=600, children=controls) self.map_controls = HBox(width=self.fig.plot_width, children=map_controls) self.map_area = VBox(width=self.fig.plot_width, children=[ self.map_controls, self.fig, self.model.legend_bottom_vbox ]) self.layout = HBox(width=1366, children=[self.controls, self.map_area]) self.model.fig = self.fig self.model.update_hover()
from bokeh.io import output_file, show from bokeh.models import CheckboxGroup output_file("checkbox_group.html") checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) show(checkbox_group)
4:(line_Hospitalized_1, line_Hospitalized_2), 5:(line_Daily_Infected_1, line_Daily_Infected_2), 6:(line_Daily_Dead_1, line_Daily_Dead_2)} # Dimensions quarantine_policy = {'No Quarantine': 'no_quarantine', 'Quarantine':'quarantine'}#'Random Quarantine': 'Rand','HyperSocial Qurarantine': 'Hyper'} quarantine_object = {'People': 'People', 'Location':'Location', 'Both':'Both'} quarantine_object_type = {'Hypersocial':'Hyper', 'Random':'Random'} quarantine_percentile = {'1%': '1', '2%': '2', '5%': '5', '10%': '10'} quarantine_start = {'17':'start_17'} quarantine_period = {'14':'14 Days','28':'28 Days','42':'42 Days'} head = Div(text="""<h1>Compare models to analyze spread of Covid-19</h1>""", width=1000, height=40) checkbox_div = Div(text="""<h3>Select plot lines you want to see</h3>""", width=500, height=40) checkbox_group = CheckboxGroup(labels=["Infected", "Susceptible", "Recovered", "Dead", "Hospitalized", "Daily_Infected", "Daily_Dead"], active=list(range(7))) ##################################### R square values ################################################# rev_infected_us_val = infected_us.values[::-1] start_i = 0 for i in range(len(infected.values)-1): if rev_infected_us_val[0] >= infected.values[i] and rev_infected_us_val[0] <= infected.values[i+1]: start_i = i infected_r2 = r2_score(infected_us.values[::-1], infected.values[start_i:len(infected_us)+start_i]) dead_r2 = r2_score(dead_us.values[::-1], dead.values[start_i:len(dead_us)+start_i]) r_square_div = Div(text="""<br><h3>R-Square value between current US stats and policies(Model 1) over generated data</h3><br>Infected r2 score = """ +str(infected_r2)+"<br>Dead r2 score = "+str(dead_r2), width=500, height=200) ######################################################################################################### ## Model 1 initial model div_model_1 = Div(text="""<h3>Model 1</h3>""", width=100, height=30)
# ('infectious_parasitic','infectious_parasitic'), ('injury','injury'), ('muscular_rheumatological','muscular_rheumatological'), # ('neurological','neurological'), ('noDiagnosis','noDiagnosis'), ('other','other'), ('pyschiatric','pyschiatric'), # ('respiratory','respiratory'), ('sexualDysfunction','sexualDysfunction'), ('tumor','tumor'), ('unknown','unknown'), ('urinary','urinary')] medicalConditionList = [ 'noReport', 'ENT', 'OBGYN', 'Old_age_midLife_syndrome', 'alcohol_poisoning', 'dermatological', 'digestive', 'endocrine', 'heart', 'hematological', 'infectious_parasitic', 'injury', 'muscular_rheumatological', 'neurological', 'noDiagnosis', 'other', 'pyschiatric', 'respiratory', 'sexualDysfunction', 'tumor', 'unknown', 'urinary' ] medicalConditionSelector = Select(title="Medical Condition", options=medicalConditionList, value='noReport') pregnantCheckbox = CheckboxGroup(labels=["Pregnant"], active=[]) diabetesCheckbox = CheckboxGroup(labels=["Diabetes"], active=[]) highBPCheckbox = CheckboxGroup(labels=["High blood pressure"], active=[]) heart_attackCheckbox = CheckboxGroup(labels=["History of Heart attack"], active=[]) internal_bleedingCheckbox = CheckboxGroup( labels=["History of internal bleeding"], active=[]) fixedInputs = column( modelSelector, Div(text='Background:', width=300, style={ 'font-size': '200%', 'font-weight': 'bold', 'color': 'black'
if i not in new: data_source.data = empty_df elif old and i not in old: resample_data_source(i, main_data_sources, x_range) for (i, data_source) in enumerate(sub_data_sources): if i not in new: data_source.data = empty_df elif old and i not in old: range = Range1d( start=min([x.index.min() for j, x in enumerate(data_frames) if j in checkbox_group.active]), end=max([x.index.max() for j, x in enumerate(data_frames) if j in checkbox_group.active]) ) resample_data_source(i, sub_data_sources, range) checkbox_group = CheckboxGroup(labels=["AAPL", "GOOG"], active=[0, 1]) checkbox_group.on_change("active", change_active_stocks) # Main plot: tools = 'pan,wheel_zoom,box_zoom,reset' def resample_data_source(index, data_sources: List[ColumnDataSource], range: Range1d): cds: ColumnDataSource = data_sources[index] df = data_frames[index] start = pd.to_datetime(range.start, unit='ms') end = pd.to_datetime(range.end, unit='ms') print(f'{range.start}/{start} -> {range.end}/{end}') if range.end == 1: return sliced = df[start: end]
from bokeh.plotting import figure output_file("line_on_off.html", title="line_on_off.py example") p = figure() props = dict(line_width=4, line_alpha=0.7) x = np.linspace(0, 4 * np.pi, 100) l0 = p.line(x, np.sin(x), color=Viridis3[0], legend_label="Line 0", **props) l1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend_label="Line 1", **props) l2 = p.line(x, np.tan(x), color=Viridis3[2], legend_label="Line 2", **props) checkbox = CheckboxGroup(labels=["Line 0", "Line 1", "Line 2"], active=[0, 1, 2], width=100) callback = CustomJS(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), code=""" l0.visible = checkbox.active.includes(0) l1.visible = checkbox.active.includes(1) l2.visible = checkbox.active.includes(2) """) checkbox.js_on_change('active', callback) layout = row(checkbox, p) show(layout)
def create_plot(units, df_list): tools = "pan,box_zoom,reset" p = figure(x_axis_type='datetime', tools=tools) p.toolbar.logo = None p.yaxis[0].ticker.desired_num_ticks = 4 p.yaxis.axis_label = units props = dict(line_width=4, line_alpha=0.7, hover_line_alpha=1.0) colors = Category10[10] glyph_dict = {} labels = [] active = [] items = [] sources = [] names = 'abcdefghijklmnopqrstuvwxyz' callback_string = '{}.visible = {} in checkbox.active;' code_string = '' i = 0 for df in df_list: legend = df.columns[0] series = df.iloc[:, 0] labels.append(legend) x = series.index y = series.values.round(2) source = ColumnDataSource(data={ 'x': x, 'y': y, 'date': [str(x) for x in x] }) sources.append(source) line = p.line('x', 'y', color=colors[i], hover_color=colors[i], source=sources[i], **props) items.append((legend, [line])) name = names[i] line.name = name code_string += callback_string.format(name, str(i)) glyph_dict.update({name: line}) active.append(i) i += 1 l = Legend(items=items, location=(0, 0), orientation='horizontal', border_line_color=None) p.add_layout(l, 'below') hover = HoverTool(tooltips=[('date', '@date'), ('value', '@y{0.2f}')]) p.add_tools(hover) checkbox = CheckboxGroup(labels=labels, active=active, width=200) glyph_dict.update({'checkbox': checkbox}) checkbox.callback = CustomJS.from_coffeescript(args=glyph_dict, code=code_string) return checkbox, p #from bokeh.layouts import row # #c,p = create_plot('kcfs',df_list) #r=row([c,p]) ##doc = curdoc() ##doc.theme = theme ##doc.add_root(r) ## #show(r) ##
# Import CheckboxGroup, RadioGroup, Toggle from bokeh.models from bokeh.models import CheckboxGroup, RadioGroup, Toggle # Add a Toggle: toggle toggle = Toggle(button_type='success', label='Toggle button') # Add a CheckboxGroup: checkbox checkbox = CheckboxGroup(labels=['Option 1', 'Option 2', 'Option 3']) # Add a RadioGroup: radio radio = RadioGroup(labels=['Option 1', 'Option 2', 'Option 3']) # Add widgetbox(toggle, checkbox, radio) to the current document curdoc().add_root(widgetbox(toggle, checkbox, radio))
def __init__(self, name: str, plot_params: List[PlotParameter], param_names: List[str]): # load values self.name = name self.plot_params = plot_params self.param_names = param_names self.title = Paragraph(text=self.name, width=1000, height=200, style={ 'font-size': '40pt', 'font-weight': 'bold' }) # set up the tools and the figure itself self.tools = 'pan,wheel_zoom,box_zoom,reset,save' self.hover_tool = HoverTool( tooltips=[ ('value', '$y'), ('time', '$x{%H:%M:%S}') ], formatters={ '$x': 'datetime' }, mode='mouse' ) self.ticker_datetime = DatetimeTickFormatter(minsec=['%H:%M:%S %m/%d']) # iterator used to cycle through colors self.colors = self.colors_gen() # setting up the linear figure self.fig_linear = figure(width=1000, height=1000, tools=self.tools, x_axis_type='datetime') self.fig_linear.xaxis[0].formatter = self.ticker_datetime # setup the hover formatter self.fig_linear.add_tools(self.hover_tool) # automatically updates the range of the y-axis to center only visible lines self.fig_linear.y_range = DataRange1d(only_visible=True) # setting up the log figure self.fig_log = figure(width=1000, height=1000, tools=self.tools, x_axis_type='datetime', y_axis_type='log') self.fig_log.xaxis[0].formatter = self.ticker_datetime # setup the hover formatter self.fig_log.add_tools(self.hover_tool) # automatically updates the range of the y-axis to center only visible lines self.fig_log.y_range = DataRange1d(only_visible=True) # creates the lines self.lines_linear = [] self.lines_log = [] for params, c in zip(self.plot_params, self.colors): self.lines_linear.append(params.create_line(fig=self.fig_linear, color=c)) self.lines_log.append(params.create_line(fig=self.fig_log, color=c)) # Create the checkbox and the buttons and their respective triggers self.checkbox = CheckboxGroup(labels=self.param_names, active=list(range(len(self.param_names)))) self.all_button = Button(label='select all') self.none_button = Button(label='deselect all') self.checkbox.on_click(self.update_lines) self.all_button.on_click(self.all_selected) self.none_button.on_click(self.none_selected) # create the panels to switch from linear to log panels = [Panel(child=self.fig_linear, title='linear'), Panel(child=self.fig_log, title='log')] # creates the layout with all of the elements of this plot GUI self.layout = column(self.title, row(Tabs(tabs=panels)), self.checkbox, row(self.all_button, self.none_button))