def buildVendorsTab(): defaultGfxVendors = [ gfxVendors.index('NVIDIA Corporation'), gfxVendors.index('Advanced Micro Devices, Inc. [AMD/ATI]'), gfxVendors.index('Intel Corporation') ] gfxVendorCheckbox = CheckboxGroup(labels=gfxVendors, active=defaultGfxVendors) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title="GFX Vendors", x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): vendors = [gfxVendors[i] for i in range(len(gfxVendors)) if i in selected] releaseUsers = 100 * getUsersForVendors('release', vendors) / gfxTotalReleaseUsers betaUsers = 100 * getUsersForVendors('beta', vendors) / gfxTotalBetaUsers fig.x_range.factors = vendors fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in vendors], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in vendors], y=betaUsers / 2, height=betaUsers, ) gfxVendorCheckbox.on_click(update) update(gfxVendorCheckbox.active) vendorComparison = HBox(HBox(VBoxForm(*[gfxVendorCheckbox]), width=300), fig, width=1100) return Panel(child=vendorComparison, title="GFX Vendor Comparison")
def buildOSesTab(): osesCheckbox = CheckboxGroup(labels=oses, active=[i for i in range(len(oses))]) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title='OS', x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): cur_oses = [oses[i] for i in range(len(oses)) if i in selected] releaseUsers = 100 * getUsersForOses('release', cur_oses) / osTotalReleaseUsers betaUsers = 100 * getUsersForOses('beta', cur_oses) / osTotalBetaUsers fig.x_range.factors = cur_oses fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in cur_oses], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in cur_oses], y=betaUsers / 2, height=betaUsers, ) osesCheckbox.on_click(update) update(osesCheckbox.active) osesComparison = HBox(HBox(VBoxForm(*[osesCheckbox]), width=300), fig, width=1100) return Panel(child=osesComparison, title="OS Comparison")
def make_inputs(self): with open("states.csv") as f: states = [line.strip().split(',') for line in f.readlines()] self.selectr = Select( name='states', value='Choose A State', options=[s[1] for s in states] + ['Choose A State'], ) labels = ["County Averages", "Hotels"] self.check_group = CheckboxGroup(labels=labels, active=[0,1], inline=True) ##Filler plot x_range = Range1d(0, 300) y_range = Range1d(0, 12) self.filler = Plot( x_range=x_range, y_range=y_range, title="", plot_width=300, plot_height=12, min_border=0, **PLOT_FORMATS ) x_range = Range1d(0, 300) y_range = Range1d(0, 18) self.filler2 = Plot( x_range=x_range, y_range=y_range, title="", plot_width=300, plot_height=14, min_border=0, **PLOT_FORMATS )
def make_inputs(self): with open("states.csv") as f: states = [line.strip().split(',') for line in f.readlines()] self.selectr = Select( name='states', value='Choose A State', options=[s[1] for s in states] + ['Choose A State'] ) labels = ["County Averages", "Hotels"] self.check_group = CheckboxGroup(labels=labels, active=[0,1])
def make_inputs(self): columns = [ TableColumn(field='x', title='x'), TableColumn(field='y', title='y'), TableColumn(field='device', title='device'), TableColumn(field='platform', title='platform') ] # obj.data_display0 = DataTable(source=obj.source2, columns=columns) # obj.data_display1 = DataTable(source=obj.source3, columns=columns) # setup user input self.x_axis_options = Select(title="X:", value='size', options=axis_options) self.y_axis_options = Select(title="Y:", value='throughput [1/sec]', options=axis_options) self.benchmarks = Select(title="Benchmark:", value=benchmark_names[0], options=benchmark_names) self.device_names = CheckboxGroup(labels=device_names, active=[0]) self.platform_names = CheckboxButtonGroup(labels=platform_names, active=[0])
def recommender_tab_advanced(recommender): def make_div_list(textlist, max_lines, fmt_str="""%s""", **attribs): """create a list of divs containing text to display""" divs = [] for i in range(max_lines): if len(textlist) > i: divs.append(Div(text=fmt_str % (textlist[i]), **attribs)) else: divs.append(Div(text=fmt_str % (' '), **attribs)) return divs def make_rec_list(titles, max_lines): """create a recommendation list of games, with a thumbnail, game title, info and Amazon buy links""" global games_by_title fmt_str1 = """ <div class="rec-post-container"> <div class="rec-post-thumb"><img src="%s" /></div> <div class="rec-post-content"> <h3 class="rec-post-title">%s<br> <a href="%s" target="_blank">Info</a><span> </span> <a href="%s" target="_blank">Buy on Amazon</a> </h3> </div> </div>""" fmt_str2 = """""" divs = [] for i in range(max_lines): # there is a title available for this list slot if len(titles) > i: divs.append( Div(text=fmt_str1 % (games_by_title['pic_url'].loc[titles[i]], titles[i], 'https://boardgamegeek.com/boardgame/' + str(games_by_title['id'].loc[titles[i]]), 'https://www.amazon.com/s?k=' + titles[i].replace(' ', '+') + '&i=toys-and-games'))) # no title, so fill with blank else: divs.append(Div(text=fmt_str2)) return divs # update the 'liked games' list UI elements def update_liked_list(titlelist): global max_liked ctl_liked_games.children = make_div_list(titlelist, max_liked, fmt_str=liked_list_fmt, render_as_text=False) # update the 'recommended games' list UI elements def update_recommended_list(titlelist): global n_recommendations ctl_recommended_games.children = make_rec_list(titlelist, n_recommendations) # called when a control widget is changed def update_filters(attr, old, new): global category_includes, mechanics_includes global category_excludes, mechanics_excludes category_includes = [ ctl_category_selection1.labels[i] for i in ctl_category_selection1.active ] category_includes += [ ctl_category_selection2.labels[i] for i in ctl_category_selection2.active ] mechanics_includes = [ ctl_mechanics_selection1.labels[i] for i in ctl_mechanics_selection1.active ] mechanics_includes += [ ctl_mechanics_selection2.labels[i] for i in ctl_mechanics_selection2.active ] # NOTE: this will need to be changed if I ever implement exclude selections! if ctl_include_expansions.active: category_excludes = [] else: category_excludes = ['Expansion for Base-game'] # called when a control widget is changed def update_preflist(attr, old, new): global liked_games liked_games.append(ctl_game_entry.value) liked_games = list(filter(None, set(liked_games))) # get control values update_liked_list(liked_games) ctl_game_entry.value = '' # reset preferred games list def reset_preferred_games(): global liked_games liked_games = [] update_liked_list(liked_games) # recommend some games def recommend_games(): global liked_games, recommended_games global games_all, n_recommendations, title_list global category_includes, mechanics_includes # get game IDs for titles liked_ids = recommender.get_item_title_id(liked_games) # select games to search from based on filters: recommended_games = recommender.recommend_items_by_pref_list( liked_ids, num2rec=n_recommendations, weightrange=ctl_game_weight.value, minrating=ctl_game_min_rating.value, categories_include=category_includes, categories_exclude=category_excludes, mechanics_include=mechanics_includes, mechanics_exclude=mechanics_excludes) # show the recommended games update_recommended_list(recommended_games) # NOTE: I'm using globals because I'm running into variable scope # problems with the bokeh handlers. Easiest to declare globals global liked_games, recommended_games, games_all global n_recommendations, max_liked, title_list, title_list_lower global category_includes, mechanics_includes global category_excludes, mechanics_excludes global games_by_title # layout params n_recommendations = 10 max_liked = 8 num_check_options = 20 # Format to use for liked list. # This needs to be changed to work like rec list liked_list_fmt = """<div style="font-size : 14pt; line-height:14pt;">%s</div>""" # variables used by the tab games_all = recommender.item_data # use all games for search liked_games = [] recommended_games = [] weight_range = [1, 5] category_includes = [] mechanics_includes = [] category_excludes = [] mechanics_excludes = [] # list of all game titles title_list = games_all['name'] title_list_lower = [s.lower() for s in title_list] games_by_title = recommender.item_data.set_index('name') # preferred game entry text control ctl_game_entry = AutocompleteInput(completions=list(title_list) + list(title_list_lower), min_characters=1, title='Enter some game names you like:') ctl_game_entry.on_change('value', update_preflist) # reset liked game list button ctl_reset_prefs = Button(label='Reset game list', width_policy='min', align='end') ctl_reset_prefs.on_click(reset_preferred_games) # liked list title ctl_liked_list_title = Div( text= """<div style="font-size : 18pt; line-height:16pt;">Games you like:</div>""" ) # liked game entries ctl_liked_games = WidgetBox( children=make_div_list(liked_games, max_liked, fmt_str=liked_list_fmt)) # recommended list title ctl_recommended_list_title = Div( text= """<div style="font-size : 18pt; line-height:16pt;">Games we recommend:</div>""" ) # recommended games list widget ctl_recommended_games = WidgetBox( children=make_rec_list(recommended_games, n_recommendations)) # Recommend games button ctl_recommend = Button(label='Recommend some games!', width_policy='min', align='center') ctl_recommend.on_click(recommend_games) # game weight slider ctl_game_weight = RangeSlider( start=1, end=5, value=(1, 5), step=.1, title='Game weight range', width_policy='min', ) ctl_game_weight.on_change('value', update_filters) # min game rating slider ctl_game_min_rating = Slider(start=1, end=10, value=7, step=.1, title='Minimum average rating', width_policy='min') ctl_game_min_rating.on_change('value', update_filters) # collect all category and mechanics labels from recommender data categories, mechanics = recommender.get_categories_and_mechanics() # game category selection category_list = ['Any category'] + list(categories['tag'].values) ctl_category_selection1 = CheckboxGroup( labels=category_list[:int(num_check_options / 2)], width_policy='min', active=[0]) ctl_category_selection1.on_change('active', update_filters) ctl_category_selection2 = CheckboxGroup( labels=category_list[int(num_check_options / 2):num_check_options], width_policy='min') ctl_category_selection2.on_change('active', update_filters) # game mechanism checkbox group mechanics_list = ['Any mechanism'] + list(mechanics['tag'].values) ctl_mechanics_selection1 = CheckboxGroup( labels=mechanics_list[:int(num_check_options / 2)], width_policy='min', active=[0]) ctl_mechanics_selection1.on_change('active', update_filters) ctl_mechanics_selection2 = CheckboxGroup( labels=mechanics_list[int(num_check_options / 2):num_check_options], width_policy='min') ctl_mechanics_selection2.on_change('active', update_filters) # select whether to include expansions ctl_include_expansions = CheckboxGroup(labels=['Include game expansions'], width_policy='min') ctl_include_expansions.on_change('active', update_filters) # controls to select preferred games pref_controls = WidgetBox( ctl_liked_list_title, ctl_liked_games, Spacer(min_height=20), ctl_game_entry, ctl_reset_prefs, Spacer(min_height=5), ) ctl_liked_list_title = Div( text= """<div style="font-size : 18pt; line-height:16pt;">Game Categories:</div>""" ) filter_controls = WidgetBox( row(ctl_game_weight, Spacer(min_width=50), ctl_game_min_rating), row(ctl_include_expansions), column( row( Div(text= """<div style="font-size : 18pt; line-height:16pt;">Game Categories:</div>""" ), Spacer(min_width=50), ctl_recommend), row(ctl_category_selection1, ctl_category_selection2), Spacer(min_height=5), Div(text= """<div style="font-size : 18pt; line-height:16pt;">Game Mechanics:</div>""" ), row(ctl_mechanics_selection1, ctl_mechanics_selection2), )) # recommendation results results_controls = WidgetBox( ctl_recommended_list_title, ctl_recommended_games, Spacer(min_height=10), ) # Create a row layout layout = row(column(pref_controls, filter_controls), Spacer(min_width=50), results_controls) # Make a tab with the layout tab = Panel(child=layout, title='Advanced Game Recommender') return tab
toggle = Toggle(label="Toggle button", type="success") toggle.on_click(toggle_handler) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_value="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(radio_group_handler) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(radio_button_group_handler) vbox = VBox(children=[ button, toggle, dropdown, split, checkbox_group, radio_group,
step=1) usb_min_ = Slider(title="Minimum number of USB ports", value=0, start=0, end=3, step=1) hd_ = Select(title="Type of HD", options=sorted(hd_map.keys()), value="All") tv_3d_ = Select(title="3D TV", options=sorted(yes_no_map.keys()), value="No") x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value="Length of the diagonal") y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="Price") # Create Checkbox controls checkbox_group = CheckboxGroup( labels=["Samsung", "LG", "Philips", "Thomson", "Sony"], active=[], width=120) ######################################################################################################### # Define functions ######################################################################################################### # Updata data if something change def get_data(): hd_e = hd_map[hd_.value] full_h_e = hd_map[hd_.value] tv_3d_e = yes_no_map[tv_3d_.value] # Filter sliders selected_tv = tv_data[(tv_data.Price >= min_price_.value)
def h_t_tab(self): """Plots the humidity and temperature""" self.h_t_fig = figure(plot_width=int(self.page_width*0.9), plot_height=self.page_height, title="Temperature and humidity", toolbar_location="above", x_axis_type="datetime") self.h_t_fig.xaxis.axis_label = "Timestamp" self.h_t_fig.yaxis.axis_label = "Temperature (C)" # Ranges need to be defined here - causes update issues if this # doesn't happen here self.h_t_fig.y_range = Range1d(start=0, end=100) self.h_t_fig.extra_y_ranges = {'humidity': Range1d(start=0, end=100)} self.h_t_fig.add_layout(LinearAxis(y_range_name='humidity', axis_label="Relative humidity (%)"), 'right') # Add the lines self.h_t_line = 2*[None] # Plot the humidity/pressure self.h_t_line[0] = self.h_t_fig.line(x='Timestamp', y='Temperature (C)', source=self.source, color="blue", legend="Temperature", line_width=2) self.h_t_line[1] = self.h_t_fig.line(x="Timestamp", y="Relative humidity (%)", source=self.source, y_range_name="humidity", color="green", legend="Humidity", line_width=2) # Update the data and the plot ranges self.h_t_update() # Checkboxes to show lines resp_b = [0, 1] h_t_check_head = Div(text="Responses") h_t_check = CheckboxGroup(labels=["Temperature", "Humidity"], active=resp_b, name="Lines") h_t_check.on_click(self.h_t_lines_changed) # Lay out the page w = widgetbox(h_t_check_head, h_t_check, width=int(self.page_width*0.1)) l = row(w, self.h_t_fig) return Panel(child=l, title="Temperature and humidity")
def create_tab(data, name): def make_dataset(metric_fun, metric_sentiment, month_start, month_end, editorial, category, social_network, product): """Constrói os datasets para cada tipo de gráfico utilizado no dashboard Parâmetros ---------- data : DataFrame Pandas DataFrame expandido com dados do Sprinklr metric_fun : FUN Função para calcular métrica específica selecionada no widget metric_sentiment : str Sentimento relacionado à métrica escolhida (Positividade: positivo, Gradiente: negativo, Crise: negativo, Saúde do post: positivo) [restante] : str Valaores selecionados nas opções de filtros nos widgets Retorna ------- dict Dicionário com três chaves, correspondentes aos três gráficos apresentados. Cada chave é relacionada ao nome o gráfico e os valores são datasets no formato column data source """ month_start = pd.Timestamp(month_start) month_end = pd.Timestamp(month_end) # Filtragem dos dados com base nas seleções dos widgets filters = { 'Editoria': editorial, 'Categoria': category, 'SocialNetwork': social_network, 'Produto': product } filtered_data = filter_data(data, filters) # Gera datasets para cada gráfico ts_data = metric_fun(filtered_data) ts_data = ts_data[(ts_data.time >= month_start) & (ts_data.time <= month_end)] donut_data = filtered_data[(filtered_data.Month >= month_start) & (filtered_data.Month <= month_end)] donut_data = percent(donut_data) donut_data['angle'] = donut_data['value'] / sum( donut_data['value']) * 2 * pi donut_data['color'] = Category20c[donut_data.shape[0]] avg_donut_data = percent_avg(filtered_data) avg_donut_data = avg_donut_data[avg_donut_data.Month == month_end][[ 'Sentimento', 'MAVG' ]] avg_donut_data.columns = ['label', 'value'] avg_donut_data['angle'] = avg_donut_data['value'] / sum( avg_donut_data['value']) * 2 * pi avg_donut_data['color'] = Category20c[avg_donut_data.shape[0]] top_data = filter_sentiment(filtered_data, metric_sentiment) top_data = top_data[(top_data.Month >= month_start) & (top_data.Month <= month_end)] top_data = brand_health_txengages(top_data) avg_top_data = round(top_data.score.mean(), 2) top_data = top_data.sort_values('score', ascending=False).iloc[:10] top_data = top_data.sort_values('score') top_data['recorte'] = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ] # Converte dataframes em column data source datasets = { 'ts': ColumnDataSource(ts_data), 'donut': ColumnDataSource(donut_data), 'avg_donut': ColumnDataSource(avg_donut_data), 'top': ColumnDataSource(top_data), 'avg_top': avg_top_data } return datasets def update(attr, old, new): """Constrói os datasets para cada tipo de gráfico utilizado no dashboard Parâmetros ---------- old : ColumnDataSource Dataframe antigo relacionado aos filtros antigos new : ColumnDataSource Dataframe novo, com linhas filtradas de acordo com seleções mais recentes """ month_start = month_select.value_as_date[0] month_end = month_select.value_as_date[1] editorial = editorial_select.value category = category_select.value product = product_select.value social_network = [ social_network_select.labels[i] for i in social_network_select.active ] metric = metric_select.value metric_attr = get_metric_attr(metric) metric_fun = metric_attr['fun'] metric_sentiment = metric_attr['sentiment'] new_src = make_dataset(metric_fun=metric_fun, metric_sentiment=metric_sentiment, month_start=month_start, month_end=month_end, editorial=editorial, category=category, social_network=social_network, product=product) src['ts'].data.update(new_src['ts'].data) src['top'].data.update(new_src['top'].data) src['avg_top'] = new_src['avg_top'] src['donut'].data.update(new_src['donut'].data) src['avg_donut'].data.update(new_src['avg_donut'].data) networks = data.SocialNetwork.unique().tolist() editorials = get_multselect_options(data, 'Editoria') categories = get_multselect_options(data, 'Categoria') products = get_multselect_options(data, 'Produto') month_select = DateRangeSlider(start=date(2019, 1, 1), end=date(2019, 8, 1), value=(date(2019, 1, 1), date(2019, 8, 1)), step=1, format="%b %Y") metric_select = Select(value="gradiente", options=[("velocity", "Parâmetro de Crise"), ("positivity", "Grau de Positividade"), ("gradiente", "Grau de Negatividade"), ("brand_health", "Saúde da Marca"), ("post_health", "Saúde do Post")]) product_select = MultiSelect(value=['Todos'], options=products) category_select = MultiSelect(value=['Todos'], options=categories) editorial_select = MultiSelect(value=['Todos'], options=editorials) social_network_select = CheckboxGroup(labels=networks, active=list(range(len(networks)))) metric_select.on_change('value', update) month_select.on_change('value', update) editorial_select.on_change('value', update) category_select.on_change('value', update) product_select.on_change('value', update) social_network_select.on_change('active', update) initial_metric_attr = get_metric_attr(metric_select.value) metric_sentiment = initial_metric_attr['sentiment'] initial_networks = [ social_network_select.labels[i] for i in social_network_select.active ] src = make_dataset(metric_fun=initial_metric_attr['fun'], metric_sentiment=metric_sentiment, month_start=month_select.value_as_date[0], month_end=month_select.value_as_date[1], editorial=editorial_select.value, category=category_select.value, social_network=initial_networks, product=product_select.value) p_ts = make_plot_ts(src['ts'], 'Evolução', metric_sentiment) p_top = make_dotplot(src['top']) avg_top = src['avg_top'] avg_top = create_div_title(f'Escore Médio: {avg_top}') p_donut = make_plot_donut(src['donut'], 'Percentual') p_avg_donut = make_plot_donut(src['avg_donut'], 'Norma Percentual') metric_title = create_div_title('MÉTRICA') month_title = create_div_title('PERÍODO') network_title = create_div_title('REDE SOCIAL') category_title = create_div_title('CATEGORIA') editorial_title = create_div_title('EDITORIA') product_title = create_div_title('PRODUTO') controls = WidgetBox( column(metric_title, metric_select, Div(height=5), month_title, month_select, Div(height=5), editorial_title, editorial_select, Div(height=5), category_title, category_select, Div(height=5), product_title, product_select, Div(height=5), network_title, social_network_select, width=250)) plots = column(p_ts, Div(height=20), row(p_donut, p_avg_donut)) layout = row(controls, Div(width=50), plots) layout = column(Div(text="", height=5), layout, Div(width=20), avg_top, p_top) tab = Panel(child=layout, title=name) 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
class HotelApp(VBox): extra_generated_classes = [["HotelApp", "HotelApp", "VBox"]] jsmodel = "VBox" # input selectr = Instance(Select) #check_group = Instance(RadioGroup) check_group = Instance(CheckboxGroup) # plots plot = Instance(GMapPlot) bar_plot = Instance(Plot) # data source source = Instance(ColumnDataSource) county_source = Instance(ColumnDataSource) # layout boxes mainrow = Instance(HBox) #bottomrow = Instance(HBox) statsbox = Instance(VBox) totalbox = Instance(VBox) # inputs #ticker1_select = Instance(Select) #ticker2_select = Instance(Select) #input_box = Instance(VBoxForm) def make_inputs(self): with open("states.csv") as f: states = [line.strip().split(',') for line in f.readlines()] self.selectr = Select( name='states', value='Choose A State', options=[s[1] for s in states] + ['Choose A State'] ) labels = ["County Averages", "Hotels"] self.check_group = CheckboxGroup(labels=labels, active=[0,1]) def make_outputs(self): pass #self.pretext = Paragraph(text="", width=800) def __init__(self, *args, **kwargs): super(HotelApp, self).__init__(*args, **kwargs) self._show_counties = True self._show_hotels = True @classmethod def create(cls): """ This function is called once, and is responsible for creating all objects (plots, datasources, etc) """ # create layout widgets obj = cls() obj.mainrow = HBox() #obj.bottomrow = HBox() obj.statsbox = VBox() obj.totalbox = VBox() labels = ["County Average Ratings", "Hotel Locations"] obj.make_inputs() obj.make_outputs() # outputs #obj.pretext = Paragraph(text="", width=500) obj.make_source() obj.make_county_source() lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() #obj.make_plots(lat, lng, zoom, xr, yr) obj.make_plots() # layout obj.set_children() return obj @property def selected_df(self): pandas_df = self.df selected = self.source.selected print "seeing if selected!" if selected: idxs = selected['1d']['indices'] pandas_df = pandas_df.iloc[idxs, :] else: pandas_df = pandas_df.iloc[0:0, :] return pandas_df def make_source(self): self.source = ColumnDataSource(data=self.df) self.source.callback = Callback(args=dict(), code=""" var inds = cb_obj.get('selected')['1d'].indices; var theidx = inds[0]; console.log("yep"); console.log(theidx); $.get( "reviews", {id: theidx}, function( response ) { $( "#section2" ).html( response ); }, "html"); console.log("done"); """) def update_source(self): if self.selectr.value is None or self.selectr.value == 'Choose A State': df = hdata else: df = hdata[hdata['state'] == self.selectr.value] for col in df: self.source.data[col] = df[col] def make_county_source(self): self.county_source = ColumnDataSource(data=self.countydf) def update_county_source(self): if self.selectr.value is None or self.selectr.value == 'Choose A State': df = county_data else: df = county_data[county_data['state'] == self.selectr.value] for col in df: self.county_source.data[col] = df[col] """def init_check_group(self): print "initing radio group" self.check_group.on_click(self.check_group_handler) def check_group_handler(self, active): print "radio group handler %s" % active""" def make_plots(self): self.create_map_plot() self.populate_glyphs() self.make_bar_plot() #def make_plots(self): def create_map_plot(self): lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() x_range = xr y_range = yr #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6) map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom) #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "Hotel Review Explorer", plot_width=680, plot_height=600 ) plot.map_options.map_type="hybrid" xaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') #pan = PanTool() #wheel_zoom = WheelZoomTool() #box_select = BoxSelectTool() #box_select.renderers = [rndr] #tooltips = "@name" #tooltips = "<span class='tooltip-text'>@names</span>\n<br>" #tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>" #hover = HoverTool(tooltips="@num_reviews") #hover = HoverTool(tooltips="@names") #hover = HoverTool(tooltips=tooltips) #tap = TapTool() #plot.add_tools(pan, wheel_zoom, box_select, hover, tap) #plot.add_tools(hover, tap) #overlay = BoxSelectionOverlay(tool=box_select) #plot.add_layout(overlay) #plot.add_glyph(self.source, circle) #county_xs, county_ys = get_some_counties() #apatch = Patch(x=county_xs, y=county_ys, fill_color=['white']*len(county_xs)) #plot.add_glyph(apatch) self.plot = plot def populate_glyphs(self): self.plot.renderers=[] self.plot.tools=[] if self._show_counties: print "showing you the counties" #datasource = ColumnDataSource(county_data) #apatch = Patches(xs=county_xs, ys=county_ys, fill_color='white') #apatch = Patches(xs='xs', ys='ys', fill_color='colors', fill_alpha="alpha") apatch = Patches(xs='xs', ys='ys', fill_color='thecolors', fill_alpha='alpha') self.plot.add_glyph(self.county_source, apatch, name='counties') if self._show_hotels: print "showing you the hotels" circle2 = Circle(x="lon", y="lat", size=10, fill_color="fill2", fill_alpha=1.0, line_alpha=0.0) circle = Circle(x="lon", y="lat", size=10, fill_color="fill", fill_alpha=1.0, line_color="black") #print "source is ", self.source['lon'], self.source['lat'], self.source['f1ll'] self.plot.add_glyph(self.source, circle, nonselection_glyph=circle2, name='hotels') #county_xs, county_ys = get_some_counties() rndr = self.plot.renderers[-1] pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() box_select.renderers = [rndr] tooltips = "@name" tooltips = "<span class='tooltip-text'>@names</span>\n<br>" tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>" hover = HoverTool(tooltips=tooltips, names=['hotels']) tap = TapTool(names=['hotels']) self.plot.add_tools(pan, wheel_zoom, box_select, hover, tap) overlay = BoxSelectionOverlay(tool=box_select) self.plot.add_layout(overlay) def make_bar_plot(self): # create a new plot x_rr = Range1d(start=0.0, end=6.0) y_rr = Range1d(start=0.0, end=10.0) TOOLS = "box_select,lasso_select" bar_plot = figure(tools=TOOLS, width=400, height=350, x_range=x_rr, y_range=y_rr, title="Average Rating") #x's and y's based on selected_df sdf = self.selected_df[['names', 'ratings']] xvals = [1.0*i + 0.5 for i in range(0, len(sdf['names']))] rightvals = [1.0*i + 0.85 for i in range(0, len(sdf['names']))] ratings = [r for r in sdf['ratings']] bottoms = [0]*len(ratings) y_text = [y + 1.0 for y in ratings] all_names = [n for n in sdf['names']] print "all_names ", all_names #bar_plot.circle(xvals, ratings, size=12) bar_plot.quad(xvals, rightvals, ratings, bottoms, fill="teal") #glyph = Text(x=xvals, y=y_text, text=sdf['names'], angle=pi/4, #text_align="left", text_baseline="middle") glyphs = [Text(x=x, y=y, text=[n], angle=pi/4, text_align="left", text_baseline="middle") for x, y, n in zip(xvals, y_text, all_names)] for g in glyphs: bar_plot.add_glyph(g) bar_plot.xaxis.major_tick_line_color = None bar_plot.xaxis.minor_tick_line_color = None #bar_plot.xaxis.major_tick_line_width = 3 #bar_plot.xaxis.minor_tick_line_color = "orange" bar_plot.yaxis.minor_tick_line_color = None bar_plot.xgrid.grid_line_color = None bar_plot.ygrid.grid_line_color = None self.bar_plot = bar_plot def set_children(self): self.children = [self.totalbox] self.totalbox.children = [self.mainrow] self.mainrow.children = [self.statsbox, self.plot] self.statsbox.children = [self.selectr, self.check_group, self.bar_plot] #self.bottomrow.children = [self.pretext] def setup_events(self): super(HotelApp, self).setup_events() if self.source: self.source.on_change('selected', self, 'selection_change') if self.selectr: self.selectr.on_change('value', self, 'input_change') if self.check_group: self.check_group.on_change('active', self, 'check_change') @property def df(self): thedf = return_hotel_data() if self.selectr.value is None or self.selectr.value == 'Choose A State': return thedf else: newdf = thedf[thedf['state'] == self.selectr.value] return newdf @property def countydf(self): thedf = county_data if self.selectr.value is None or self.selectr.value == 'Choose A State': return thedf else: newdf = thedf[thedf['state'] == self.selectr.value] return newdf def selection_change(self, obj, attrname, old, new): #self.make_source() self.update_source() self.make_bar_plot() self.set_children() curdoc().add(self) def check_change(self, obj, attrname, old, new): #Turn on/off the counties/hotel data print "what the heck ", obj, attrname, old, new if 0 in new: self._show_counties = True else: self._show_counties = False if 1 in new: self._show_hotels = True else: self._show_hotels = False self.populate_glyphs() self.set_children() curdoc().add(self) def input_change(self, obj, attrname, old, new): self.make_source() self.make_county_source() print "source len: ", len(self.source.data['state']) print "county len: ", len(self.county_source.data['names']) if self.selectr.value is None or self.selectr.value == 'Choose A State': pass else: self.plot.title = self.selectr.value self.populate_glyphs() self.set_children() curdoc().add(self)
#trackerThread = classtracker.ClassTracker().start_periodic_snapshots() interfaceContainer = InterfaceContainer() dataDict = interfaceContainer.update() dataSource.data = dataDict palette = viridis(len(dataDict)) for i, (key, value) in enumerate(dataDict.items()): if key != 'time': p.line(x='time', y=key, source=dataSource, color=palette[i]) print(key) #p.legend.location= "bottom_center" #p.legend.click_policy = "mute" #p.legend.orientation="horizontal" interfaceSelection = CheckboxGroup( labels=interfaceContainer.getInterfaces(), active=[i for i in range(len(interfaceContainer.getInterfaces()))]) statSelection = CheckboxGroup( labels=list(interfaceContainer.stats.keys()), active=[i for i in range(len(interfaceContainer.getInterfaces()))]) def update_selected(wttr, old, new): a_val = autocomp.value print(a_val) #start_in_background(tracker=trackerThread) autocomp = AutocompleteInput( completions=['test2', 'test3', 'hello', 'goodbye']) autocomp.on_change('value', update_selected)
menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown.on_click(lambda value: print('dropdown: %s' % value)) dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())")) dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", menu=menu) dropdown_disabled.on_click(lambda value: print('dropdown_disabled: %s' % value)) dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())")) #dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default") #dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value)) #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value)) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(lambda value: print('radio_group: %s' % value)) radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(lambda value: print('checkbox_button_group: %s' % value)) checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())")) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(lambda value: print('radio_button_group: %s' % value)) radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())"))
return p # Update the plot based on selections def update(attr, old, new): selected_years = [seasons.labels[i] for i in seasons.active] # print(select_1.value,select_2.value) new_src = make_dataset(selected_years, select_1.value, select_2.value) src[1].data.update(new_src[1].data) # print(new_src[0][0]) seasons = CheckboxGroup(labels=list(set(df['season'])), active=[0, 1]) seasons.on_change('active', update) select_1 = Select(title="Team1:", value="Chelsea", options=list(set(df['team']))) select_1.on_change('value', update) select_2 = Select(title="Team2:", value="Manchester United", options=list(set(df['team']))) select_2.on_change('value', update) # Find the initially selected carrieres #initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] src = make_dataset([seasons.labels[i] for i in seasons.active], select_1.value,
tds2 = t2.data_source # In[34]: #widgets stats = Paragraph(text='', width=250) stats2 = Paragraph(text='', width=250) menu = [('onoffmatrix_7', 'onoffmatrix_7'), ('onoffmatrix_8', 'onoffmatrix_8'), ('odmatrix_7', 'odmatrix_7'), ('odmatrix_8', 'odmatrix_8')] select = Dropdown(label="Выберите матрицу: ", menu = menu) button1 = RadioButtonGroup(labels=['Нарисовать кружочки','Посмотреть корреспонденции']) slider1 = RangeSlider(start=0, end=1000, value=(50,200), step=50, title="Диапазон корреспонденций") slider2 = RangeSlider(start=0, end=1000, value=(50,200), step=50, title="Диапазон корреспонденций") checkbox_group = CheckboxGroup(labels=okrugs_names, active=[]) def update(attrname, old, new): sl = select.value print(sl) ok = checkbox_group.active df = pd.DataFrame(data = eval(sl)) print(df.columns.values) df1 = pd.merge(df, supers_okrugs, how = 'inner', left_on = ['super_site_from'], right_on = ['super_site']) df1 = df1[df1['id'].isin(ok)] df2 = pd.merge(df, supers_okrugs, how = 'inner', left_on = ['super_site_to'], right_on = ['super_site']) df2 = df2[df2['id'].isin(ok)]
top='rank_diff', width=0.5, source=source, fill_color=Viridis10[6]) p3.y_range.start = -40 p3.y_range.end = 0 hover = HoverTool(tooltips=[("Score@2006", "@score_x"), ('Score@2019', '@score_y')]) p3.add_tools(hover) bar_layout = column(p2, p3) #show(layout) #menu = Select(options=['Top Seven','Bottom Seven'], value='Top Seven',title='Select Type') country_selection = CheckboxGroup(labels=sorted( list(country_rank_df.country_name.unique())), active=[0]) def get_all_price_dataset(country_rank_df, names): df = dict() df['year'] = [] df['score'] = [] df['color'] = [] df['country'] = [] for ind, country in enumerate(names): df['year'].append(country_rank_df[( country_rank_df.country_name == country)].year.tolist()) df['score'].append(country_rank_df[( country_rank_df.country_name == country)].score.tolist()) df['color'].append(RdYlBu7[ind])
def create_module(user): # start controller controller = Controller(user) # module # Section 1 title1 = Div(text='Selección del Universo Objetivo', css_classes=['mtt_title']) menu1 = Select(title="Delegación:", value="TODOS", name='menu1', options=["TODOS"], width=200, css_classes=['mtt_menu1']) menu2 = Select(title="Unicom:", value='TODOS', name='menu2', options=['TODOS'], width=200, css_classes=['mtt_menu2']) menu3 = Select(title="Municipio:", value="TODOS", name='menu3', options=["TODOS"], width=200, css_classes=['mtt_menu3']) menu4 = Select(title="Corregimiento:", value="TODOS", name='menu4', options=["TODOS"], width=200, css_classes=['mtt_menu4']) menu5 = Select(title="Tipología:", value="TODOS", name='menu5', options=["TODOS"], width=200, css_classes=['mtt_menu5']) # Section 2 title2 = Div(text='Criterios de Optimización', css_classes=['mtt_title']) fig1 = figure(plot_width=600, plot_height=300, css_classes=['mtt_fig1'], tools='pan,box_zoom,reset', name='fig1', title='Cantidad de Clientes x día de Lectura') fig1.toolbar.logo = None fig1.toolbar_location = 'above' fig1.vbar(x=[1, 2, 3], width=0.5, bottom=0, top=[1.2, 2.5, 3.7], color="darkcyan", fill_alpha=0.6, line_color='black', name='vbar1') fig1.line(x=[0, 1], y=[0, 1], line_color="red", line_width=2, alpha=0.8, legend='Promedio', name='line1.2') fig1.legend.click_policy = "hide" fig1.legend.location = "top_left" fig1.legend.background_fill_color = "white" fig1.legend.background_fill_alpha = 0.5 fig1.legend.label_text_color = "#505050" fig1.legend.orientation = "vertical" fig1.xaxis.axis_label = 'Día de Lectura' fig1.add_tools(create_hover(1)) fig1.yaxis[0].formatter = NumeralTickFormatter(format="0.0a") fig2 = figure(plot_width=600, plot_height=300, css_classes=['mtt_fig2'], tools='pan,box_zoom,reset', name='fig2', title='Cantidad de Itinerarios x día de Lectura') fig2.toolbar.logo = None fig2.toolbar_location = 'above' fig2.vbar(x=[1, 2, 3], width=0.5, bottom=0, top=[1.2, 2.5, 3.7], color="darkcyan", fill_alpha=0.6, line_color='black', name='vbar2') fig2.line(x=[0, 1], y=[0, 1], line_color="red", line_width=2, alpha=0.8, legend='Promedio', name='line2.2') fig2.legend.click_policy = "hide" fig2.legend.location = "top_left" fig2.legend.background_fill_color = "white" fig2.legend.background_fill_alpha = 0.5 fig2.legend.label_text_color = "#505050" fig2.legend.orientation = "vertical" fig2.xaxis.axis_label = 'Día de Lectura' fig2.add_tools(create_hover(1)) fig2.yaxis[0].formatter = NumeralTickFormatter(format="0.0a") map_options = GMapOptions(lat=10.032663, lng=-74.042470, map_type="roadmap", zoom=7) fig3 = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options, plot_width=600, plot_height=450, css_classes=['mtt_fig3'], name='fig3') fig3.toolbar.logo = None fig3.toolbar_location = 'above' fig3.add_tools(PanTool(), WheelZoomTool()) fig3.title.text = 'Dispersión Geográfica de Itinerarios' fig3.api_key = 'AIzaSyATl81v4Wnm4udDvlNTcgw4oWMzWJndkfQ' x = np.linspace(-2, 2, 10) source = ColumnDataSource(data=dict( lat=x, lon=x**2, sizes=np.linspace(10, 20, 10), colors=controller.day_colors[0:10], )) circle = Circle(x="lon", y="lat", size='sizes', fill_color='colors', fill_alpha=0.6, line_color='black') fig3.add_glyph(source, circle, name='circles1') fig3.add_tools(create_hover(2)) fig4 = figure(plot_width=600, plot_height=300, css_classes=['mtt_fig4'], tools='pan,box_zoom,reset', name='fig2', title='Distancia Media entre Itinerarios (Km)') fig4.toolbar.logo = None fig4.toolbar_location = 'above' fig4.vbar(x=[1, 2, 3], width=0.5, bottom=0, top=[1.2, 2.5, 3.7], color="darkcyan", fill_alpha=0.6, line_color='black', name='vbar4') fig4.legend.click_policy = "hide" fig4.legend.location = "top_left" fig4.legend.background_fill_color = "white" fig4.legend.background_fill_alpha = 0.5 fig4.legend.label_text_color = "#505050" fig4.legend.orientation = "vertical" fig4.xaxis.axis_label = 'Día de Lectura' fig4.add_tools(create_hover(1)) fig4.yaxis[0].formatter = NumeralTickFormatter(format="0.0a") menu6 = Select(title="Error (%):", value='3', name='menu6', options=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], css_classes=['mtt_menu6']) text2 = Div(text='<b>Criterios de Optimización (w)</b>', css_classes=['mtt_text2']) menu7 = Select(title="Clientes:", value='20', name='menu7', options=[ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100' ], css_classes=['mtt_menu7']) menu8 = Select(title="Día:", value='40', name='menu8', options=[ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100' ], css_classes=['mtt_menu8']) menu9 = Select(title="Dispersión:", value='10', name='menu9', options=[ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100' ], css_classes=['mtt_menu9']) widget1 = layout([[text2], [menu7, menu8, menu9, menu6]]) checkbox1 = CheckboxGroup(labels=['Simular Paso a Paso'], active=[], name='checkbox1', css_classes=['mtt_checkbox1']) button1 = Button(label='Optimizar', button_type="primary", css_classes=['mtt_button1']) button1.on_click(controller.optim_days) widget2 = layout([[checkbox1, button1]]) text3 = Div(text='Resultados: ', css_classes=['mtt_text3']) widget3 = layout([ [widget1], [widget2], ]) widget4 = layout([[fig4], [widget3, text3]]) fig5 = figure(plot_width=800, plot_height=300, css_classes=['mtt_fig5'], tools='pan,box_zoom,reset', name='fig5', title='Movimiento de Itinerarios') fig5.toolbar.logo = None fig5.toolbar_location = 'above' fig5.vbar(x=[-3, -2, -1, 0, 1, 2, 3], width=0.5, bottom=0, top=[0, 0, 0, 0, 0, 0, 0], color="darkred", fill_alpha=0.6, line_color='black', name='vbar5') fig5.legend.click_policy = "hide" fig5.legend.location = "top_left" fig5.legend.background_fill_color = "white" fig5.legend.background_fill_alpha = 0.5 fig5.legend.label_text_color = "#505050" fig5.legend.orientation = "vertical" fig5.xaxis.axis_label = 'Días' fig5.add_tools(create_hover(1)) fig5.yaxis[0].formatter = NumeralTickFormatter(format="0.0a") # Section 3 title3 = Div(text='Generación de Agenda', css_classes=['mtt_title3']) button2 = Button(label='Ver Impactos', button_type="primary", css_classes=['mtt_button2']) text1 = Div(text='<p>Seleccionar Año:</p>', css_classes=['mtt_text1']) opts = [str(controller.now.year), str(controller.now.year + 1)] rbutton1 = RadioButtonGroup(labels=opts, active=0, name='rbutton1', css_classes=['mtt_rbutton1']) button3 = Button(label='Exportar', button_type="success", css_classes=['mtt_button3']) # dashboard dashboard = layout([ [title1], [menu1, menu2, menu3, menu4, menu5], [title2], [fig1, fig2], [fig3, widget4], [fig5], [Spacer(height=10)], [title3], [text1, rbutton1, button2, button3], ], sizing_mode='fixed') dashboard.name = 'mantenimiento' # ini module data curdoc().add_root(dashboard) menu1.on_change('value', controller.on_change_menus) menu2.on_change('value', controller.on_change_menus) menu3.on_change('value', controller.on_change_menus) menu4.on_change('value', controller.on_change_menus) menu5.on_change('value', controller.on_change_menus) controller.on_change_menus(None, None, None)
xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [ [ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt ] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all) play_all_sox_button = Button(label='Play sox', button_type='success', width=60) play_all_sox_button.on_click(play_all_sox) audio_first_checkbox = CheckboxGroup(labels=['audio first'], active=[0]) audio_first_checkbox.on_click(audio_first_selected) fsel.on_change('value', file_selected) source.on_change('selected', selection_change) curdoc().add_root(row(fsel, play_all_button, play_all_sox_button, audio_first_checkbox, msgdiv)) (gp, ch0) = make_plot() x_range = ch0.x_range curdoc().add_root(row(gp))
p.line('last_mod_date', "v", source=source) tab1 = Panel(child=p, title="Plot") columns = [ TableColumn(field="last_mod_date", title="TimeStamp"), TableColumn(field="date", title="Date"), TableColumn(field="v", title="Value"), ] dataTable = DataTable(source=source, columns=columns, width=800, height=600) tab2 = Panel(child=dataTable, title="Table") tabs = Tabs(tabs=[tab1, tab2]) # tabs.css_classes = ["hide"] autoUpdateCheckbox = CheckboxGroup( labels=["Auto Update Data Source (every 15s)"], active=[]) autoUpdateCheckbox.disabled = True gatewayControl.on_change('value', lambda attr, old, new: update_device()) deviceControl.on_change('value', lambda attr, old, new: update_indicator()) submitButton.on_click(lambda: callback()) autoUpdateCheckbox.on_click(lambda attr: auto_update(attr)) sizing_mode = 'fixed' # 'scale_width' also looks nice with this example inputs = widgetbox(*controls, sizing_mode=sizing_mode, name="widgets") plotwidget = widgetbox([autoUpdateCheckbox, tabs], sizing_mode=sizing_mode, name="plotwidget") mainLayout = layout(children=[[inputs, plotwidget]], sizing_mode=sizing_mode,
from numpy import pi import pandas as pd import numpy as np import matplotlib.pyplot as plt import json import math import re import itertools # # Load # generate and save data from generate file. Save it with logical filename cat_data = np.load('my_file.npy').item() categories = list(cat_data.keys()) category_selection = CheckboxGroup(labels=categories, active=[0, 1]) # Select the airlines names from the selection values [category_selection.labels[i] for i in category_selection.active] def modify_doc(doc): 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'
from bokeh.plotting import figure from bokeh.sampledata.iris import flowers from bokeh.sampledata.autompg2 import autompg2 as mpg click_button = Button(label="Button still has click event", button_type="success") disabled_button = Button(label="Button (disabled) - still has click event", button_type="primary", disabled=True) toggle = Toggle(label="Toggle button", button_type="success") menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, split=True) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) text_input = TextInput(placeholder="Enter value ...") completions = ["aaa", "aab", "aac", "baa", "caa"] autocomplete_input = AutocompleteInput(placeholder="Enter value (auto-complete) ...", completions=completions) select = Select(options=["Option 1", "Option 2", "Option 3"]) multi_select = MultiSelect(options=["Option %d" % (i+1) for i in range(16)], size=6) slider = Slider(value=10, start=0, end=100, step=0.5)
def buildDevicesTab(): gfxVendorSelect = Select(title='Vendor', options=gfxVendors, value=gfxVendors[0]) gfxDeviceCheckbox = CheckboxGroup() source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title="GFX Devices", x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update_view(): vendor = gfxVendorSelect.value deviceNames = getDeviceNames('release', vendor, True) gfxDeviceCheckbox.labels = deviceNames devices = [deviceNames[i] for i in range(len(deviceNames)) if i in gfxDeviceCheckbox.active] releaseUsers = 100 * getUsersForDevices('release', vendor, devices) / gfxTotalReleaseUsers betaUsers = 100 * getUsersForDevices('beta', vendor, devices) / gfxTotalBetaUsers fig.x_range.factors = devices fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in devices], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in devices], y=betaUsers / 2, height=betaUsers, ) def update(attrname, old, new): gfxDeviceCheckbox.active = [i for i in range(5)] update_view() def click(selected): update_view() gfxVendorSelect.on_change('value', update) gfxDeviceCheckbox.on_click(click) update('value', '', gfxVendorSelect.value) deviceComparison = HBox(HBox(VBoxForm(*[gfxVendorSelect, gfxDeviceCheckbox]), width=300), fig, width=1100) return Panel(child=deviceComparison, title="GFX Device Comparison")
# the database connection db = MongoClient().scientificworkflowlogs datasource = db.test attributes = ["timestamp", "min1", "min5", "min15", "duration", "procs_total", "procs_running", "procs_sleeping", "procs_waiting", "procs_vmsize", "procs_rss", "task_total", "task_running", "task_sleeping", "task_waiting", "ram_shared", "ram_buffer", "swap_total", "swap_free"] attributes_p1 = ["min1", "min5", "min15", "procs_running", "procs_waiting", "task_running", "task_waiting", "ram_shared", "swap_total", "swap_free"] attributes_p2 = ["procs_total", "procs_sleeping", "task_total", "task_sleeping", "ram_buffer"] attributes_p3 = ["procs_vmsize", "procs_rss"] attributes_p4 = ["duration"] # Order attributes by plot, such that the checkboxes appear in order attributes_ord = attributes_p1 + attributes_p2 + attributes_p3 + attributes_p4 #checkbox_group_p = CheckboxGroup(labels=attributes[1:], active=[i for i in range(len(attributes[1:]))]) checkbox_group_p = CheckboxGroup(labels=attributes_ord, active=[i for i in range(len(attributes_ord))]) # Redraw plots, if a checkbox was set or unset def checkbox(attr, old, new): global source global task_source global current_run global checkbox_group_p global attributes global attributes_ord global datasource events_pipeline = [ {"$match": {"session.id": current_run}}, {"$sort": {"timestamp": 1}},
def attention_tab(beers): # Dataset for density plot based on Genres and range of ratings # and bandwidth for density estimation def make_dataset( genre_list, range_start, range_end, bandwidth ): xs = [] ys = [] colors = [] labels = [] for i, genre in enumerate(genre_list): subset = beers[beers['style_genre'] == genre] subset = subset[subset['ratings'].between(range_start, range_end)] kde = gaussian_kde(subset['ratings'], bw_method=bandwidth) # Evenly space x values x = np.linspace(range_start, range_end, 6500) # 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(genre_colors[i]) labels.append(genre) 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 = 650, title = 'Distribution of Beer Genre Attention', x_axis_label = 'Attention of Genre (Number of Ratings of Beer)', 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=[('Genre', '@label'), ('Ratings', '$x'), ('Density', '$y')], line_policy = 'next') # Add the hover tool and styling p.add_tools(hover) p = p_style(p) return p def update(attr, old, new): # List of genres to plot genres_to_plot = [genre_selection.labels[i] for i in genre_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(genres_to_plot, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth) src.data.update(new_src.data) def p_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 # genres and colors available_genres = list(set(beers['style_genre'])) available_genres.sort() genre_colors = Category20_16 genre_colors.sort() # Genres to plot genre_selection = CheckboxGroup(labels=available_genres, active = [0, 1]) genre_selection.on_change('active', update) range_select = RangeSlider(start = 0, end = 500, value = (0, 200), step = 50, title = 'Range of Attention (Number of Ratings)') range_select.on_change('value', update) # intial genres and data source initial_genres = [genre_selection.labels[i] for i in genre_selection.active] # Bandwidth of kernel bandwidth_select = Slider(start = 0.1, end = 5, step = 0.1, value = 2, 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_genres, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth_select.value) sidetext = Div( text="""Please use the filters below to adjust the <b>Attention Density Plot</b> as needed.""", width=250, height=50) # Make the density plot p = make_plot(src) # Add style to the plot p = p_style(p) # Put controls in a single element controls = WidgetBox(sidetext, genre_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 = 'Distribution of Beer Genre Attention') return tab
y_column = Select(title='Variable', value=y_col_init, options=columns) y_column.on_change('value', update_columns) size_column = Select(title='Size', value='constant', options=['constant'] + columns) size_column.on_change('value', update_columns) slider = RangeSlider(start=years[0], end=years[-1], range=(years[0], years[-1]), step=1, title="Years") slider.on_change('range', update_year) region_column = CheckboxGroup(labels=regions[:], active=range(len(regions))) region_column.on_change('active', update_columns) country_column = CheckboxGroup(labels=countries[:], active=range(10)) country_column.on_change('active', update_columns) reset_button = Button(label='Reset') reset_button.on_click(reset) #Create initial plot p, sc_source, line_source = make_plot() desc_box = Div(text=update_desc_box()) controls = widgetbox( [y_column, size_column, country_column, slider, reset_button, desc_box],
def select_values_2(attr, old, new, w_box, c_data): if new != 'None': if c_data[w_box.children[1]. value][new].values.dtype == 'object': # categorical data level_3 = MultiSelect(title='value', value=['None'], options=['None'], width=180) try: level_3.options = np.unique( c_data[w_box.children[1].value] [new].iloc[:, 0].dropna().values).tolist() level_3.value = [level_3.options[0]] except TypeError: level_3.options = np.unique([ str(obj) for obj in c_data[w_box.children[1].value] [new].iloc[:, 0].dropna().values ]).tolist() finally: w_box.children[3] = column(level_3) elif 'datetime' in str(c_data[w_box.children[1].value] [new].values.dtype): # datetime data start = c_data[w_box.children[1].value][new].min().dt.date.item() end = c_data[w_box.children[1].value][new].max().dt.date.item() date_slider = DateRangeSlider( title="", start=start, end=end, value=(start, end), # value_as_date=True, # step=1, width=180) checkbox_group = CheckboxGroup(labels=["invert selection"], active=[], width=180) w_box.children[3] = column(date_slider, checkbox_group) elif 'int' in str(c_data[w_box.children[1].value][new].values.dtype) or \ 'float' in str(c_data[w_box.children[1].value][new].values.dtype): # print("3 ", clinical_data[select_1.value][new].values.dtype) start = c_data[w_box.children[1].value][new].min().item() end = c_data[w_box.children[1].value][new].max().item() slider = RangeSlider(start=start, end=end, step=0.1, value=(start, end), title=new + " Range", width=180) checkbox_group = CheckboxGroup(labels=["invert selection"], active=[], width=180) w_box.children[3] = column(slider, checkbox_group) else: print( "Something went wrong, unexpected datatype by clinical data value selecting" ) # TODO error message? else: w_box.children[3] = PreText(text='please select a property', width=200)
def modify_doc(doc): 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' #other p.plot_width = 2000 return p def get_percentages(cat): variables = [str(x) for x in range(100)] name = 'age' values_s = [] values_v = [] for var in variables: values_s.append(cat_data[cat]['suspect'][name][var]) values_v.append(cat_data[cat]['victim'][name][var]) percentages_s = [] #percentages_v = [] if sum(values_s) == 0: percentages_s = [x for x in values_s] # if sum(values_v) == 0: # percentages_v = [x for x in values_v] if sum(values_s) != 0: percentages_s = [x / float(sum(values_s)) for x in values_s] # if sum(values_v) != 0: # percentages_v = [x/float(sum(values_v)) for x in values_v] return percentages_s def make_dataset(categories, range_start=0, range_end=100, bin_width=1): # Check to make sure the start is less than the end! assert range_start < range_end, "Start must be less than end!" for_category = pd.DataFrame(columns=[ 'proportion', 'left', 'right', 'f_proportion', 'f_interval', 'name', 'color' ]) range_extent = range_end - range_start # Iterate through all the carriers i = 0 for category in categories: #GET THESE PERCENTAGES FROM generate file arr_hist = np.array(get_percentages(category)) edges = np.array([x for x in range(len(arr_hist) + 1)]) # Divide the counts by the total to get a proportion and create df arr_df = pd.DataFrame({ 'proportion': 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 years' % (left, right) for left, right in zip(arr_df['left'], arr_df['right']) ] # Assign the carrier for labels arr_df['name'] = category # Color each carrier differently print(Category20_16[i], i) arr_df['color'] = Category20_16[i] if i == 15: print("i", i) i = 0 # Add to the overall dataframe for_category = for_category.append(arr_df) i += 1 # Overall dataframe for_category = for_category.sort_values(['name', 'left']) print(for_category.head()) # Convert dataframe to column data source return ColumnDataSource(for_category) def make_plot(src): # Blank plot with correct labels p = figure(plot_width=700, plot_height=700, title='Histogram of Arrival Delays by Carrier', 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) p.legend.click_policy = 'hide' # Styling p = style(p) return p # Update function takes three default parameters def update(attr, old, new): # Get the list of carriers for the graph categories_to_plot = [ category_selection.labels[i] for i in category_selection.active ] # Make a new dataset based on the selected carriers and the # make_dataset function defined earlier new_src = make_dataset(categories_to_plot, range_start=-60, range_end=120, bin_width=5) # Update the source used the quad glpyhs src.data.update(new_src.data) category_selection = CheckboxGroup(labels=categories, active=[0, 1]) category_selection.on_change('active', update) controls = WidgetBox(category_selection) initial_categories = [ category_selection.labels[i] for i in category_selection.active ] src = make_dataset(initial_categories, range_start=-60, range_end=120, bin_width=5) p = make_plot(src) layout = row(controls, p) doc.add_root(layout)
from bokeh.layouts import row from bokeh.models import ColumnDataSource from bokeh.models.widgets import CheckboxGroup from bokeh.plotting import figure x=[3,4,6,12,10,1] y=[7,1,3,4,1,6] source = ColumnDataSource(data=dict(x=x, y=y)) plot_figure = figure(title='Checkbox',plot_height=450, plot_width=600, tools="save,reset",toolbar_location="below") plot_figure.scatter('x', 'y', source=source, size=10) checkbox = CheckboxGroup(labels=['Show x-axis label','Show y-axis label']) def checkbox_click(attr,old,new): active_checkbox=checkbox.active ##Getting checkbox value in list ## Get first checkbox value and show x-axis label if len(active_checkbox)!=0 and (0 in active_checkbox): plot_figure.xaxis.axis_label='X-Axis' else: plot_figure.xaxis.axis_label = None ## Get second checkbox value and show y-axis label if len(active_checkbox)!=0 and (1 in active_checkbox): plot_figure.yaxis.axis_label='Y-Axis'
return p # Update the plot based on selections 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) # 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
toggle_active = Toggle(label="Toggle button (initially active)", button_type="success", active=True) toggle_active.js_on_click(CustomJS(code="console.log('toggle_active: ' + this.active, this.toString())")) menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())")) dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", disabled=True, menu=menu) dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())")) #dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default") #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())")) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())")) widget_box = WidgetBox(children=[ button, button_disabled, toggle_inactive, toggle_active, dropdown, dropdown_disabled, #dropdown_split,
def team_tab(passing_model): result = [ "Group Stage", "Round of 16", "Quarter-finals", "Semi-finals", "Final" ] #position_details = list(passing_model.Position_Detail.unique()) result_color = factor_cmap('Round', palette=Spectral6, factors=result) checkbox = CheckboxGroup(labels=result, active=[0, 1, 2, 3, 4]) rounds = [checkbox.labels[i] for i in checkbox.active] #max_passes = int(passing_model["Passes"].max()) #pass_slider = RangeSlider( # start=0, end=max_passes, value=(70, max_passes), # step=5, title="Number of Passes") def make_dataset(rounds): source = ColumnDataSource( data=passing_model.loc[passing_model["Round"].isin(rounds), :]) #& #(passing_model["Passes"] >= pass_slider_min) & #(passing_model["Passes"] <= pass_slider_max), :]) source.data["Pass_Size"] = source.data["Passes"] / 50 source.data["xP_Mean_mean"] = np.repeat(source.data["xP_Mean"].mean(), len(source.data["Passes"])) source.data["xP_Rating_mean"] = np.repeat( source.data["xP_Rating"].mean(), len(source.data["Passes"])) return source def make_plot(source): """Need to return the span so we can update them in callback (I think)""" # Set up Plot Figure plot_size_and_tools = { 'plot_height': 100, 'plot_width': 1000, 'x_range': (source.data["xP_Rating"].min() * .8, source.data["xP_Rating"].max() * 1.2), 'y_range': (source.data["xP_Mean"].min() * .8, source.data["xP_Mean"].max() * 1.2) } plot = figure( tools=["tap", "pan", "wheel_zoom", 'box_select', 'reset', 'help'], title="Expected Passes v. Pass Difficulty") plot.y_range.flipped = True # Get Means and Ranges and Top n% for Labels xp_ms = source.data["xP_Mean_mean"][0] xp_mean_span = Span(location=xp_ms, dimension='width', line_color="black", line_dash='solid', line_width=3, line_alpha=.2) plot.add_layout(xp_mean_span) xp_rs = source.data["xP_Rating_mean"][0] xp_rating_span = Span(location=xp_rs, dimension='height', line_color="black", line_dash='solid', line_width=3, line_alpha=.2) plot.add_layout(xp_rating_span) renderer = plot.circle( "xP_Rating", "xP_Mean", size="Pass_Size", color=result_color, legend="Round", source=source, # set visual properties for selected glyphs selection_color=Spectral6[5], #color="Position_Detail", # set visual properties for non-selected glyphs nonselection_fill_alpha=0.1, nonselection_fill_color=Spectral6[0], nonselection_line_color=Spectral6[5], nonselection_line_alpha=1.0) plot.legend.location = (10, 50) plot.legend.border_line_width = 3 plot.legend.border_line_color = "black" plot.legend.border_line_alpha = 0.5 labels = LabelSet(x='xP_Rating', y='xP_Mean', text='Team', level='glyph', text_font_size='10pt', x_offset=-2, y_offset=2, source=source, render_mode='canvas') plot.add_layout(labels) # Hover tool with vline mode hover = HoverTool( tooltips=[ ('Team', '@Team'), ('Result', '@Round'), #('Position', '@Position_Detail'), ('Expected Pass Rating', '@xP_Rating'), ('Total Passes', '@Passes') ], mode='vline') plot.add_tools(hover) # Add Labels in the corners citation1 = Label(x=10, y=10, x_units='screen', y_units='screen', text='Easier Passes, Poorly Executed', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) # Add Labels in the corners citation2 = Label(x=10, y=510, x_units='screen', y_units='screen', text='Harder Passes, Poorly Executed', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) # Add Labels in the corners citation3 = Label(x=625, y=10, x_units='screen', y_units='screen', text='Easier Passes, Well Executed', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) # Add Labels in the corners citation4 = Label(x=625, y=510, x_units='screen', y_units='screen', text='Easier Passes, Well Executed', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) plot.add_layout(citation1) plot.add_layout(citation2) plot.add_layout(citation3) plot.add_layout(citation4) return plot, xp_mean_span, xp_rating_span def callback(attr, old, new): new_rounds = [checkbox.labels[i] for i in checkbox.active] # Update Dataset new_df = make_dataset(new_rounds) source.data.update(new_df.data) # Update Averages xp_ms = source.data["xP_Mean_mean"][0] xp_mean_span.location = xp_ms xp_rs = source.data["xP_Rating_mean"][0] xp_rating_span.location = xp_rs source = make_dataset(rounds) plot, xp_mean_span, xp_rating_span = make_plot(source) inputs = widgetbox(checkbox) checkbox.on_change('active', callback) #pass_slider.on_change('value', callback) # Create a row layout layout = column(inputs, plot) #layout = row(plot) # Make a tab with the layout tab = Panel(child=layout, title='Team Passing Model') return tab
def _create_type_filter(incident_types): checkbox_group = CheckboxGroup( labels=[t for t in incident_types], active=list(np.arange(0,len(incident_types)))) header = Div(text="Incident types:", width=200, height=100) return checkbox_group #widgetbox(children=[header, checkbox_group])
def map_tab(map_data, states): # Function to make a dataset for the map based on a list of carriers def make_dataset(carrier_list): # Subset to the carriers in the specified list subset = map_data[map_data['carrier']['Unnamed: 3_level_1'].isin( carrier_list)] # Dictionary mapping carriers to colors color_dict = {carrier: color for carrier, color in zip( available_carriers, airline_colors)} # Lists of data for plotting flight_x = [] flight_y = [] colors = [] carriers = [] counts = [] mean_delays = [] min_delays = [] max_delays = [] dest_loc = [] origin_x_loc = [] origin_y_loc = [] dest_x_loc = [] dest_y_loc = [] origins = [] dests = [] distances = [] # Iterate through each carrier for carrier in carrier_list: # Subset to the carrier sub_carrier = subset[subset['carrier']['Unnamed: 3_level_1'] == carrier] # Iterate through each route (origin to destination) for the carrier for _, row in sub_carrier.iterrows(): colors.append(color_dict[carrier]) carriers.append(carrier) origins.append(row['origin']['Unnamed: 1_level_1']) dests.append(row['dest']['Unnamed: 2_level_1']) # Origin x (longitude) and y (latitude) location origin_x_loc.append(row['start_long']['Unnamed: 20_level_1']) origin_y_loc.append(row['start_lati']['Unnamed: 21_level_1']) # Destination x (longitude) and y latitude (location) dest_x_loc.append(row['end_long']['Unnamed: 22_level_1']) dest_y_loc.append(row['end_lati']['Unnamed: 23_level_1']) # Flight x (longitude) locations flight_x.append([row['start_long']['Unnamed: 20_level_1'], row['end_long']['Unnamed: 22_level_1']]) # Flight y (latitude) locations flight_y.append([row['start_lati']['Unnamed: 21_level_1'], row['end_lati']['Unnamed: 23_level_1']]) # Stats about the particular route counts.append(row['arr_delay']['count']) mean_delays.append(row['arr_delay']['mean']) min_delays.append(row['arr_delay']['min']) max_delays.append(row['arr_delay']['max']) distances.append(row['distance']['mean']) # Create a column data source from the lists of lists new_src = ColumnDataSource(data = {'carrier': carriers, 'flight_x': flight_x, 'flight_y': flight_y, 'origin_x_loc': origin_x_loc, 'origin_y_loc': origin_y_loc, 'dest_x_loc': dest_x_loc, 'dest_y_loc': dest_y_loc, 'color': colors, 'count': counts, 'mean_delay': mean_delays, 'origin': origins, 'dest': dests, 'distance': distances, 'min_delay': min_delays, 'max_delay': max_delays}) return new_src def make_plot(src, xs, ys): # Create the plot with no axes or grid p = figure(plot_width = 1100, plot_height = 700, title = 'Map of 2013 Flight Delays Departing NYC') p.xaxis.visible = False p.yaxis.visible = False p.grid.visible = False # States are drawn as patches patches_glyph = p.patches(xs, ys, fill_alpha=0.2, fill_color = 'lightgray', line_color="#884444", line_width=2, line_alpha=0.8) # Airline flights are drawn as lines lines_glyph = p.multi_line('flight_x', 'flight_y', color = 'color', line_width = 2, line_alpha = 0.8, hover_line_alpha = 1.0, hover_line_color = 'color', legend = 'carrier', source = src) # Origins are drawn as squares (all in NYC) squares_glyph = p.square('origin_x_loc', 'origin_y_loc', color = 'color', size = 10, source = src, legend = 'carrier') # Destinations are drawn as circles circles_glyph = p.circle('dest_x_loc', 'dest_y_loc', color = 'color', size = 10, source = src, legend = 'carrier') # Add the glyphs to the plot using the renderers attribute p.renderers.append(patches_glyph) p.renderers.append(lines_glyph) p.renderers.append(squares_glyph) p.renderers.append(circles_glyph) # Hover tooltip for flight lines, assign only the line renderer hover_line = HoverTool(tooltips=[('Airline', '@carrier'), ('Number of Flights', '@count'), ('Average Delay', '@mean_delay{0.0}'), ('Max Delay', '@max_delay{0.0}'), ('Min Delay', '@min_delay{0.0}')], line_policy = 'next', renderers = [lines_glyph]) # Hover tooltip for origin and destination, assign only the line renderer hover_circle = HoverTool(tooltips=[('Origin', '@origin'), ('Dest', '@dest'), ('Distance (miles)', '@distance')], renderers = [circles_glyph]) # Position the location so it does not overlap plot p.legend.location = (10, 50) # Add the hovertools to the figure p.add_tools(hover_line) p.add_tools(hover_circle) p = style(p) return p # Styling 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 # Show selected carriers on map def update(attr, old, new): # Find list of carriers and make a new data set carrier_list = [carrier_selection.labels[i] for i in carrier_selection.active] new_src = make_dataset(carrier_list) src.data.update(new_src.data) available_carriers = list(set(map_data['carrier']['Unnamed: 3_level_1'])) available_carriers.sort() airline_colors = Category20_16 airline_colors.sort() # Remove Alaska and Hawaii from states if 'HI' in states: del states['HI'] if 'AK' in states: del states['AK'] # Put longitudes and latitudes in lists xs = [states[state]['lons'] for state in states] ys = [states[state]['lats'] for state in states] # CheckboxGroup to select carriers for plotting carrier_selection = CheckboxGroup(labels=available_carriers, active = [0, 1]) carrier_selection.on_change('active', update) # Initial carriers to plot initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] # Initial source and plot src = make_dataset(initial_carriers) p = make_plot(src, xs, ys) # Layout setup layout = row(carrier_selection, p) tab = Panel(child = layout, title = 'Flight Map') return tab
from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models.widgets import TextInput, Slider, CheckboxGroup, DatePicker, DataTable, Div state_choose = TextInput(value="MA", title="Choose State") state_choose.on_change('value', update) radius_select = TextInput(value='5', title='Select Radius (Miles)') radius_select.on_change('value', update) solution_select = TextInput(value='0', title='Select Solution') solution_select.on_change('value', update) tran_type_select = CheckboxGroup(labels=['Sale', 'Return'], active=[0, 1], name='Transaction Type') tran_type_select.on_change('active', update) min_date_select = DatePicker(title='Start Date', value=min_date1, min_date=min_date1, max_date=max_date1) min_date_select.on_change('value', update) max_date_select = DatePicker(title='End Date', value=max_date1, min_date=min_date1, max_date=max_date1) max_date_select.on_change('value', update) guideline = Div(text="""<center>
all_figures.append(monthly_edition_bytes_figure) for fig in all_figures: fig.x_range = all_figures[0].x_range cbg_labels = [ "Total pages", "Monthly new pages", "Total pages per user", "Monthly edited pages", "Total editions", "Monthly editions", "Total editions per user", "Total editions per page", "Monthly editions per edited page", "Editions by author type", "Total users", "Total logged users", "Total anonymous users", "Monthly new users", "Monthly new logged users", "Monthly new anonymous users", "Active users by type", "Average page size", "Average edition bytes", "Monthly average edition bytes" ] cbg_pages = CheckboxGroup(labels=cbg_labels[0:4], active=[0], css_classes=['pages_checks']) cbg_editions = CheckboxGroup(labels=cbg_labels[4:10], active=[0], css_classes=['edition_checks']) cbg_users = CheckboxGroup(labels=cbg_labels[10:17], active=[], css_classes=['users_checks']) cbg_ratios = CheckboxGroup(labels=cbg_labels[17:20], active=[], css_classes=['other_checks']) cbg_pages.on_click(cb_callback) cbg_editions.on_click(cb_callback) cbg_users.on_click(cb_callback) cbg_ratios.on_click(cb_callback)
) clear_seed_button = Button( label="Clear", button_type="success", css_classes=["clear_button"], width=50 ) export_button = Button( label="Export", button_type="success", css_classes=["export_button"], width=100 ) expand_table_source = ColumnDataSource(data=empty_table) expand_table = DataTable( source=expand_table_source, columns=expand_columns, width=500, css_classes=["expand_table"] ) phrases_list = MultiSelect( title="", value=[], options=[], width=300, size=27, css_classes=["phrases_list"] ) checkbox_group = CheckboxGroup( labels=["Text annotation", checkbox_label], active=[], width=400, css_classes=["checkbox_group"] ) annotate_checkbox = CheckboxGroup( labels=["Text annotation"], active=[], width=400, css_classes=["annotate_checkbox"] ) search_box_area = column(children=[Div(height=10, width=200)]) working_label = Div(text="", style={"color": "blue", "font-size": "15px"}) search_working_label = Div( text="", style={"color": "blue", "padding-bottom": "0px", "font-size": "15px"} ) seed_check_label = Div(text="", style={"font-size": "15px"}, height=20, width=500) table_layout = Row(expand_table) table_area = column(children=[table_layout]) seed_layout = column( Row(seed_input_box, column(Div(height=14, width=0), clear_seed_button)), expand_button,
def type_tab(df): """ Make a tab includes a line plot which shows how different attack types affected when year pass Parameters: df (DataFrame): a pandas dataframe Returns: tab: a bokeh object """ # Setup needed variable unique_types = list(df.attacktype1_txt.unique()) palette = brewer['Spectral'][len(unique_types)] colormap = {unique_types[i]: palette[i] for i in range(len(unique_types))} def make_data(df, start=1970, end=2017, types=unique_types): """ Modify data for plotting Parameters: df (DataFrame): a pandas dataframe start (int): start year number end (int): end year number types (list): a list of unique attack type Returns: ColumnDataSource: a bokeh object """ modified = df[(df['iyear'] >= start) & (df['iyear'] <= end)].\ groupby(['iyear', 'attacktype1_txt'], as_index=False).count() modified = modified[modified['attacktype1_txt'].isin(types)] source = {} for i in range(len(types)): if 'x' in source.keys(): source['x'].append( list(modified[modified['attacktype1_txt'] == types[i]].iyear)) source['y'].append( list(modified[modified['attacktype1_txt'] == types[i]].eventid)) source['type'].append( list(modified[modified['attacktype1_txt'] == types[i]].attacktype1_txt.unique())) source['colors'].append(colormap[types[i]]) else: source['x'] = [ list(modified[modified['attacktype1_txt'] == types[i]].iyear) ] source['y'] = [ list(modified[modified['attacktype1_txt'] == types[i]].eventid) ] source['type'] = [ list(modified[modified['attacktype1_txt'] == types[i]].attacktype1_txt.unique()) ] source['colors'] = [colormap[types[i]]] return ColumnDataSource(source) def update(): """ Update the ColumnDataSource when client interact with widgets """ selected_types = [types.labels[i] for i in types.active] new_src = make_data(df, year.value[0], year.value[1], selected_types) src.data.update(new_src.data) # Setup needed variable year = RangeSlider(start=1970, end=2017, value=(1970, 2017), step=1, title="Year Range") types = CheckboxGroup(labels=unique_types, active=list(range(len(unique_types)))) src = make_data(df) year.on_change('value', lambda attr, old, new: update()) types.on_change('active', lambda attr, old, new: update()) controls = WidgetBox(year, types) # line plot p = figure(plot_height=600, plot_width=800, title='Attack Types', x_axis_label='Years', y_axis_label='Types', output_backend='webgl') p.multi_line(xs='x', ys='y', source=src, line_color='colors', line_width=2, legend='type') p.legend.location = 'top_left' p.add_tools( HoverTool(show_arrow=False, tooltips=[('Year', '$data_x'), ('Counts', '$data_y'), ('Type', '@type')])) # Setup tab structure and name tab = Panel(child=row(controls, p), title='Attack Types') return tab
def histogram_tab(data): # Function to make a dataset for histogram based on a list of journals, def make_dataset(topic_list): # Dataframe to hold information sum_table = data.groupby('Journal').sum() sum_table['Journal'] = ['AA', 'ASR', 'JMAS'] table = sum_table[topic_list] new_table = pd.melt(table, var_name='topics', value_name='count') journal = ["AA", "ASR", "JMAS"] * len(topic_list) new_table['Journal'] = journal grouped = new_table.groupby(['topics', 'Journal']) x = [name for name, group in grouped] counts = new_table.groupby(['topics', 'Journal'])['count'].sum().values source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure(x_range=FactorRange(*x), plot_height=250, title="Topics Break Down by Year") return source, p 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, p): journal = ["AA", "ASR", "JMAS"] palette = [cc.rainbow[i * 15] for i in range(17)] p.vbar(x='x', top='counts', width=0.9, source=src, fill_color=factor_cmap('x', palette=palette, factors=journal, start=1, end=2)) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None hover = HoverTool() hover.tooltips = [("count", "@counts")] hover.mode = 'vline' p.add_tools(hover) # Styling p = style(p) return p def update(attr, old, new): topics_to_plot = [ topic_selection.labels[i] for i in topic_selection.active ] new_src, p = make_dataset(topics_to_plot) src.data.update(new_src.data) # Carriers and colors available_topics = [ "topics_domestic_politics", "topics_international_relations", "topics_society", "topics_econ" ] topic_selection = CheckboxGroup(labels=available_topics, active=[0, 1, 2, 3]) topic_selection.on_change('active', update) # Initial carriers and data source initial_topics = [ topic_selection.labels[i] for i in topic_selection.active ] src, p = make_dataset(initial_topics) p = make_plot(src, p) # Put controls in a single element controls = WidgetBox(topic_selection) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title='Histogram') return tab
# initialize data source for line plot source_curve = ColumnDataSource(data=dict(x=[], y=[])) # plotting for normal parametrization source_point_normal = ColumnDataSource(data=dict(x=[], y=[])) # plotting for arc length parametrization source_point_arc = ColumnDataSource(data=dict(x=[], y=[])) # initialize controls # choose between original and arc length parametrization parametrization_input = CheckboxGroup(labels=['show original parametrization', 'show arc length parametrization'], active=[0, 1]) parametrization_input.on_click(parametrization_change) # slider controlling the current parameter t t_value_input = Slider(title="parameter t", name='parameter t', value=arc_settings.t_value_init, start=arc_settings.t_value_min, end=arc_settings.t_value_max, step=arc_settings.t_value_step) t_value_input.on_change('value', t_value_change) # text input for the x component of the curve x_component_input = TextInput(value=arc_settings.x_component_input_msg, title="curve x") x_component_input.on_change('value', curve_change) # text input for the y component of the curve y_component_input = TextInput(value=arc_settings.y_component_input_msg, title="curve y") y_component_input.on_change('value', curve_change) # dropdown menu for selecting one of the sample curves sample_curve_input = Dropdown(label="choose a sample function pair or enter one below",
hover = HoverTool(tooltips=[('Carrier', '@name'), ('Delay', '@f_interval'), ('Proportion', '@f_proportion')], mode='vline') p.add_tools(hover) # Styling p = style(p) return p p = make_plot(ColumnDataSource(by_carrier)) show(p) carrier_selection = CheckboxGroup(labels=available_carriers, active=[0, 1]) show(carrier_selection) [carrier_selection.labels[i] for i in carrier_selection.active] # Update function takes three default parameters def update(attr, old, new): # Get the list of carriers for the graph carriers_to_plot = [ carrier_selection.labels[i] for i in carrier_selection.active ] # Make a new dataset based on the selected carriers and the # make_dataset function defined earlier new_src = make_dataset(carriers_to_plot,
class BenchmarkApp(HBox): """An example of a browser-based, interactive plot with slider controls.""" extra_generated_classes = [["BenchmarkApp", "BenchmarkApp", "HBox"]] inputs = Instance(VBoxForm) # widgets benchmarks = Instance(Select) x_axis_options = Instance(Select) y_axis_options = Instance(Select) # TODO: Convert this to a MultiSelect once it is fixed # https://github.com/bokeh/bokeh/issues/2495 device_names = Instance(CheckboxGroup) platform_names = Instance(CheckboxButtonGroup) # data displays, not enabled by default data_display0 = Instance(DataTable) data_display1 = Instance(DataTable) # plot and interaction plot = Instance(Plot) hover = Instance(HoverTool) # data source0 = Instance(ColumnDataSource) source1 = Instance(ColumnDataSource) source2 = Instance(ColumnDataSource) source3 = Instance(ColumnDataSource) source4 = Instance(ColumnDataSource) source5 = Instance(ColumnDataSource) source6 = Instance(ColumnDataSource) source7 = Instance(ColumnDataSource) source8 = Instance(ColumnDataSource) source9 = Instance(ColumnDataSource) def make_source(self): # set up the data source self.source0 = ColumnDataSource(data=dict()) self.source1 = ColumnDataSource(data=dict()) self.source2 = ColumnDataSource(data=dict()) self.source3 = ColumnDataSource(data=dict()) self.source4 = ColumnDataSource(data=dict()) self.source5 = ColumnDataSource(data=dict()) self.source6 = ColumnDataSource(data=dict()) self.source7 = ColumnDataSource(data=dict()) self.source8 = ColumnDataSource(data=dict()) self.source9 = ColumnDataSource(data=dict()) def make_inputs(self): columns = [ TableColumn(field='x', title='x'), TableColumn(field='y', title='y'), TableColumn(field='device', title='device'), TableColumn(field='platform', title='platform') ] # obj.data_display0 = DataTable(source=obj.source2, columns=columns) # obj.data_display1 = DataTable(source=obj.source3, columns=columns) # setup user input self.x_axis_options = Select(title="X:", value='size', options=axis_options) self.y_axis_options = Select(title="Y:", value='throughput [1/sec]', options=axis_options) self.benchmarks = Select(title="Benchmark:", value=benchmark_names[0], options=benchmark_names) self.device_names = CheckboxGroup(labels=device_names, active=[0]) self.platform_names = CheckboxButtonGroup(labels=platform_names, active=[0]) @classmethod def create(cls): """One-time creation of app's objects. This function is called once, and is responsible for creating all objects (plots, datasources, etc) """ obj = cls() obj.make_source() obj.make_inputs() obj.make_plot() obj.update_data() obj.set_children() return obj def plot_data(self, source, linecolor, symbolfill): self.plot.line( 'x', 'y', source=source, line_color=linecolor, line_width=3, line_alpha=0.6) self.plot.scatter('x', 'y', source=source, fill_color=symbolfill, size=8) def make_plot(self): # configure the toolset toolset = ['wheel_zoom,save,box_zoom,resize,reset'] self.hover = BenchmarkApp.make_hovertool() toolset.append(self.hover) title = self.benchmarks.value + " " + \ "(" + self.y_axis_options.value + " vs." + self.x_axis_options.value + ")" self.plot = figure(title_text_font_size="12pt", plot_height=400, plot_width=400, tools=toolset, title=title, ) # remove the logo self.plot.logo = None # Generate a figure container # Plot the line by the x,y values in the source property self.plot_data(self.source0, "#F0A3FF", "white") self.plot_data(self.source1, "#0075DC", "white") self.plot_data(self.source2, "#993F00", "white") self.plot_data(self.source3, "#4C005C", "white") self.plot_data(self.source4, "#191919", "white") self.plot_data(self.source5, "#005C31", "white") self.plot_data(self.source6, "#2BCE48", "white") self.plot_data(self.source7, "#FFCC99", "white") self.plot_data(self.source8, "#808080", "white") self.plot_data(self.source9, "#94FFB5", "white") # set the x/y axis labels # plot.xaxis.axis_label = self.x_axis_options.value # plot.yaxis.axis_label = self.y_axis_options.value def set_children(self): self.inputs = VBoxForm( children=[self.benchmarks, self.device_names, self.platform_names, self.x_axis_options, self.y_axis_options, # self.data_display0, self.data_display1 ] ) self.children.append(self.inputs) self.children.append(self.plot) @classmethod def make_hovertool(self): hover = HoverTool( tooltips = [ ("Device", "@device"), ("Backend", "@platform"), ("(x,y)", "(@x,@y)") ] ) return hover def setup_events(self): """Attaches the on_change event to the value property of the widget. The callback is set to the input_change method of this app. """ super(BenchmarkApp, self).setup_events() if not self.benchmarks: return # Event registration for everything except checkboxes self.benchmarks.on_change('value', self, 'benchmark_changed') self.x_axis_options.on_change('value', self, 'input_change') self.y_axis_options.on_change('value', self, 'input_change') # Event registration for checkboxes self.device_names.on_click(self.checkbox_handler) self.platform_names.on_click(self.checkbox_handler) def checkbox_handler(self, active): self.update_data() def benchmark_changed(self, obj, attrname, old, new): self.update_data() self.make_plot() curdoc().add(self) def input_change(self, obj, attrname, old, new): """Executes whenever the input form changes. It is responsible for updating the plot, or anything else you want. Args: obj : the object that changed attrname : the attr that changed old : old value of attr new : new value of attr """ self.update_data() self.make_plot() curdoc().add(self) def getXY(self, celero_result, axis_filter): """Returns the X or Y value as specified by axis_filter""" # TODO: Remove the baseline measurement from the timing results if axis_filter == 'size': return celero_result['data_sizes'] elif axis_filter == 'log2(size)': return np.log2(celero_result['data_sizes']) elif axis_filter == 'log10(size)': return np.log10(celero_result['data_sizes']) elif axis_filter == 'time [ms]': return celero_result['times'] * 1E-3 elif axis_filter == 'throughput [1/sec]': return 1.0 / (celero_result['times'] * 1E-6) elif axis_filter == 'throughput [log2(1/sec)]': return np.log2(1.0 / (celero_result['times'] * 1E-6)) elif axis_filter == 'throughput [log10(1/sec)]': return np.log10(1.0 / (celero_result['times'] * 1E-6)) @classmethod def make_field_ids(self, id_number): """Creates a unique set of named fields for the y, device, and platform""" i = str(id_number) y_id = 'y' + i device_id = 'device' + i platform_id = 'platform' + i return [y_id, device_id, platform_id] def update_data(self): """Called each time that any watched property changes. This updates the sin wave data with the most recent values of the sliders. This is stored as two numpy arrays in a dict into the app's data source property. """ # extract the user's input benchmark = self.benchmarks.value devices = list(device_names[i] for i in self.device_names.active) platforms = list(platform_names[i] for i in self.platform_names.active) x_axis_label = self.x_axis_options.value y_axis_label = self.y_axis_options.value # extract only the results which match this group filtered_results = filter(lambda x: x['benchmark_name'] == benchmark, celero_results) # remove the baseline measurements from the plots filtered_results = filter(lambda x: x['benchmark_name'] != "Baseline", filtered_results) # select the desired devices filtered_results = filter(lambda x: x['extra_data']['AF_DEVICE'] in devices, filtered_results) filtered_results = filter(lambda x: x['extra_data']['AF_PLATFORM'] in platforms, filtered_results) # extract the data sources = dict() result_number = 0 for result in filtered_results: # ensure we don't plot too many results if result_number > MAX_PLOTS: break y_id, device_id, platform_id = self.make_field_ids(result_number) # Extract the results from the benchmark platform = result['extra_data']['AF_PLATFORM'] device = result['extra_data']['AF_DEVICE'] x = self.getXY(result, x_axis_label) y = self.getXY(result, y_axis_label) # store the benchmark results in the self.source object # NOTE: we replicate the device and platform data here so that # it works correctly with the mouseover/hover sources['x'] = x sources[y_id] = y sources[device_id] = [device] * len(x) sources[platform_id] = [platform] * len(x) # increment the counter result_number += 1 # assign the data self.assign_source(sources, self.source0, 0) self.assign_source(sources, self.source1, 1) self.assign_source(sources, self.source2, 2) self.assign_source(sources, self.source3, 3) self.assign_source(sources, self.source4, 4) self.assign_source(sources, self.source5, 5) self.assign_source(sources, self.source6, 6) self.assign_source(sources, self.source7, 7) self.assign_source(sources, self.source8, 8) self.assign_source(sources, self.source9, 9) def assign_source(self, src, dest, index): """Assigns the data from src to the dictionary in dest if the corresponding data exists in src.""" y_id, device_id, platform_id = self.make_field_ids(index) dest.data = dict() if y_id in src: dest.data['x'] = src['x'] dest.data['y'] = src[y_id] dest.data['device'] = src[device_id] dest.data['platform'] = src[platform_id] dest._dirty = True
def modify_doc(doc): def make_dataset(carrier_list, range_start=-60, range_end=120, bin_width=5): 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 Carrier', 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) p.legend.click_policy = 'hide' # Styling p = style(p) return p # Update function takes three default parameters def update(attr, old, new): # Get the list of carriers for the graph carriers_to_plot = [ carrier_selection.labels[i] for i in carrier_selection.active ] # Make a new dataset based on the selected carriers and the # make_dataset function defined earlier new_src = make_dataset(carriers_to_plot, range_start=-60, range_end=120, bin_width=5) # Update the source used the quad glpyhs src.data.update(new_src.data) carrier_selection = CheckboxGroup(labels=available_carriers, active=[0, 1]) carrier_selection.on_change('active', update) controls = WidgetBox(carrier_selection) initial_carriers = [ carrier_selection.labels[i] for i in carrier_selection.active ] src = make_dataset(initial_carriers, range_start=-60, range_end=120, bin_width=5) p = make_plot(src) layout = row(controls, p) doc.add_root(layout)
class HotelApp(VBox): extra_generated_classes = [["HotelApp", "HotelApp", "VBox"]] jsmodel = "VBox" # input selectr = Instance(Select) #check_group = Instance(RadioGroup) check_group = Instance(CheckboxGroup) # plots plot = Instance(GMapPlot) filler = Instance(Plot) filler2 = Instance(Plot) bar_plot = Instance(Plot) legend_plot = Instance(Plot) legend_filler = Instance(Plot) # data source source = Instance(ColumnDataSource) county_source = Instance(ColumnDataSource) # layout boxes checkbox = Instance(VBox) mainrow = Instance(HBox) statsbox = Instance(VBox) mapbox = Instance(VBox) legendbox = Instance(HBox) totalbox = Instance(VBox) # inputs #ticker1_select = Instance(Select) #ticker2_select = Instance(Select) #input_box = Instance(VBoxForm) def make_inputs(self): with open("states.csv") as f: states = [line.strip().split(',') for line in f.readlines()] self.selectr = Select( name='states', value='Choose A State', options=[s[1] for s in states] + ['Choose A State'], ) labels = ["County Averages", "Hotels"] self.check_group = CheckboxGroup(labels=labels, active=[0,1], inline=True) ##Filler plot x_range = Range1d(0, 300) y_range = Range1d(0, 12) self.filler = Plot( x_range=x_range, y_range=y_range, title="", plot_width=300, plot_height=12, min_border=0, **PLOT_FORMATS ) x_range = Range1d(0, 300) y_range = Range1d(0, 18) self.filler2 = Plot( x_range=x_range, y_range=y_range, title="", plot_width=300, plot_height=14, min_border=0, **PLOT_FORMATS ) def make_outputs(self): pass #self.pretext = Paragraph(text="", width=800) def __init__(self, *args, **kwargs): super(HotelApp, self).__init__(*args, **kwargs) self._show_counties = True self._show_hotels = True @classmethod def create(cls): """ This function is called once, and is responsible for creating all objects (plots, datasources, etc) """ # create layout widgets obj = cls() obj.mainrow = HBox() obj.checkbox = VBox(height=50) obj.mapbox = VBox() #obj.bottomrow = HBox() obj.statsbox = VBox( width=500) obj.totalbox = VBox() obj.legendbox = HBox() labels = ["County Average Ratings", "Hotel Locations"] obj.make_inputs() obj.make_outputs() # outputs #obj.pretext = Paragraph(text="", width=500) obj.make_source() obj.make_county_source() lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() #obj.make_plots(lat, lng, zoom, xr, yr) obj.make_plots() # layout obj.set_children() return obj @property def selected_df(self): pandas_df = self.df selected = self.source.selected print "seeing if selected!" if selected: idxs = selected['1d']['indices'] pandas_df = pandas_df.iloc[idxs, :] else: pandas_df = pandas_df.iloc[0:0, :] return pandas_df def make_source(self): self.source = ColumnDataSource(data=self.df) self.source.callback = Callback(args=dict(), code=""" var inds = cb_obj.get('selected')['1d'].indices; var theidx = inds[0]; console.log("yep"); console.log(theidx); $.get( "reviews", {id: theidx}, function( response ) { $( "#section2" ).html( response ); }, "html"); console.log("done"); """) def update_source(self): if self.selectr.value is None or self.selectr.value == 'Choose A State': df = hdata else: df = hdata[hdata['state'] == self.selectr.value] new_data = {} for col in df: new_data[col] = df[col] self.source.data = new_data def make_county_source(self): self.county_source = ColumnDataSource(data=self.countydf) def update_county_source(self): if self.selectr.value is None or self.selectr.value == 'Choose A State': df = county_data else: df = county_data[county_data['state'] == self.selectr.value] new_data = {} for col in df: new_data[col] = df[col] self.county_source.data = new_data #for col in df: # self.county_source.data[col] = df[col] def make_plots(self): self.create_map_plot() self.create_legend() self.populate_glyphs() self.make_bar_plot() def create_legend(self): x_range = Range1d(0, 185) y_range = Range1d(0, 130) text_box = Plot( x_range=x_range, y_range=y_range, title="", plot_width=185, plot_height=130, min_border=0, **PLOT_FORMATS ) FONT_PROPS_SM['text_font_size'] = '11pt' text_box.add_glyph( Text(x=35, y=9, text=['Low Average Rating'], **FONT_PROPS_SM) ) text_box.add_glyph( Rect(x=18, y=18, width=25, height=25, fill_color='#ef4e4d', line_color=None) ) text_box.add_glyph( Text(x=35, y=49, text=['Medium Average Rating'], **FONT_PROPS_SM) ) text_box.add_glyph( Rect(x=18, y=58, width=25, height=25, fill_color='#14a1af', line_color=None) ) text_box.add_glyph( Text(x=35, y=89, text=['High Average Rating'], **FONT_PROPS_SM) ) text_box.add_glyph( Rect(x=18, y=98, width=25, height=25, fill_color='#743184', line_color=None) ) self.legend_plot = text_box ##Filler plot x_range = Range1d(0, 40) y_range = Range1d(0, 100) self.legend_filler = Plot( x_range=x_range, y_range=y_range, title="", plot_width=40, plot_height=100, min_border=0, **PLOT_FORMATS ) def create_map_plot(self): lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() x_range = xr y_range = yr #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6) map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom) #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, plot_width=680, plot_height=600, title=" " ) plot.map_options.map_type="hybrid" xaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') self.plot = plot def populate_glyphs(self): self.plot.renderers=[] self.plot.tools=[] if self._show_counties: print "showing you the counties" #datasource = ColumnDataSource(county_data) #apatch = Patches(xs=county_xs, ys=county_ys, fill_color='white') #apatch = Patches(xs='xs', ys='ys', fill_color='colors', fill_alpha="alpha") apatch = Patches(xs='xs', ys='ys', fill_color='thecolors', fill_alpha='alpha') self.plot.add_glyph(self.county_source, apatch, name='counties') if self._show_hotels: print "showing you the hotels" circle2 = Circle(x="lon", y="lat", size=10, fill_color="fill2", fill_alpha=1.0, line_color="black") circle = Circle(x="lon", y="lat", size=10, fill_color="fill", fill_alpha=1.0, line_color="black") #print "source is ", self.source['lon'], self.source['lat'], self.source['f1ll'] self.plot.add_glyph(self.source, circle2, nonselection_glyph=circle, name='hotels') #county_xs, county_ys = get_some_counties() rndr = self.plot.renderers[-1] pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() box_select.renderers = [rndr] tooltips = "@name" tooltips = "<span class='tooltip-text'>@names</span>\n<br>" tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>" hover = HoverTool(tooltips=tooltips, names=['hotels']) tap = TapTool(names=['hotels']) self.plot.add_tools(pan, wheel_zoom, box_select, hover, tap) overlay = BoxSelectionOverlay(tool=box_select) self.plot.add_layout(overlay) def make_bar_plot(self): # create a new plot y_rr = Range1d(start=0.0, end=5.0) TOOLS = "box_select,lasso_select" #x's and y's based on selected_df sdf = self.selected_df[['names', 'ratings']] xvals = [1.0*i + 0.5 for i in range(0, len(sdf['names']))] rightvals = [1.0*i + 0.85 for i in range(0, len(sdf['names']))] ratings = [r for r in sdf['ratings']] centers = [0.5*r for r in ratings] bottoms = [0]*len(ratings) y_text = [y + 1.0 for y in ratings] width = [1.0] * len(ratings) all_names = [] for n in sdf['names']: short_name = n[:20] idx = short_name.rfind(" ") all_names.append(short_name[:idx]) while len(all_names) > 0 and len(all_names) < 5: all_names.append(" ") bar_plot = figure(tools=TOOLS, width=400, height=350, x_range=all_names, y_range=y_rr, title="Average Rating") bar_plot.title_text_color = "black" bar_plot.title_text_font_size='15pt' bar_plot.title_text_font='Avenir' bar_plot.title_text_align = "right" print "all_names ", all_names bar_colors = [] for r in ratings: if r >= 4.0: bar_colors.append("#743184") elif r >= 3.0: bar_colors.append("#14a1af") else: bar_colors.append("#ef4e4d") bar_plot.xaxis.major_label_orientation = pi/2.3 bar_plot.rect(x=all_names, y=centers, width=width, height=ratings, color=bar_colors, line_color="black") #glyph = Text(x=xvals, y=y_text, text=sdf['names'], angle=pi/4, #text_align="left", text_baseline="middle") #glyphs = [Text(x=x, y=y, text=[n], angle=pi/4, text_align="left", text_baseline="middle") #for x, y, n in zip(xvals, y_text, all_names)] bar_plot.xaxis.major_tick_line_color = None bar_plot.xaxis.minor_tick_line_color = None bar_plot.yaxis.minor_tick_line_color = None bar_plot.xgrid.grid_line_color = None bar_plot.ygrid.grid_line_color = None self.bar_plot = bar_plot def set_children(self): self.children = [self.totalbox] self.totalbox.children = [self.mainrow] self.mainrow.children = [self.statsbox, self.mapbox] self.mapbox.children = [self.plot] #self.checkbox.children = [self.filler, self.check_group, self.filler2] self.statsbox.children = [self.bar_plot, self.legendbox] self.legendbox.children = [self.legend_filler, self.legend_plot] #self.bottomrow.children = [self.pretext] def setup_events(self): super(HotelApp, self).setup_events() if self.source: self.source.on_change('selected', self, 'selection_change') if self.selectr: self.selectr.on_change('value', self, 'input_change') if self.check_group: self.check_group.on_change('active', self, 'check_change') @property def df(self): thedf = return_hotel_data() if self.selectr.value is None or self.selectr.value == 'Choose A State': return thedf else: newdf = thedf[thedf['state'] == self.selectr.value] return newdf @property def countydf(self): thedf = county_data if self.selectr.value is None or self.selectr.value == 'Choose A State': return thedf else: newdf = thedf[thedf['state'] == self.selectr.value] return newdf def selection_change(self, obj, attrname, old, new): #self.make_source() self.update_source() self.make_bar_plot() self.set_children() curdoc().add(self) def check_change(self, obj, attrname, old, new): #Turn on/off the counties/hotel data print "what the heck ", obj, attrname, old, new if 0 in new: self._show_counties = True else: self._show_counties = False if 1 in new: self._show_hotels = True else: self._show_hotels = False self.populate_glyphs() self.set_children() curdoc().add(self) def input_change(self, obj, attrname, old, new): #import pdb;pdb.set_trace() print "source len: ", len(self.source.data['state']) print "county len: ", len(self.county_source.data['names']) self.update_source() self.update_county_source() print "source len: ", len(self.source.data['state']) print "county len: ", len(self.county_source.data['names']) if self.selectr.value is None or self.selectr.value == 'Choose A State': pass else: self.plot.title = self.selectr.value
def templateAcceptedLoanPerRegion(): LABELS = ["Central", "Mid - Atlantic", "NorthEast", "NorthWest", "South", "SouthEast", "SouthWest"] colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#17becf'] data = pd.read_csv(DATA + 'perc_acc_loan_per_region_date_compact.csv') central = data['Central'] / 100 midatl = data['Mid-Atlantic'] / 100 northe = data['Northeast'] / 100 northw = data['Northwest'] / 100 south = data['South'] / 100 southe = data['Southeast'] / 100 southw = data['Southwest'] / 100 date = data['date'] source = ColumnDataSource(data=dict(x=[datetime.strptime(d, '%b-%Y') for d in date.values], Central=central, MidAtlantic=midatl, Northeast=northe, Northwest=northw, South=south, Southeast=southe, Southwest=southw )) props = dict(line_width=4, line_alpha=0.8) p = Figure(x_axis_type="datetime", width=1200, height=380) p0 = p.line('x', 'Central', source=source, legend="Central", line_color=colors[0], **props) p1 = p.line('x', 'MidAtlantic', source=source, legend="Mid - Atlantic", line_color=colors[1], **props) p2 = p.line('x', 'Northeast', source=source, legend="NorthEast", line_color=colors[2], **props) p3 = p.line('x', 'Northwest', source=source, legend="NorthWest", line_color=colors[3], **props) p4 = p.line('x', 'South', source=source, legend="South", line_color=colors[4], **props) p5 = p.line('x', 'Southeast', source=source, legend="SouthEast", line_color=colors[5], **props) p6 = p.line('x', 'Southwest', source=source, legend="SouthWest", line_color=colors[6], **props) p.yaxis.axis_label = 'Percentage of accepted loans' p.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") p.border_fill_color = LIGHT_GREEN p.background_fill_color = LIGHT_GREEN p.legend.background_fill_color = LIGHT_GREEN p.legend.background_fill_alpha = 0.5 checkbox = CheckboxGroup( labels=LABELS, inline=True, active=[0, 1, 2, 3, 4, 5, 6], width=800) code = """ //console.log(cb_obj.active); p0.visible = false; p1.visible = false; p2.visible = false; p3.visible = false; p4.visible = false; p5.visible = false; p6.visible = false; for (i in checkbox.active) { //console.log(cb_obj.active[i]); if (checkbox.active[i] == 0) { p0.visible = true; } else if (checkbox.active[i] == 1) { p1.visible = true; } else if (checkbox.active[i] == 2) { p2.visible = true; } else if (checkbox.active[i] == 3) { p3.visible = true; } else if (checkbox.active[i] == 4) { p4.visible = true; } else if (checkbox.active[i] == 5) { p5.visible = true; } else if (checkbox.active[i] == 6) { p6.visible = true; } } """ checkbox.callback = CustomJS(args=dict(p0=p0, p1=p1, p2=p2, p3=p3, p4=p4, p5=p5, p6=p6, checkbox=checkbox), code=code) boundaries = open(DATA + 'boundaries.json').read() states = json.loads(boundaries) region_state = pd.read_csv(DATA + 'region-state.csv', header=0) region_state = region_state.set_index('state') state_xs = [states[code]["lons"] for code in states] state_ys = [states[code]["lats"] for code in states] name = states.keys() colors_state = [] for i in name: if i != 'AK' and i != 'HI': reg = region_state.loc[i]['region'] if reg == "Central": colors_state.append(colors[0]) elif reg == "Mid-Atlantic": colors_state.append(colors[1]) elif reg == "Northeast": colors_state.append(colors[2]) elif reg == "Northwest": colors_state.append(colors[3]) elif reg == "South": colors_state.append(colors[4]) elif reg == "Southeast": colors_state.append(colors[5]) elif reg == "Southwest": colors_state.append(colors[6]) source = ColumnDataSource(data=dict( x=state_xs, y=state_ys, name=name, colors=colors_state, )) q = figure(title="", toolbar_location=None, plot_width=300, plot_height=160 ) q.xaxis.visible = False q.yaxis.visible = False q.xgrid.grid_line_color = None q.ygrid.grid_line_color = None q.min_border_left = False q.min_border_right = False q.min_border_top = False q.min_border_bottom = False q.border_fill_color = LIGHT_GREEN q.background_fill_color = LIGHT_GREEN q.patches('x', 'y', source=source, fill_color='colors', fill_alpha=0.9, line_color="white", line_width=0.1) layout = VBox(q, checkbox, p) # show(layout) script, div = components(layout) return script, div
x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value="Precision @ N") y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="Item Coverage") num_preds = Select(title="N", value='1000', options=['All', '100', '1000']) alg_type = Select(title = "Recommender Type", value='All', options = ['All', 'All CF', 'All CB', 'cf_mllib', 'cf_user', 'cf_item', 'cb_vect', 'cb_kmeans']) u_button = Button(label="User Vector") c_button = Button(label="Content Vector") #initialize to movielens labels = ['pos_ratings', 'ratings', 'ratings_to_interact'] c_labels = ["genre"] dataset_type = Select(title = "Dataset", value='movielens_1m', options = ['All', 'All MovieLens', 'movielens_1m', 'Last_FM', 'git']) checkbox_button_group = CheckboxGroup(labels=labels, active = [0,1,2]) checkbox_button_group_content = CheckboxGroup(labels=c_labels, active = [0]) hover = HoverTool(tooltips=[ ("Dataset","@dataset"), ("User Vector","@user_vector"), ("Content Vector", "@content_vector"), ("Algorithm", "@alg_type"), ("Num_preds", "@num_run") ]) p = Figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover]) p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None) def select_run():
p.xgrid.grid_line_color = None cities = [''] df = pd.read_csv('data/Food/df_transformed.csv') # names = [str(n).split(',')[0].strip() for n in df.MMSANAME] # # df['city'] = names # # df = df.loc[df.city != 'nan', :].copy() ######################### checkbox_cities_labels = list(df.city.unique()) city_selection = CheckboxGroup(labels=checkbox_cities_labels, active=[]) ######################### columns_to_select = [c for c in df.columns] # if c.startswith('_')] # columns_to_select = ['city'] + columns_to_select # df = df.loc[:, columns_to_select] cols = list(df.columns) cols.remove('city') for c in cols: df[c] = pd.to_numeric(df[c], errors='coerce') df = df.fillna(value=-1.0) #########################
source = TextInput(title="Source coordinates (hh:mm:ss dd:mm:ss)", value="00:00:00 00:00:00") epoch = TextInput(title="Starting UTC time (DD/MM/YYYY HH:MM)", value="01/01/2018 00:00") duration = Slider(title="Duration of the observation (hours)", value=8.0, start=1.0, end=30.0, step=0.25) elevation_limit = Slider(title="Lowest elevation (degrees)", value=10.0, start=0.0, end=50.0, step=5.0) # Add checkboxes: include Ar, include eMERLIN, include VLBA, include LBA. outstations = CheckboxGroup(labels=["eMERLIN", "VLBA", "LBA", "KVN"], active=[]) # Reading all stations all_stations = Station.stations_from_file( path.dirname(__file__) + '/station_location.txt') # Default parameters source_coord = coord.SkyCoord('00h00m00s +00d00m00s') times_obs = get_obs_times(get_time('01/01/2018 00:00'), duration.value) selected_stations = copy.deepcopy(stations[type_array.value]) selected_all_stations = stations['EVN'] + stations['eMERLIN'] + stations['VLBA'] + stations['LBA']\ + stations['KVN'] # Set up callbacks def update_data(attrname, old, new):
def histogram_tab(meta): # 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): types_to_plot = [ type_selection.labels[i] for i in type_selection.active ] new_src = make_dataset(types_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) # Variable types and colors available_type = list(set(meta['Type'])) available_type.sort() type_colors = Category20_16 type_colors.sort() type_selection = CheckboxGroup(labels=available_type, active=[0, 1]) type_selection.on_change('active', update) binwidth_select = Slider(start=1, end=30, step=1, value=5, title='Bin Width') binwidth_select.on_change('value', update) range_select = RangeSlider(start=-60, end=180, value=(-60, 120), step=5, title='Range') range_select.on_change('value', update) # Initial carriers and data source initial_carriers = [ type_selection.labels[i] for i in type_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(type_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
button = Button(label="Push button", icon=Icon(name="check"), type="primary") button.on_click(button_handler) toggle = Toggle(label="Toggle button", type="success") toggle.on_click(toggle_handler) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_action="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(radio_group_handler) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(radio_button_group_handler) vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group]) document.add(vbox) session.store_document(document)
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