class range_slider(): def __init__(self, widget_lst, label, start, end, step, callback_throttle, default): self.label = label self.start = start self.end = end self.step = step self.callback_throttle = callback_throttle self.default = default self.slider = None self.callback = None widget_lst.append(self) def initialize(self, widget_lst): self.slider = RangeSlider(start = self.start, end = self.end, value = self.default, step = self.step, title = self.label) widget_lst.append(self.slider) if self.callback is not None: self.slider.on_change('value', self.callback) def add_callback(self, callback): self.callback = callback if self.slider is not None: self.slider.on_change('value', self.callback) #May not keep that one def set_value(self, value): if self.slider is not None: self.slider.value = value self.default = value
def Create_Range_Sliders(): range_slider_x = RangeSlider(title='X-Axis Range', start=0, end=1, value=(0, 1), step=0.1) range_slider_y = RangeSlider(title='Y-Axis Range', start=0, end=1, value=(0, 1), step=0.1) range_slider_xdate = DateRangeSlider(title='X-Axis Range (Date)', start=date(2017, 1, 1), end=date(2017, 1, 2), value=(date(2017, 1, 1), date(2017, 1, 2)), step=1) range_slider_ydate = DateRangeSlider(title='Y-Axis Range (Date)', start=date(2017, 1, 1), end=date(2017, 1, 2), value=(date(2017, 1, 1), date(2017, 1, 2)), step=1) return (range_slider_x, range_slider_y, range_slider_xdate, range_slider_ydate)
def value_slider(source, plots): val_min = source.data["xmin"].min() val_max = source.data["xmax"].max() if "ci_lower" in source.column_names: val_min = min(val_min, source.data["ci_lower"].min()) if "ci_upper" in source.column_names: val_max = max(val_max, source.data["ci_upper"].max()) x_range = val_max - val_min value_column_slider = RangeSlider( start=val_min - 0.02 * x_range, end=val_max + 0.02 * x_range, value=(val_min, val_max), step=x_range / 500, title="Value", name="value_slider", ) code = """ var lower_end = cb_obj.value[0] var upper_end = cb_obj.value[1] for (var i = 0; i < plots.length; ++ i){ plots[i].x_range.start = lower_end; plots[i].x_range.end = upper_end; } """ callback = CustomJS(args={"plots": plots}, code=code) value_column_slider.js_on_change("value", callback) return value_column_slider
def initialize(self, label, start, end, step, callback_throttle, default): self.slider = RangeSlider(start=start, end=end, range=default, step=step, title=label, callback_throttle=callback_throttle) self.widget_lst.append(self.slider)
def get_slider(desc, range, default=None): if default is None: default = range slider = RangeSlider( title=desc, start=range[0], end=range[1], value=default, step=0.1) slider.on_change('value', on_filter_change) return slider
def make_plot1(df): data = ColumnDataSource( data={ "x": df["Saniye"], "y": df["ECG"], "z": df["AFIB_STATUS"], "r": df[df["Peaks"] == "R"], "q": df[df["Peaks"] == "Q"], "s": df[df["Peaks"] == "S"], "p": df[df["Peaks"] == "QRS_complex_on"], "t": df[df["Peaks"] == "QRS_complex_off"] }) hover_tool1 = HoverTool(tooltips=[("ECG Value", "@y"), ("AFIB Status", "@z"), ("Second", "@x")]) plot1 = figure(tools=[hover_tool1], x_axis_label="Second", y_axis_label="ECG Value", title="Basic ECG Analysis", plot_width=1500, plot_height=500) plot1.xaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.xgrid.grid_line_color = "LightPink" plot1.yaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.ygrid.grid_line_color = "LightPink" plot1.line(x="x", y="y", source=data) for data, name, color in zip([ data.data["r"], data.data["q"], data.data["s"], data.data["p"], data.data["t"] ], ["R", "Q", "S", "QRS_complex_on", "QRS_complex_off"], ["red", "green", "gray", "cyan", "black"]): #df = pd.DataFrame(data) plot1.circle(data["Saniye"], data["ECG"], color=color, alpha=0.8, muted_color=color, muted_alpha=0.1, legend_label=name, size=8) plot1.legend.location = "top_right" plot1.legend.click_policy = "mute" callback2 = CustomJS(args=dict(plot1=plot1), code=""" var a = cb_obj.value; plot1.x_range.start = a[0]; plot1.x_range.end = a[1]; plot1.change.emit(); cb_obj.title = "Interval is " + a[0] + " Second to " + a[1] + " Second" """) slider_widget = RangeSlider(start=df["Saniye"].min(), end=df["Saniye"].max(), step=1, value=(df["Saniye"].min(), df["Saniye"].max()), title="Select Second Interval") slider_widget.js_on_change("value_throttled", callback2) return plot1, slider_widget
def heatmap_tab(controls): # the list of control domains will be colorcoded for the heat map controls_domains=list(set((dataFrame[dataFrame['root']==True])['control_name'])) controls_domains.sort() controls_colors = Category20_16 controls_colors.sort() controls_selection = CheckboxGroup(labels=controls_domains, active = [0, 1]) range_select = RangeSlider(start = 0, end = 100, value = (80, 100), step = 10, title = 'Compliance % Range') def form_controls_dataset(controls_list, range_start = 80, range_end = 100): # Dataframe to hold information heatmap_df = pd.DataFrame(columns=['impact', 'frequency', 'control']) range_extent = range_end - range_start # Iterate through all the carriers for i, control_name in enumerate(controls_list): # Add to the overall dataframe heatmap_df = heatmap_df.append(temp_df) # Overall dataframe heatmap_df = heatmap_df.sort_values(['impact', 'frequency']) return ColumnDataSource(heatmap_df) controls_dataset = form_controls_dataset(list(controls_domains[0]), range_start = range_select.value[0], range_end = range_select.value[1]) def update(attr, old, new): controls_to_plot = [] for i in controls_selection.active: tmp_control_name=controls_selection.labels[i] tmp_control_id= new_controls_dataset = form_controls_dataset(controls_to_plot, range_start = range_select.value[0], range_end = range_select.value[1]) controls_dataset.data.update(new_controls_dataset.data) controls_selection.on_change('active', update) range_select.on_change('value', update) # return tab
def build_filter_controls(options): server_names = options['server_names'] server_select = RadioButtonGroup(labels=server_names, active=0) year_select = RangeSlider(start=options['year-start'], end=options['year-end'], value=(options['year-start'], options['year-end']), step=1) #, title="Year") month_select = MultiSelect(title="Month:", value=['0'], options=options['month']) day_select = RangeSlider(start=1, end=31, value=(1, 31), step=1) ###, title="Day") day_week_select = CheckboxButtonGroup( #title='Dia da semana', labels=options['day_week']) #, #active=[i for i in range(len(options['day_week']))]) time_select = RangeSlider(start=0, end=24, value=(0, 24), step=1, title="Period") scale_select = RadioButtonGroup(labels=querys.scale, active=0) def select_data(): print('data select') server_name = server_names[server_select.active] months = month_select.value days = day_select.value day_week = day_week_select.active years = year_select.value time = time_select.value scale = querys.scale_str[scale_select.active] db = database.db sql = build_query(server_name, scale, years, months, days, day_week, time) print(sql) # return pd.io.sql.read_sql(sql, db) return [ server_select, scale_select, year_select, month_select, day_select, day_week_select, time_select ], select_data
def _setup_selection_widgets(self): """Set selection widgets.""" self.select_all_button = cbs.select_button( data_source=self.data_source['main_source']) self.deselect_all_button = cbs.deselect_button( data_source=self.data_source['main_source']) self.pressure_slider = RangeSlider(start=0, end=100, value=(0, 100), step=0.5, title="Select with pressure range", width=300) callback = cbs.range_selection_callback( data_source=self.data_source['main_source']) self.pressure_slider.js_on_change('value', callback)
def create_range_slider(self, plane: Plane) -> RangeSlider: """ Creates a range slider to comfortable show and change a given plane's values range. Parameters ---------- plane : Plane One of the three planes of the 3D data. Returns ------- RangeSlider An instance of the Slider model for the given plane. """ range_slider = RangeSlider( start=0, end=1, value=(0, 1), step=1, title=f"{plane.name.capitalize()} View", name=f"{plane.name}_values_slider", ) return range_slider
def _get_xaxis_slider(self, plot_obj): """ Creates an "x-axis slider" that allows the user to interactively change the boundaries of the axes :param plot_obj: Bokeh plot object :return: x-axis slider """ callback = CustomJS(args={'plot': plot_obj}, code=""" var a = cb_obj.value; plot.x_range.start = a[0]; plot.x_range.end = a[1]; """) slider = RangeSlider(start=0, end=50, value=(self.df['x'].min(), self.df['x'].max()), step=1, title="x-axis range slider", width=200) slider.js_on_change('value', callback) return slider
def generate_date_range_slider(days=100): end = datetime.utcnow() start = (datetime.utcnow() - timedelta(days=days)) step = timedelta(days=1) div = Div(text="<b>Date Range: </b>{} - {}".format(start.strftime("%Y/%m/%d"), start.strftime("%Y/%m/%d"))) callback = CustomJS(args=dict(text_input=div), code=""" var f = cb_obj.range var st_dt = new Date(0); st_dt.setUTCSeconds(f[0]) var et_dt = new Date(0); et_dt.setUTCSeconds(f[1]) var start = st_dt.toISOString().slice(0,10).replace(/-/g,"/") var end = et_dt.toISOString().slice(0,10).replace(/-/g,"/") text_input.text = "<b>Date Range: </b>" + start + " - " + end """) start_num = start.timestamp() end_num = end.timestamp() step_num = step.total_seconds() range_slider = RangeSlider(start=start_num, end=end_num, range=(start_num, end_num), step=step_num, title=None, callback=callback) return div, range_slider
def _subgroup_slider(source, subgroup_col): sorted_uniques = np.array(sorted(set(source.data[subgroup_col]))) min_val, max_val = sorted_uniques[0], sorted_uniques[-1] min_dist_btw_vals = (sorted_uniques[1:] - sorted_uniques[:-1]).min() slider = RangeSlider( start=min_val - 0.05 * min_val, end=max_val + 0.05 * max_val, value=(min_val, max_val), step=min_dist_btw_vals, title=subgroup_col.title(), name="subgroup_widget", ) slider.js_on_change( "value", CustomJS(code="source.change.emit();", args={"source": source})) return slider
def RangeWidget(*args, **kw): if not 'start' in kw and 'end' in kw: kw['start'], kw['end'] = kw['value'] elif 'value' not in kw: kw['value'] = (kw['start'], kw['end']) # TODO: should use param definition of integer (when that is # itself fixed...). if isinstance(kw['start'], int) and isinstance(kw['end'], int): kw['step'] = 1 return RangeSlider(*args, **kw)
def __init__(self, number: int, name: str, gui_name: str = "", full_range: List[int] = [0, 1], step: int = 1, options: List = []): self.number = number self.name = name self.gui_name = gui_name if gui_name else name self.full_range = full_range self.step = step self.options = options self.slider = RangeSlider(title=gui_name, start=full_range[0], end=full_range[1], step=step, value=full_range) self.slider.on_change("value", self.slider_function)
class BasicFilter: number: int name: str gui_name: str full_range: List[int] step: int options: List def __init__(self, number: int, name: str, gui_name: str = "", full_range: List[int] = [0, 1], step: int = 1, options: List = []): self.number = number self.name = name self.gui_name = gui_name if gui_name else name self.full_range = full_range self.step = step self.options = options self.slider = RangeSlider(title=gui_name, start=full_range[0], end=full_range[1], step=step, value=full_range) self.slider.on_change("value", self.slider_function) def slider_function(self, attr, old, new): for opt in self.options: opt_limit = getattr(opt, self.name) if opt_limit["incompatible"]: if new[0] <= opt_limit["limit"] <= new[1]: opt_limit["incompatible"] = False opt.incompatibility_count -= 1 if opt.incompatibility_count == 0: opt.button.disabled = False else: if not (new[0] <= opt_limit["limit"] <= new[1]): opt_limit["incompatible"] = True opt.incompatibility_count += 1 opt.button.disabled = True
class range_slider(): def __init__(self, widget_lst, label, start, end, step, callback_throttle, default): self.widget_lst = widget_lst self.slider = None self.initialize(label, start, end, step, callback_throttle, default) def initialize(self, label, start, end, step, callback_throttle, default): self.slider = RangeSlider(start=start, end=end, range=default, step=step, title=label, callback_throttle=callback_throttle) self.widget_lst.append(self.slider) def add_callback(self, callback): self.slider.on_change('range', callback) def set_value(self, value): self.slider.range = value
def visualise(self): """This function visualises our whole datatset""" # output to static HTML file output_file("index.html") # Make up plot for data_type in self.data.columns[2:]: self.lines.append(self._make_line(data_type)) # Adding a selector countries = self.data.Country.drop_duplicates().to_list() select = Select(title="Displayed Country:", value=countries[0], options=countries) years = RangeSlider(start=1950, end=2018, value=(1964, 2001), step=1, title="Year range:") # show the results show(row(Tabs(tabs=self.lines), column(select, years)))
def make_sliders(gdf, values, samples): """ Description ------------ Set RangeSliders for a list of values from a (Geo)DataFrame Returns -------- Dict of Bokeh RangeSliders Parameters ----------- - gdf(GeoDataFrame o DataFrame): - GeoPandas GeoDataFrame or Pandas DataFrame - values(list): - list of values for which RangeSlider is needed - steps(int): - number of samples for steps (used to determine step, based on _set_step()) """ sliders = {} roofs_related = ["angles", "area", "min_width", "compactness"] for value in values: start = gdf[value].min() end = gdf[value].max() step = _set_step(start, end, samples) if value in roofs_related: title = value + " (Rooftop's polygon)" elif value == "total_surface": title = "total surface (ground area * nb levels)" else: title = value + " (Building)" sliders[value] = RangeSlider(start=gdf[value].min(), end=gdf[value].max(), step=step, title=title, value=(gdf[value].min(), gdf[value].max())) return sliders
from bokeh.models.layouts import Row, Column from bokeh.models.widgets import Slider, RangeSlider, DateSlider, DateRangeSlider, Div from bokeh.models.callbacks import CustomJS slider = Slider(title="Numerical", value=50, start=0, end=96, step=5) disabled_slider = Slider(title="Disabled", value=50, start=0, end=96, step=5, disabled=True) range_slider = RangeSlider(title="Numerical range", value=[30, 70], start=0, end=100, step=0.5) date_slider = DateSlider(title="Date", value=date(2014, 1, 1), start=date(2010, 1, 1), end=date(2020, 1, 1), step=1) date_range_slider = DateRangeSlider(title="Date range", value=(date(2014, 1, 1), date(2018, 12, 31)), start=date(2010, 1, 1), end=date(2020, 1, 1), step=1)
def histogram_tab(flights): # Function to make a dataset for histogram based on a list of carriers # a minimum delay, maximum delay, and histogram bin width def make_dataset(carrier_list, range_start=-60, range_end=120, bin_width=5): # Dataframe to hold information by_carrier = pd.DataFrame(columns=[ 'proportion', 'left', 'right', 'f_proportion', 'f_interval', 'name', 'color' ]) range_extent = range_end - range_start # Iterate through all the carriers for i, carrier_name in enumerate(carrier_list): # Subset to the carrier subset = flights[flights['name'] == carrier_name] # Create a histogram with 5 minute bins arr_hist, edges = np.histogram(subset['arr_delay'], bins=int(range_extent / bin_width), range=[range_start, range_end]) # Divide the counts by the total to get a proportion arr_df = pd.DataFrame({ 'proportion': arr_hist / np.sum(arr_hist), 'left': edges[:-1], 'right': edges[1:] }) # Format the proportion arr_df['f_proportion'] = [ '%0.5f' % proportion for proportion in arr_df['proportion'] ] # Format the interval arr_df['f_interval'] = [ '%d to %d minutes' % (left, right) for left, right in zip(arr_df['left'], arr_df['right']) ] # Assign the carrier for labels arr_df['name'] = carrier_name # Color each carrier differently arr_df['color'] = Category20_16[i] # Add to the overall dataframe by_carrier = by_carrier.append(arr_df) # Overall dataframe by_carrier = by_carrier.sort_values(['name', 'left']) return ColumnDataSource(by_carrier) 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' return p def make_plot(src): # Blank plot with correct labels p = figure(plot_width=700, plot_height=700, title='Histogram of Arrival Delays by Airline', x_axis_label='Delay (min)', y_axis_label='Proportion') # Quad glyphs to create a histogram p.quad(source=src, bottom=0, top='proportion', left='left', right='right', color='color', fill_alpha=0.7, hover_fill_color='color', legend='name', hover_fill_alpha=1.0, line_color='black') # Hover tool with vline mode hover = HoverTool(tooltips=[('Carrier', '@name'), ('Delay', '@f_interval'), ('Proportion', '@f_proportion')], mode='vline') p.add_tools(hover) # Styling p = style(p) return p def update(attr, old, new): carriers_to_plot = [ carrier_selection.labels[i] for i in carrier_selection.active ] new_src = make_dataset(carriers_to_plot, range_start=range_select.value[0], range_end=range_select.value[1], bin_width=binwidth_select.value) src.data.update(new_src.data) # Carriers and colors available_carriers = list(set(flights['name'])) available_carriers.sort() airline_colors = Category20_16 airline_colors.sort() carrier_selection = CheckboxGroup(labels=available_carriers, active=[0, 1]) carrier_selection.on_change('active', update) binwidth_select = Slider(start=1, end=30, step=1, value=5, title='Bin Width (min)') binwidth_select.on_change('value', update) range_select = RangeSlider(start=-60, end=180, value=(-60, 120), step=5, title='Range of Delays (min)') range_select.on_change('value', update) # Initial carriers and data source initial_carriers = [ carrier_selection.labels[i] for i in carrier_selection.active ] src = make_dataset(initial_carriers, range_start=range_select.value[0], range_end=range_select.value[1], bin_width=binwidth_select.value) p = make_plot(src) # Put controls in a single element controls = WidgetBox(carrier_selection, binwidth_select, range_select) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title='Histogram') return tab
def emergence_tab(company_data, founder_data, gis_data): company_data.loc[:, 'IncorporationDate'] = pd.to_datetime( company_data['IncorporationDate'], format='%d/%m/%Y') company_data.loc[:, 'year'] = company_data['IncorporationDate'].dt.to_period( 'Y').astype(str).astype(int) founder_data = founder_data.dropna() founder_data.loc[:, 'IncorporationDate'] = pd.to_datetime( founder_data['IncorporationDate'], format='%d/%m/%Y') founder_data.loc[:, 'year'] = founder_data['IncorporationDate'].dt.to_period( 'Y').astype(str).astype(int) founder_data.loc[:, 'age'] = founder_data['year'] - founder_data[ 'date_of_birth.year'] founder_data.loc[:, 'age'] = founder_data['age'].astype(int) ############################################## # def the function to prepare data for plots # ############################################## def make_dataset(plot_indicators, map_indicators, range_start=1980, range_end=2020, year_select=2020): # calculate the accumulated number of companies companies = company_data.copy() companies.loc[:, 'company_count'] = 1 companies = companies.loc[:, ['year', 'company_count']] companies = pd.DataFrame( companies.groupby(['year'])['company_count'].sum()) companies.loc[:, 'company_sum'] = companies['company_count'].cumsum() companies = companies.reset_index() data = companies.loc[:, ['year', 'company_sum']] # calculate the accumulated number of founders founders = founder_data.copy() founders.loc[:, 'founder_count'] = 1 founders = founders.loc[:, ['year', 'founder_count']] founders = pd.DataFrame( founders.groupby(['year'])['founder_count'].sum()) founders.loc[:, 'founder_sum'] = founders['founder_count'].cumsum() founders = founders.reset_index() data = pd.merge(data, founders, on='year') data = data.drop(columns=['founder_count'], axis=1) data = data[data['year'] >= range_start] data = data[data['year'] <= range_end] company_nodes = gis_data.copy() companies_1 = company_data.copy() companies_1 = companies_1.loc[:, ['RegAddress.PostCode', 'year']] companies_1 = companies_1[companies_1['year'] <= year_select] companies_1.loc[:, 'count'] = 1 companies_1 = pd.DataFrame( companies_1.groupby(['RegAddress.PostCode'])['count'].sum()) companies_1.loc[:, 'count'] = companies_1['count'].apply(np.log) companies_1.loc[:, 'count'] = companies_1['count'] * 30 companies_1 = companies_1.reset_index() companies_1.loc[:, 'RegAddress.PostCode'] = companies_1[ 'RegAddress.PostCode'].str.replace(' ', '') companies_1 = pd.merge(companies_1, company_nodes, left_on='RegAddress.PostCode', right_on='postcode') companies_1 = companies_1.loc[:, ['count', 'x', 'y']] founder_nodes = gis_data.copy() founder_1 = founder_data.copy() founder_1 = founder_1[founder_1['year'] <= year_select] founder_1.loc[:, 'count'] = 1 founder_1 = pd.DataFrame( founder_1.groupby(['RegAddress.PostCode'])['count'].sum()) founder_1.loc[:, 'count'] = founder_1['count'].apply(np.log) founder_1.loc[:, 'count'] = founder_1['count'] * 30 founder_1 = founder_1.reset_index() founder_1.loc[:, 'RegAddress.PostCode'] = founder_1[ 'RegAddress.PostCode'].str.replace(' ', '') founder_1 = pd.merge(founder_1, founder_nodes, left_on='RegAddress.PostCode', right_on='postcode') founder_1 = founder_1.loc[:, ['count', 'x', 'y']] if 'Num of Companies' not in plot_indicators: data.loc[:, 'company_sum'] = 'N/A' if 'Num of Founders' not in plot_indicators: data.loc[:, 'founder_sum'] = 'N/A' if map_indicators != 'Num of Companies': companies_1 = pd.DataFrame(columns=['count', 'x', 'y']) if map_indicators != 'Num of Founders': founder_1 = pd.DataFrame(columns=['count', 'x', 'y']) return (ColumnDataSource(data), ColumnDataSource(companies_1), ColumnDataSource(founder_1)) ############################# # plot the map of tech-city # ############################# def make_map(company_src, founder_src): # set the range of axises x_min = -12000 x_max = -8500 y_min = 6714000 y_max = 6716000 # define the map tiles to use tile_provider = get_provider(Vendors.CARTODBPOSITRON_RETINA) # plot the map p_map = figure(match_aspect=True, x_range=(x_min, x_max), y_range=(y_min, y_max), x_axis_type='mercator', y_axis_type='mercator', height=550) p_map.circle(x='x', y='y', color='darkslategray', source=company_src, size=10, fill_alpha=0.4, radius='count') p_map.circle(x='x', y='y', color='brown', source=founder_src, size=10, fill_alpha=0.4, radius='count') p_map.grid.visible = True # add map tiles map = p_map.add_tile(tile_provider) map.level = 'underlay' # formatting p_map.xaxis.visible = False p_map.yaxis.visible = False return p_map #################################### # define the function to plot data # #################################### def make_plot(src): p = figure(plot_width=1000, plot_height=550, x_axis_label='YEAR', y_axis_label='NUM') p.line(source=src, x='year', y='company_sum', color='darkslategray', legend_label='Num of Companies') p.line(source=src, x='year', y='founder_sum', color='brown', legend_label='Num of Founders') p.legend.location = 'top_left' hover = HoverTool(tooltips=[( 'Year', '@year'), ('Num of Companies', '@company_sum'), ('Num of Founders', '@founder_sum')]) p.add_tools(hover) return p ############################## # define the update function # ############################## def update(attr, old, new): plot_indicators = [ plot_indicator_selection.labels[i] for i in plot_indicator_selection.active ] map_indicators = map_indicator_selection.value new_src, new_company_src, new_founder_src = make_dataset( plot_indicators, map_indicators, range_start=range_select.value[0], range_end=range_select.value[1], year_select=year_select.value) src.data.update(new_src.data) company_src.data.update(new_company_src.data) founder_src.data.update(new_founder_src.data) # %% set controllers available_indicators = ['Num of Companies', 'Num of Founders'] plot_indicator_selection = CheckboxGroup(labels=available_indicators, active=[0, 1]) plot_indicator_selection.on_change('active', update) map_indicator_selection = Select(title="Choose Indicator", value='Num of Companies', options=available_indicators) map_indicator_selection.on_change('value', update) year_select = Slider(start=1980, end=2020, value=2020, step=1, title='Choose the year') year_select.on_change('value', update) range_select = RangeSlider(start=1980, end=2020, value=(1980, 2020), title='Time Period (year)') range_select.on_change('value', update) # %% initial indicators and data source initial_plot_indicators = [ plot_indicator_selection.labels[i] for i in plot_indicator_selection.active ] initial_map_indicator = map_indicator_selection.value src, company_src, founder_src = make_dataset( initial_plot_indicators, initial_map_indicator, range_start=range_select.value[0], range_end=range_select.value[1], year_select=year_select.value) p1 = make_plot(src) p2 = make_map(company_src, founder_src) # %% put controls in a single element plot_controls = WidgetBox(plot_indicator_selection, range_select) map_controls = WidgetBox(map_indicator_selection, year_select) # text description: title_1 = Div(text=''' <b>Emergence and Development of London Tech City</b> ''') description_1 = Div(text=''' <b>In 2008</b>, Tech City - also known as East London Tech City or Silicon Roundabout - came to prominence, with a variety of companies operating in the area, including Last.FM, Poke and Trampoline System. Being located in Inner East London, Tech City presents a large number of advantages for firms: a central location, cheap rents, accessibility to the rest of London and proximity to other like-minded tech companies. Moreover, Tech City offers many nightlife activaties, which is highly attractive to the type of workers and employees that digital and tech business want to retain - young, urban, creative and tech-savvy. ''') description_2 = Div(text=''' <b>In Nov 2010</b>, then UK Prime Minister made a speech to emphasize the importance of East London Tech firms in the UK Economy and set ambitious plans to further develop Tech City, promising a governmental support. The proposals involved building the profile of the area through government funding (£15 million in Government Funding) and support. Besides, Tech City Investment Organisation (TCIO) was created by the government aiming to make Tech City the leading digital hub in Europe. ''') description_3 = Div( text='<b>The Tech City strategy presented 3 clear objectives:</b>\n') description_4 = Div( text='1. Supporting the cluster of start-ups and small/midium-sized\ businesses(SMES);') description_5 = Div(text='2. Attracting large international investers;') description_6 = Div( text='3. Using this momentum to steer high-tech activity further east,\ including into a post-Games Olympic Park.') description_7 = Div(text=''' <b>In May 2011</b>, TweetDeck, a social media dashboard, was launched by Twitter and gave another boost to the already growing repulation of Tech City. ''') reference_1 = Div(text=''' <a href="https://www.mbymontcalm.co.uk/blog/history-behind-tech-city/ ">Reference 1</a> ''') reference_2 = Div(text=''' <a href="https://www.demos.co.uk/files/A_Tale_of_Tech_City_web.pdf ">Reference 2</a> ''') reference_3 = Div(text=''' <a href="https://www.gov.uk/government/speeches/east-end-tech-city-speech">Reference 3</a> ''') reference_4 = Div(text=''' <a href="https://olaonikoyi.medium.com/the-problems-at-east-london -tech-city-london-silicon-roundabout-d0bc2d4c7181">Reference 4</a> ''') title_2 = Div(text=''' <b>Data Visual</b> ''') description_8 = Div(text=''' The programme was a major success and resulted in an important multiplication of the number of tech companies operating in the region. In 2000, the number of companies in Tech City was 628. After Cameron's speech in 2011, the number of companies started increasing exponentially - indeed, the number of companies increased by 1204% between 2011 and 2020 (3,208 in 2011 vs. 41,841 in 2020). ''') # %% design the layout plot_layout = column(plot_controls, p1) map_layout = column(map_controls, p2) graph_layout = row(plot_layout, map_layout) layout = column(title_1, description_1, description_2, description_3, description_4, description_5, description_6, description_7, reference_1, reference_2, reference_3, reference_4, title_2, description_8, graph_layout) # %% make a tab with the layout tab = Panel(child=layout, title='Emergence of Tech-City') return tab
tooltips=TOOLTIPS) processed_image_fig.yaxis.axis_label = "Pixels" processed_image_fig.xaxis.axis_label = "Pixels" image_select = Select(title="Image File:", value="", options=list(RAW_FILES), min_height=50, max_width=300) img = np.random.randint(0, 2**16, (IMAGE_SIZE, IMAGE_SIZE), dtype=np.uint16).astype(np.float) raw_image_obj = raw_image_fig.image(image=[img], x=[0], y=[0], dw=[IMAGE_SIZE], dh=[IMAGE_SIZE], palette=cc.fire) processed_image_obj = processed_image_fig.image(image=[img.T], x=[0], y=[0], dw=[IMAGE_SIZE], dh=[IMAGE_SIZE], palette=cc.fire) colormap_scale_slider = RangeSlider(start=0, end=2**16, value=(0,2**16), step=1, title="Colormap Scale (nm)") blur_slider = Slider(start=1, end=255, step=2, value=3, title="Gaussian Blur Kernel Size") @gen.coroutine def update_loading_props(**kwargs): update_bokeh_props(loading_props, **kwargs) @gen.coroutine @without_document_lock def image_change_callback(attr, _, image_name): image_path = os.path.join(IMAGE_FOLDER, image_name) data, extent = load_image(image_path) # Don't use the raw nanometers for display doc.add_next_tick_callback(partial(update_bokeh_dict,
def build(self): # init widget if self.has_type == True: active = [i for i in range(len(self.labels))] labels = [ self.labels[i] + " (" + self.colors[i] + ")" for i in range(len(self.labels)) ] self.label_checkbox = CheckboxGroup(labels=labels, active=active) self.x_rangeslider = RangeSlider(value=[-100, 150], start=-100, end=150, step=1, title="x") self.y_rangeslider = RangeSlider(value=[-100, 100], start=-100, end=100, step=1, title="y") if self.has_time == True: self.time_rangeslider = DateRangeSlider( format="%Y-%b-%d %H:%M", value=[self.timeRange[0], self.timeRange[1]], start=self.timeRange[0], end=self.timeRange[1], step=10, title="time") controls = [] if self.has_type == True: controls.append(self.label_checkbox) controls.append(self.x_rangeslider) controls.append(self.y_rangeslider) if self.has_time == True: controls.append(self.time_rangeslider) widgets = widgetbox(controls, width=700, height=700) # if self.has_type == True: # widgets = widgetbox(self.label_checkbox, self.x_rangeslider, self.y_rangeslider, width=700, height=700) # controls = [self.label_checkbox, self.x_rangeslider, self.y_rangeslider] # else: # widgets = widgetbox(self.x_rangeslider, self.y_rangeslider, width=700, height=700) # controls = [self.x_rangeslider, self.y_rangeslider] for control in controls: if type(control) == CheckboxGroup: control.on_change('active', lambda attr, old, new: self.update()) else: control.on_change('value', lambda attr, old, new: self.update()) # self.source_scatter is variable which figure will display the data from self.source_scatter = ColumnDataSource(data=self.original_data) self.scatter_plot = figure(plot_width=700, plot_height=700, tools=self.tools, tooltips=self.tooltip, toolbar_location="left", title="") sp = self.scatter_plot.circle(x='x', y='y', size=20, color=self.color, source=self.source_scatter) table_attr_name = self.attr_name[:-1] st_table = selection_table(table_attr_name, sp, self.source_scatter) layout = column(row(widgets, self.scatter_plot), st_table.table) self.update() for name in self.attr_name: self.source_scatter.data[name] = pd.Series( self.source_scatter.data[name]) curdoc().add_root(layout)
def load_page(experiment_df, experiment_db): ########## bokeh plots ########## # general plot tools plot_tools = 'wheel_zoom, pan, reset, save, hover' hover = HoverTool(tooltips=[("(x,y)", "($x, $y)")]) # progress curve plots global raw_source raw_source = ColumnDataSource(data=dict(x=[], y=[], yr=[], yfit=[])) global raw raw = figure(title="Initial Rate Fit", x_axis_label="Time", y_axis_label="Signal", plot_width=350, plot_height=300, tools=plot_tools) raw.circle('x', 'y', size=2, source=raw_source, color='gray', selection_color="black", alpha=0.6, nonselection_alpha=0.2, selection_alpha=0.6) raw.line('x', 'yfit', source=raw_source, color='red') global warning_source warning_source = ColumnDataSource(data=dict( x=[0], y=[0], t=[ 'Please enter transform equation! \nMust convert signal to [substrate] \nin Schnell-Mendoza mode (e.g. via \nx/6.22/0.45/0.001 for sample data). \nNote: this transform may need \nto be inverted through multiplying \nby -1 when analyzing experiments \nthat measure increasing product \nconcentration over time)' ])) global warning warning = raw.text(x='x', y='y', text='t', text_font_size='12pt', angle=0, source=warning_source) warning.visible = False global circles_source circles_source = ColumnDataSource( data=dict(x=[-.05, -.05, 1.6, 1.6], y=[0, 0.6, 0, 0.6])) global circles circles = raw.circle(x='x', y='y', alpha=0., source=circles_source) circles.visible = False global resi resi = figure(title="Initial Rate Fit Residuals", x_axis_label="Time", y_axis_label="Residual", plot_width=700, plot_height=200, tools='wheel_zoom,pan,reset') resi.yaxis.formatter = BasicTickFormatter(precision=2, use_scientific=True) resi.circle('x', 'yr', size=5, source=raw_source, color='grey', alpha=0.6) # model plot for titration experiments global model_data_source model_data_source = ColumnDataSource( data=dict(xt=[], yt=[], n=[], ct=[], et=[])) global model_plot_source model_plot_source = ColumnDataSource( data=dict(xp=[], yp=[], l=[], u=[], cp=[], ep=[])) global model_fit_source model_fit_source = ColumnDataSource(data=dict(x=[], y=[])) global varea_source varea_source = ColumnDataSource(data=dict(x=[], r1=[], r2=[])) global model model = figure(title='Model Fit', x_axis_label='Concentration', y_axis_label='Rate', plot_width=350, plot_height=300, tools=plot_tools) model.circle('xp', 'yp', size=8, source=model_plot_source, color='cp', alpha=0.6) model.add_layout( Whisker(source=model_plot_source, base='xp', upper='u', lower='l')) model.line('x', 'y', source=model_fit_source, line_width=3, color='black', alpha=0.8) model.varea('x', 'r1', 'r2', source=varea_source, color='grey', alpha=0.3) ########## bokeh widgets ########## # button for selecting progress curve fitting routine global fit_button fit_button = RadioButtonGroup(labels=[ 'Maximize Slope Magnitude', 'Linear Fit', 'Logarithmic Fit', 'Schnell-Mendoza' ], active=0, width=375) fit_button.on_change('active', widget_callback) # button for selecting progress curve fitting routine global scalex_box scalex_box = CheckboxButtonGroup( labels=["transform x-axis to Log10 scale"], active=[]) scalex_box.on_change('active', widget_callback) # dropdown menu for selecting titration experiment model global model_select model_select = Select( title='Choose Model', value='Michaelis-Menten', options=['Michaelis-Menten', 'pEC50/pIC50', 'High-Throughput Screen'], width=350) model_select.on_change('value', widget_callback) # dropdown menu for selecting blank sample to subtract from remaining titration samples global subtract_select subtract_select = Select(title='Select Blank Sample for Subtraction', value='', options=list(experiment_df)[1:] + [''], width=350) subtract_select.on_change('value', widget_callback) # dropdown menu for selecting titration sample to plot in current view global sample_select sample_select = Select(title='Y Axis Sample', value=list(experiment_df)[-1], options=list(experiment_df)[1:], width=350) sample_select.on_change('value', sample_callback) # text input box for transforming slopes to rates global transform_input transform_input = TextInput(value='', title="Enter Transform Equation", width=350) transform_input.on_change('value', widget_callback) # text input box for setting delay time in logarithmic progress curve fitting global offset_input offset_input = TextInput(value='', title="Enter Time Between Mixing and First Read", width=350) offset_input.on_change('value', widget_callback) # text input boxes for fixing EC/IC50 parameters global bottom_fix bottom_fix = TextInput(value='', title="Fix pIC50/pEC50 Bottom") bottom_fix.on_change('value', widget_callback) global top_fix top_fix = TextInput(value='', title="Fix pIC50/pEC50 Top") top_fix.on_change('value', widget_callback) global slope_fix slope_fix = TextInput(value='', title="Fix pIC50/pEC50 Hill Slope") slope_fix.on_change('value', widget_callback) # text input boxes for progress curve xrange selection global start_time start_time = TextInput(value=str( experiment_df[list(experiment_df)[0]].values[0]), title="Enter Start Time") global end_time end_time = TextInput(value=str( experiment_df[list(experiment_df)[0]].values[-1]), title='Enter End Time') start_time.on_change('value', xbox_callback) end_time.on_change('value', xbox_callback) # range slider to select threshold for hit detection in HTS mode global threshold_slider threshold_slider = Slider(start=0, end=5, value=2, step=0.1, title='HTS Hit Threshold (Standard Deviation)', width=350) threshold_slider.on_change('value', threshold_callback) # range slider to update plots according to progress cuve xrange selection xmin = experiment_df[experiment_df.columns[0]].values[0] xmax = experiment_df[experiment_df.columns[0]].values[-1] global range_slider range_slider = RangeSlider( start=xmin, end=xmax, value=(xmin, xmax), step=experiment_df[experiment_df.columns[0]].values[1] - xmin, title='Fine Tune X-Axis Range', width=650) range_slider.on_change('value', slider_callback) # button to upload local data file global file_source file_source = ColumnDataSource(data=dict(file_contents=[], file_name=[])) file_source.on_change('data', file_callback) try: output_filename = file_source.data['file_name'] + '-out.csv' except: output_filename = 'output.csv' global upload_button upload_button = Button(label="Upload Local File", button_type="success", width=350) upload_button.callback = CustomJS(args=dict(file_source=file_source), code=open( join(dirname(__file__), "upload.js")).read()) # table containing rate fits and errors template = """ <div style="background:<%=ct%>"; color="white";> <%= value %></div> """ formatter = HTMLTemplateFormatter(template=template) columns = [ TableColumn(field='n', title='Sample'), TableColumn(field='yt', title='Slope (Initial Rate)', formatter=formatter), TableColumn(field='et', title='Std. Error') ] global rate_table rate_table = DataTable(source=model_data_source, columns=columns, width=350, height=250, selectable=True, editable=True) # tables containing model fits and errors global mm_source mm_source = ColumnDataSource(dict(label=[], Km=[], Vmax=[])) columns = [ TableColumn(field='label', title=''), TableColumn(field='Vmax', title='Vmax'), TableColumn(field='Km', title='Km') ] global mm_table mm_table = DataTable(source=mm_source, columns=columns, width=350, height=75, selectable=True, editable=True) global ic_source ic_source = ColumnDataSource( dict(label=[], Bottom=[], Top=[], Slope=[], p50=[])) columns = [ TableColumn(field='label', title=''), TableColumn(field='Bottom', title='Bottom'), TableColumn(field='Top', title='Top'), TableColumn(field='Slope', title='Slope'), TableColumn(field='p50', title='pEC/IC50') ] global ic_table ic_table = DataTable(source=ic_source, columns=columns, width=350, height=75, selectable=True, editable=True) # button for copying rate data table to clipboard global copy_button copy_button = Button(label="Copy Table to Clipboard", button_type="primary", width=350) copy_button.callback = CustomJS(args=dict(source=model_data_source), code=open( join(dirname(__file__), "copy.js")).read()) # button for downloading rate data table to local csv file global download_button download_button = Button(label="Download Table to CSV", button_type="primary", width=350) download_button.callback = CustomJS(args=dict(source=model_data_source, file_name=output_filename), code=open( join(dirname(__file__), "download.js")).read()) ########## document formatting ######### desc = Div(text=open(join(dirname(__file__), "description.html")).read(), width=1400) advanced = Div( text="""<strong>Advanced Settings for \npEC/IC50 Analysis</strong>""") widgets = widgetbox(model_select, sample_select, subtract_select, transform_input, offset_input, advanced, scalex_box, bottom_fix, top_fix, slope_fix) table = widgetbox(rate_table) main_row = row( column(upload_button, widgets), column(fit_button, row(raw, model), resi, row(start_time, end_time), range_slider), column(download_button, copy_button, table, mm_table, ic_table, threshold_slider)) sizing_mode = 'scale_width' l = layout([[desc], [main_row]], sizing_mode=sizing_mode) update() curdoc().clear() curdoc().add_root(l) curdoc().title = "ICEKAT"
src.data.update(new_src.data) # CheckboxGroup to select carrier to display carrier_selection = CheckboxGroup(labels=available_carriers, active = [0, 1]) carrier_selection.on_change('active', update) # Slider to select width of bin binwidth_select = Slider(start = 1, end = 30, step = 1, value = 5, title = 'Delay Width (min)') binwidth_select.on_change('value', update) # RangeSlider control to select start and end of plotted delays range_select = RangeSlider(start = -60, end = 180, value = (-60, 120), step = 5, title = 'Delay Range (min)') range_select.on_change('value', update) # Find the initially selected carrieres initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] src = make_dataset(initial_carriers, range_start = range_select.value[0], range_end = range_select.value[1], bin_width = binwidth_select.value) p = make_plot(src) # Put controls in a single element controls = WidgetBox(carrier_selection, binwidth_select, range_select)
def density_handler(doc: Document) -> None: """ Handler function for the density application. """ task_id = doc.session_context.request.arguments.get('task_id') username = doc.session_context.request.arguments.get('username') user_dir = os.path.join(settings.USER_DATA, username) path_to_db = os.path.join(user_dir, task_id) try: conn = os.path.join(path_to_db, task_id + '.csv') df = pd.read_csv(conn) proteins = list(df.Protein.unique()) lipids = list(df.Lipids.unique()) except: proteins, lipids = [], [] for o in os.listdir(path_to_db): key = o.split('/')[-1] if key.endswith('.npy'): if key.startswith('prot_'): proteins.append('Protein(s)') else: lipid = key.split('_')[0] lipids.append(lipid) all_mpl_cmaps = [ 'viridis', 'plasma', 'inferno', 'cividis', 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'RdYlBu', 'RdYlGn', 'Spectral', 'Spectral_r', 'coolwarm', 'coolwarm_r', 'seismic', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn', 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', ] #TODO: globals declaration should not be necessary anymore. global prot_xyz prot_xyz = np.load(os.path.join(path_to_db, "prot_" + task_id + '.npy')) global l_xyz global x_min, x_max, y_min, y_max, z_min, z_max l_xyz = np.load( os.path.join(path_to_db, lipids[0] + "_" + task_id + '.npy')) x_min, x_max = l_xyz[:, 0].min(), l_xyz[:, 0].max() y_min, y_max = l_xyz[:, 1].min(), l_xyz[:, 1].max() z_min, z_max = l_xyz[:, 2].min(), l_xyz[:, 2].max() # widgets color_map = Select(title="Colormap", value="viridis", options=all_mpl_cmaps, width=120) lipid = Select(title="Lipids", value=lipids[0], options=lipids, width=100) denstype = Select(title="Density Type", value="All Proteins", options=["All Proteins", "Average"], width=120) number = Slider(title="Number of Bins", value=380, start=80, end=500, step=10, width=200) protein = Select(title="Show Protein", value="No", options=["Yes", "No"], width=90) gpcr = Select(title="Protein", value=proteins[0], options=proteins, width=130) zrange = RangeSlider(start=z_min, end=z_max, value=(z_min, z_max), step=0.2, title="Z-Axis Range", callback_policy='mouseup', width=352) cbar_range = Slider(value=256, start=0, end=256, step=1, height=600, orientation='vertical', callback_policy='mouseup', margin=(15, 0), tooltips=False, show_value=False) # colorschemes colormap = cm.get_cmap(color_map.value) bokehpalette = [ mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N)) ] def lipid_density(array, bins=160): """Given a 2D array, containing the x, y values of a lipid, return its histogram with edges.""" x = array[:, 0] y = array[:, 1] lipid, e1, e2 = np.histogram2d(x, y, density=True, bins=bins) return lipid, e1, e2 # Plot histogram image H, xe, ye = lipid_density(l_xyz, number.value) minx = np.abs(xe.min()) miny = np.abs(ye.min()) p1 = figure(plot_height=640, plot_width=640, tools='') image_source = ColumnDataSource(data=dict(image=[])) img = p1.image(image="image", x=xe[0], y=ye[0], dw=xe[-1] + minx, dh=ye[-1] + miny, palette=bokehpalette, source=image_source) circle_prot_source = ColumnDataSource( data=dict(x1=prot_xyz[:, 0], y1=prot_xyz[:, 1])) p1.circle(x="x1", y="y1", source=circle_prot_source, size=2, fill_alpha=0.2) cb_palette = LinearColorMapper(palette=bokehpalette, low=H.min(), high=H.max()) color_bar = ColorBar(color_mapper=cb_palette, width=8, location=(0, 0), label_standoff=10) color_bar.formatter = BasicTickFormatter(use_scientific=False) p1.add_layout(color_bar, 'right') # Make graph pretty p1.xgrid.grid_line_color = None p1.ygrid.grid_line_color = None p1.xaxis.major_tick_line_color = None p1.xaxis.minor_tick_line_color = None p1.yaxis.major_tick_line_color = None p1.yaxis.minor_tick_line_color = None p1.xaxis.major_label_text_font_size = '0pt' p1.yaxis.major_label_text_font_size = '0pt' p1.grid.visible = False p1.toolbar.logo = None p1.toolbar_location = None def update_all(cond=False, cmap=False): """ Update the image showing all proteins. """ if cond: # For efficiency execute only if GPCR structure changes global l_xyz global x_min, x_max, y_min, y_max, z_min, z_max l_xyz = np.load( os.path.join(path_to_db, str(lipid.value) + "_" + task_id + '.npy')) x_min, x_max = l_xyz[:, 0].min(), l_xyz[:, 0].max() y_min, y_max = l_xyz[:, 1].min(), l_xyz[:, 1].max() z_min, z_max = l_xyz[:, 2].min(), l_xyz[:, 2].max() zrange.start = z_min zrange.end = z_max index = np.where((l_xyz[:, 2] > zrange.value[0]) & (l_xyz[:, 2] < zrange.value[1])) l_xyz_new = l_xyz[index] else: l_xyz_new = l_xyz if cmap: # For efficiency execute only if image colormap changes cb_cut_value = 256 - cbar_range.value cmap = color_map.value colormap = cm.get_cmap(cmap) bokehpalette = [ mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N)) ] bp_i = 0 while bp_i < len(bokehpalette[:cb_cut_value]): bokehpalette[bp_i] = '#ffffff' bp_i += 1 img.glyph.color_mapper.palette = bokehpalette color_bar.color_mapper.palette = bokehpalette # Update histogram image H, xe, ye = lipid_density(l_xyz_new, number.value) minx = np.abs(xe.min()) miny = np.abs(ye.min()) img.glyph.dw = xe[-1] + minx img.glyph.dh = ye[-1] + miny # update image source image_source.data = dict(image=[H]) def update_protein(cond=False): """ Update the protein representation. """ if cond: # For efficiency execute only if GPCR structure changes global prot_xyz if protein.value == "Yes": circle_prot_source.data = dict(x1=prot_xyz[:, 0], y1=prot_xyz[:, 1]) elif protein.value == "No": circle_prot_source.data = dict(x1=[], y1=[]) def update_cbar(): cb_cut_value = 256 - cbar_range.value cmap = color_map.value colormap = cm.get_cmap(cmap) bokehpalette = [ mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N)) ] bp_i = 0 while bp_i < len(bokehpalette[:cb_cut_value]): bokehpalette[bp_i] = '#ffffff' bp_i += 1 img.glyph.color_mapper.palette = bokehpalette color_bar.color_mapper.palette = bokehpalette # event listeners controls = [lipid, zrange, gpcr] for control in controls: control.on_change('value', lambda attr, old, new: update_denstype(cond=True)) number.on_change('value', lambda attr, old, new: update_denstype()) color_map.on_change('value', lambda attr, old, new: update_denstype(cmap=True)) protein.on_change('value', lambda attr, old, new: update_protein()) denstype.on_change('value', lambda attr, old, new: update_denstype()) cbar_range.on_change('value', lambda attr, old, new: update_cbar()) # deal with what gets updated and what not. def update_denstype(cond=False, cmap=False): update_all(cond, cmap) update_protein(cond) update_denstype() input1 = row([gpcr, lipid, color_map, protein]) input2 = row([p1, cbar_range]) input3 = row([number, zrange]) input3 = column([input1, input2, input3]) l = layout([input3]) doc.add_root(l) doc.title = "Density App"
def initialize(self, widget_lst): self.slider = RangeSlider(start = self.start, end = self.end, value = self.default, step = self.step, title = self.label) widget_lst.append(self.slider) if self.callback is not None: self.slider.on_change('value', self.callback)
def density_tab(flights): # Dataset for density plot based on carriers, range of delays, # and bandwidth for density estimation def make_dataset(carrier_list, range_start, range_end, bandwidth): xs = [] ys = [] colors = [] labels = [] for i, carrier in enumerate(carrier_list): subset = flights[flights['name'] == carrier] subset = subset[subset['arr_delay'].between(range_start, range_end)] kde = gaussian_kde(subset['arr_delay'], bw_method=bandwidth) # Evenly space x values x = np.linspace(range_start, range_end, 100) # Evaluate pdf at every value of x y = kde.pdf(x) # Append the values to plot xs.append(list(x)) ys.append(list(y)) # Append the colors and label colors.append(airline_colors[i]) labels.append(carrier) new_src = ColumnDataSource(data={'x': xs, 'y': ys, 'color': colors, 'label': labels}) return new_src def make_plot(src): p = figure(plot_width = 700, plot_height = 700, title = 'Density Plot of Arrival Delays by Airline', x_axis_label = 'Delay (min)', y_axis_label = 'Density') p.multi_line('x', 'y', color = 'color', legend = 'label', line_width = 3, source = src) # Hover tool with next line policy hover = HoverTool(tooltips=[('Carrier', '@label'), ('Delay', '$x'), ('Density', '$y')], line_policy = 'next') # Add the hover tool and styling p.add_tools(hover) p = style(p) return p def update(attr, old, new): # List of carriers to plot carriers_to_plot = [carrier_selection.labels[i] for i in carrier_selection.active] # If no bandwidth is selected, use the default value if bandwidth_choose.active == []: bandwidth = None # If the bandwidth select is activated, use the specified bandwith else: bandwidth = bandwidth_select.value new_src = make_dataset(carriers_to_plot, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth) src.data.update(new_src.data) 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' return p # Carriers and colors available_carriers = list(set(flights['name'])) available_carriers.sort() airline_colors = Category20_16 airline_colors.sort() # Carriers to plot carrier_selection = CheckboxGroup(labels=available_carriers, active = [0, 1]) carrier_selection.on_change('active', update) range_select = RangeSlider(start = -60, end = 180, value = (-60, 120), step = 5, title = 'Range of Delays (min)') range_select.on_change('value', update) # Initial carriers and data source initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] # Bandwidth of kernel bandwidth_select = Slider(start = 0.1, end = 5, step = 0.1, value = 0.5, title = 'Bandwidth for Density Plot') bandwidth_select.on_change('value', update) # Whether to set the bandwidth or have it done automatically bandwidth_choose = CheckboxButtonGroup( labels=['Choose Bandwidth (Else Auto)'], active = []) bandwidth_choose.on_change('active', update) # Make the density data source src = make_dataset(initial_carriers, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth_select.value) # Make the density plot p = make_plot(src) # Add style to the plot p = style(p) # Put controls in a single element controls = WidgetBox(carrier_selection, range_select, bandwidth_select, bandwidth_choose) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title = 'Density Plot') return tab
def histogram_tab(flights): # Function to make a dataset for histogram based on a list of carriers # a minimum delay, maximum delay, and histogram bin width def make_dataset(carrier_list, range_start = -60, range_end = 120, bin_width = 5): # Dataframe to hold information by_carrier = pd.DataFrame(columns=['proportion', 'left', 'right', 'f_proportion', 'f_interval', 'name', 'color']) range_extent = range_end - range_start # Iterate through all the carriers for i, carrier_name in enumerate(carrier_list): # Subset to the carrier subset = flights[flights['name'] == carrier_name] # Create a histogram with 5 minute bins arr_hist, edges = np.histogram(subset['arr_delay'], bins = int(range_extent / bin_width), range = [range_start, range_end]) # Divide the counts by the total to get a proportion arr_df = pd.DataFrame({'proportion': arr_hist / np.sum(arr_hist), 'left': edges[:-1], 'right': edges[1:] }) # Format the proportion arr_df['f_proportion'] = ['%0.5f' % proportion for proportion in arr_df['proportion']] # Format the interval arr_df['f_interval'] = ['%d to %d minutes' % (left, right) for left, right in zip(arr_df['left'], arr_df['right'])] # Assign the carrier for labels arr_df['name'] = carrier_name # Color each carrier differently arr_df['color'] = Category20_16[i] # Add to the overall dataframe by_carrier = by_carrier.append(arr_df) # Overall dataframe by_carrier = by_carrier.sort_values(['name', 'left']) return ColumnDataSource(by_carrier) 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' return p def make_plot(src): # Blank plot with correct labels p = figure(plot_width = 700, plot_height = 700, title = 'Histogram of Arrival Delays by Airline', x_axis_label = 'Delay (min)', y_axis_label = 'Proportion') # Quad glyphs to create a histogram p.quad(source = src, bottom = 0, top = 'proportion', left = 'left', right = 'right', color = 'color', fill_alpha = 0.7, hover_fill_color = 'color', legend = 'name', hover_fill_alpha = 1.0, line_color = 'black') # Hover tool with vline mode hover = HoverTool(tooltips=[('Carrier', '@name'), ('Delay', '@f_interval'), ('Proportion', '@f_proportion')], mode='vline') p.add_tools(hover) # Styling p = style(p) return p def update(attr, old, new): carriers_to_plot = [carrier_selection.labels[i] for i in carrier_selection.active] new_src = make_dataset(carriers_to_plot, range_start = range_select.value[0], range_end = range_select.value[1], bin_width = binwidth_select.value) src.data.update(new_src.data) # Carriers and colors available_carriers = list(set(flights['name'])) available_carriers.sort() airline_colors = Category20_16 airline_colors.sort() carrier_selection = CheckboxGroup(labels=available_carriers, active = [0, 1]) carrier_selection.on_change('active', update) binwidth_select = Slider(start = 1, end = 30, step = 1, value = 5, title = 'Bin Width (min)') binwidth_select.on_change('value', update) range_select = RangeSlider(start = -60, end = 180, value = (-60, 120), step = 5, title = 'Range of Delays (min)') range_select.on_change('value', update) # Initial carriers and data source initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] src = make_dataset(initial_carriers, range_start = range_select.value[0], range_end = range_select.value[1], bin_width = binwidth_select.value) p = make_plot(src) # Put controls in a single element controls = WidgetBox(carrier_selection, binwidth_select, range_select) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title = 'Histogram') return tab
from bokeh.models.widgets import RangeSlider, Button, DataTable, TableColumn, NumberFormatter from bokeh.io import curdoc df = pd.read_csv(join(dirname(__file__), 'salary_data.csv')) source = ColumnDataSource(data=dict()) def update(): current = df[(df['salary'] >= slider.value[0]) & (df['salary'] <= slider.value[1])].dropna() source.data = { 'name' : current.name, 'salary' : current.salary, 'years_experience' : current.years_experience, } slider = RangeSlider(title="Max Salary", start=10000, end=110000, value=(10000, 50000), step=1000, format="0,0") slider.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="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) controls = widgetbox(slider, button)
from bokeh.plotting import figure from bokeh.sampledata.us_marriages_divorces import data df=data.copy() source = ColumnDataSource(data=dict(year=df.Year, population=df.Population,marriagep1000=df.Marriages_per_1000,divorcep1000=df.Divorces_per_1000)) plot_figure = figure(title='Range Slider',plot_height=450, plot_width=600, tools="save,reset", toolbar_location="below") plot_figure.scatter('divorcep1000', 'marriagep1000', size=5, source=source) plot_figure.xaxis.axis_label='Divorces Per 1000' plot_figure.yaxis.axis_label='Marriages Per 1000' range_slider = RangeSlider(start=1867, end=2011, value=(1867,2011), step=1, title="Filter Year") def slider_change(attr,old,new): slider_value=range_slider.value ##Getting slider value slider_low_range=slider_value[0] slider_high_range=slider_value[1] filtered_df=df[(df['Year'] >= slider_low_range) & (df['Year']<=slider_high_range)] source.data=dict(year=filtered_df.Year, population=filtered_df.Population, marriagep1000=filtered_df.Marriages_per_1000,divorcep1000=filtered_df.Divorces_per_1000) range_slider.on_change('value',slider_change) layout=row(range_slider, plot_figure)
if today.month < september_month: default_yr = str(today.year - 1) else: default_yr = str(today.year) league_obj, num_teams, week_num, owners, owners_list, team_objs, weeks, owner_to_idx = retrieve_lg_info( int(lg_id_input.value), default_yr) team1_dd = Dropdown(label='Team 1 - Select', menu=owners_list) team2_dd = Dropdown(label='Team 2 - Select', menu=owners_list) comp_button = Button(label='Compare', button_type='danger') week_slider = RangeSlider(title='Weeks', start=1, end=week_num, value=(1, week_num), step=1) year_input = TextInput(value=str(default_yr), title='Season:') plot1 = initialize_sc_figure(league_obj, week_num) plot2 = initialize_ew_figure(league_obj, week_num) plot1_wrap = column(children=[plot1]) plot2_wrap = column(children=[plot2]) line_colors = get_line_colors(num_teams) sc_sources = get_sc_sources(weeks, team_objs, owners, week_num, num_teams) # will use to avoid re-computation of data after comparisons
data={ 'x': df_slice[x], 'y': df_slice[y], 'color': df_slice['plot_color'], 'alpha': df_slice['plot_alpha'], 'size': df_slice['plot_size'], 'text': df_slice['comment_text'].str[0:75] + '...', 'flags': df_slice['all_flags'], 'single_flag': df_slice['single_flag'], 'sim_age': df_slice['sim_age'] }).data slider = RangeSlider(start=0, end=30, value=(0, 30), step=1, title='Simulated Age') slider.on_change('value', callback) buttons = CheckboxButtonGroup(labels=buttonlabels, active=[0, 1, 2, 3, 4, 5, 6]) buttons.on_change('active', callback) select = Select(title='Vectorization', value='Bag of Words', options=['Bag of Words', 'Doc2Vec']) select.on_change('value', callback) tooltips = [('Comment', '@text'), ('Flags', '@flags'), ('Age (d)', '@sim_age')]
def age_hist_tab(df_selected=None): def make_dataset(age_group_list, range_start=0.076070, range_end=0.271264, bin_width=0.00001): by_age_group = pd.DataFrame(columns=[ 'proportion', 'left', 'right', 'f_proportion', 'f_interval', 'name', 'color' ]) range_extent = range_end - range_start # Iterate through all the carriers for i, age_group in enumerate(age_group_list): # Subset to the carrier subset = df_selected[df_selected['age_range'] == age_group] # Create a histogram with 5 minute bins arr_hist, edges = np.histogram(subset['meanfun'], bins=int(range_extent / bin_width), range=[range_start, range_end]) # Divide the counts by the total to get a proportion arr_df = pd.DataFrame({ 'proportion': arr_hist / np.sum(arr_hist), 'left': edges[:-1], 'right': edges[1:] }) # Format the proportion arr_df['f_proportion'] = [ '%0.5f' % proportion for proportion in arr_df['proportion'] ] # Format the interval arr_df['f_interval'] = [ '%0.5f to %0.5f KHz' % (left, right) for left, right in zip(arr_df['left'], arr_df['right']) ] # Assign the carrier for labels arr_df['name'] = age_group # Color each carrier differently arr_df['color'] = Category20_16[i] # Add to the overall dataframe by_age_group = by_age_group.append(arr_df) # Overall dataframe by_age_group = by_age_group.sort_values(['name', 'left']) return ColumnDataSource(by_age_group) 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' return p def make_plot(src): # Blank plot with correct labels p = figure( plot_width=700, plot_height=700, title='Histogram of Age Range and Mean Fundamental Frequeny', x_axis_label='Mean fundamental frequency (KHz)', y_axis_label='Proportion') # Quad glyphs to create a histogram p.quad(source=src, bottom=0, top='proportion', left='left', right='right', color='color', fill_alpha=0.7, hover_fill_color='color', legend='name', hover_fill_alpha=1.0, line_color='black') # Hover tool with vline mode hover = HoverTool(tooltips=[('Age Group', '@name'), ('Meanfund frequency', '@f_interval'), ('Proportion', '@f_proportion')], mode='vline') p.add_tools(hover) # Styling p = style(p) return p def update(attr, old, new): age_group_to_plot = [ age_group_selection.labels[i] for i in age_group_selection.active ] new_src = make_dataset(age_group_to_plot, range_start=range_select.value[0], range_end=range_select.value[1], bin_width=binwidth_select.value) src.data.update(new_src.data) # This is the option on the side available_age_groups = list(df_selected['age_range'].unique()) age_group_selection = CheckboxGroup(labels=available_age_groups, active=[0, 1]) # What happens when you select it age_group_selection.on_change('active', update) # The slider on the side binwidth_select = Slider(start=0.001, end=0.01, step=0.001, value=0.001, title='Frequency Width (KHz)') #Something is updated binwidth_select.on_change('value', update) #The slider and the ranges for that one range_select = RangeSlider(start=0.076070, end=0.271264, value=(0.076070, 0.271264), step=0.01, title='Meanfun Frequency (KHz)') # Same here range_select.on_change('value', update) initial_age_grop = [ age_group_selection.labels[i] for i in age_group_selection.active ] src = make_dataset(initial_age_grop, range_start=range_select.value[0], range_end=range_select.value[1], bin_width=binwidth_select.value) p = make_plot(src) # Put controls in a single element controls = WidgetBox(age_group_selection, binwidth_select, range_select) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title='Age Group Histogram') return tab