def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'): source = ColumnDataSource(data=initData) selectDOW = Select(title="Days:", value="Monday", options=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]) selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"]) model = dict(source=source, select_dow = selectDOW, select_ut = selectUT) plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime") plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=model, code=""" var dayOfWeek = select_dow.get('value') var userType = select_ut.get('value') var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if(xmlhttp.status == 200){ var data = source.get('data'); var result = JSON.parse(xmlhttp.responseText); var temp=[]; for(var date in result.x) { temp.push(new Date(result.x[date])); } data['x'] = temp; data['y'] = result.y; source.trigger('change'); } else if(xmlhttp.status == 400) { alert(400); } else { alert(xmlhttp.status); } } }; var params = {dow:dayOfWeek, ut:userType}; url = "/select?" + jQuery.param( params ); xmlhttp.open("GET", url, true); xmlhttp.send(); """) selectDOW.callback = callback selectUT.callback = callback layout = vform(selectDOW, selectUT, plot) script, div = components(layout) html = readHtmlFile(fileName) html = insertScriptIntoHeader(html, script) html = appendElementContent(html, div, "div", "bokehContent") return html
def add_dropdown(self, df): ''' Adds a dropdown to bokeh line chart Inputs: df (pd.DataFrame) DataFrame that contains data for all the traces of the graph ''' assert isinstance(df, pd.DataFrame) data = df.to_dict(orient='list') data['x'] = df.index.tolist() source_available = ColumnDataSource(data=data) select = Select(title="Country", options=self.df.columns.tolist(), value=self.country) select.callback = CustomJS(args=dict( source_visible=self.source_visible, source_available=source_available), code=""" var data_visible = source_visible.data; var data_available = source_available.data; var f = cb_obj.value; data_visible.y = data_available[f]; source_visible.change.emit(); """) return select
def test_callback_property_executes(self, bokeh_model_page): select = Select(options=["Option 1", "Option 2", "Option 3"], css_classes=["foo"]) select.callback = CustomJS(code=RECORD("value", "cb_obj.value")) page = bokeh_model_page(select) el = page.driver.find_element_by_css_selector('.foo select') el.click() el = page.driver.find_element_by_css_selector('.foo select option[value="Option 3"]') el.click() results = page.results assert results['value'] == 'Option 3' assert page.has_no_console_errors()
def popByGroup(): df1 = pd.read_csv('BokehApp/Data/ageGroupYear.csv', delimiter=',', index_col='Age Groups') df1['color'] = viridis(len(df1.index)) source = ColumnDataSource(data=dict(x=df1.index, _2009=df1['2009'], _2010=df1['2010'], _2011=df1['2011'], _2012=df1['2012'], _2013=df1['2013'], _2014=df1['2014'], _2015=df1['2015'], _2016=df1['2016'], _2017=df1['2017'], _2018=df1['2018'], c=df1['color'], _2009a=df1['2009'])) source1 = ColumnDataSource(data=dict(x=df1.index, _2016=df1['2016'],c=df1['color'])) p = figure(x_range=list(df1.index.values), plot_height=350, plot_width=550,title='Irish Population Breakdown by Age Group', tools='pan, wheel_zoom, box_zoom, reset') p.vbar(x='x', top='_2009a', width=0.5, source=source, color='c') #plot style p.xaxis.major_label_orientation = 45 p.grid.grid_line_color=None p.outline_line_color=None p.axis.major_label_text_font_style = 'bold' p.toolbar.autohide = True hoverp = HoverTool() hoverp.tooltips=[('Group Population', '@_2009a')] p.add_tools(hoverp) tick_labels_p = {'100':'100K','200':'200K','300':'300K','400':'400K'} p.yaxis.major_label_overrides = tick_labels_p select = Select(title="Year:", align='start', value='_2009a', width=80, height=30, options=['_2009','_2010', '_2011', '_2012','_2013','_2014','_2015','_2016','_2017','_2018']) callback = CustomJS(args={'source':source},code=""" console.log(' changed selected option', cb_obj.value); var data = source.data; // allocate column data['_2009a'] = data[cb_obj.value]; // register the change source.change.emit(); """) select.callback = callback layout = row(select,p) return layout
def create_figure(username): MID_BLUE = "#91c8ff" PALE_BLUE = "#add8e6" ANGRY_RED = "#ef5252" WHITE = "#FFFFFF" HOUR = 60 * 60 * 1000 # 1hr in miliseconds data = list(mongo.db.records.find({"user": username}).sort('date', 1)) df = pd.io.json.json_normalize(data).fillna(0) df.set_index('date') df_indices = list(df) # TODO - dict of paired metrics to populate bar height and alpha # Plot Setup metric = Select(title='metric', value='metrics.insomnia', options=df_indices) factor1 = Select(title='factor1', value='misc.carb', options=df_indices) factor2 = Select(title='factor2', value='misc.coffee', options=df_indices) jitter_slider = Slider(title="Jitter", start=0, end=1, value=0, step=0.1) source_raw = ColumnDataSource(df.drop(['_id'], axis=1)) source = ColumnDataSource( data=dict(date=df['date'], metric=source_raw.data[metric.value], factor1=source_raw.data[factor1.value], factor2=source_raw.data[factor2.value])) callback = CustomJS(args=dict(source=source, source_raw=source_raw), code=""" var value = cb_obj.value; var title = cb_obj.title; source.data[title] = source_raw.data[value]; source.change.emit(); """) metric.callback = callback factor1.callback = callback factor2.callback = callback p_timeline = figure( x_axis_type="datetime", y_axis_label='Variable', plot_height=300, plot_width=1000, tools='pan,box_zoom,reset', ) p_factor1 = figure(x_axis_type="datetime", x_range=p_timeline.x_range, plot_height=100, plot_width=1000, tools='pan,box_zoom,hover,reset') p_factor2 = figure(x_axis_type="datetime", x_range=p_timeline.x_range, plot_height=100, plot_width=1000, tools='pan,box_zoom,hover,reset') pv = figure(toolbar_location=None, plot_width=200, plot_height=p_timeline.plot_height, y_range=p_timeline.y_range, min_border=10, y_axis_location="right") p3 = figure(plot_height=400, plot_width=400, tools='pan,box_zoom,hover,reset') # Timeline p_timeline.vbar(x=df['date'], top=df['metrics.sleep_hours'], alpha=(df['metrics.sleep_quality'] - 2) / 10, color=PALE_BLUE, width=20 * HOUR) p_timeline.vbar(x='date', top='metric', alpha=0.8, color=ANGRY_RED, source=source, width=20 * HOUR) inc = df['metrics.afternoon'] >= df['metrics.morning'] dec = df['metrics.morning'] > df['metrics.afternoon'] p_timeline.line(df['date'], df[['metrics.morning', 'metrics.afternoon']].mean(axis=1), line_width=6, color=PALE_BLUE) p_timeline.segment(df.date[inc], df['metrics.morning'][inc], df.date[inc], df['metrics.afternoon'][inc], color=WHITE, line_width=4, line_cap='square') p_timeline.segment(df.date[dec], df['metrics.morning'][dec], df.date[dec], df['metrics.afternoon'][dec], color=ANGRY_RED, line_width=4, line_cap='square') # Histogram - metrics # TODO - reflect selected metric; reflect values selected on scatter plot vhist, vedges = np.histogram(df['metrics.sleep_quality'].fillna(0), bins=10) pv.ygrid.grid_line_color = None pv.quad(left=0, bottom=vedges[:-1] + 0.05, top=vedges[1:] - 0.05, right=vhist, color=PALE_BLUE) # Factor plots p_factor1.vbar(x='date', top='factor1', color=WHITE, source=source, alpha=1, width=20 * HOUR) p_factor2.vbar(x='date', top='factor2', color=MID_BLUE, source=source, alpha=1, width=20 * HOUR) # Scatter plot p3.circle(x=jitter('metric', width=0.5), y='factor1', color=WHITE, size=8, alpha=0.5, source=source) p3.circle(x=jitter('metric', width=0.5), y='factor2', color=MID_BLUE, size=8, alpha=0.5, source=source) p3.xaxis.axis_label = 'Selected Metric' p3.yaxis.axis_label = 'Factor1 (white), Factor2 (blue)' controls = widgetbox([metric, factor1, factor2, jitter_slider], width=200) main_row = row(p_timeline, pv) bottom_row = row(controls, Spacer(width=150, height=0), p3) layout = column(main_row, p_factor1, p_factor2, bottom_row) # Add theme to document theme_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'theme.yaml') theme = Theme(theme_path) doc = curdoc() doc.theme = theme return layout
def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'): source = ColumnDataSource(data=initData) selectDOW = Select(title="Days:", value="Monday", options=[ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]) selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"]) model = dict(source=source, select_dow=selectDOW, select_ut=selectUT) plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime") plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=model, code=""" var dayOfWeek = select_dow.get('value') var userType = select_ut.get('value') var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if(xmlhttp.status == 200){ var data = source.get('data'); var result = JSON.parse(xmlhttp.responseText); var temp=[]; for(var date in result.x) { temp.push(new Date(result.x[date])); } data['x'] = temp; data['y'] = result.y; source.trigger('change'); } else if(xmlhttp.status == 400) { alert(400); } else { alert(xmlhttp.status); } } }; var params = {dow:dayOfWeek, ut:userType}; url = "/select?" + jQuery.param( params ); xmlhttp.open("GET", url, true); xmlhttp.send(); """) selectDOW.callback = callback selectUT.callback = callback layout = vform(selectDOW, selectUT, plot) script, div = components(layout) html = readHtmlFile(fileName) html = insertScriptIntoHeader(html, script) html = appendElementContent(html, div, "div", "bokehContent") return html
) # update selection in other plots and fill the table after using the box_select tool fig_list[0].select_one(BoxSelectTool).callback = CustomJS( args=dict(txt=select_text), code=box_select_code ) # make the BoxSelect tool update the 'txt' Div widget with the currently selected range of dates. fig_list[1].select_one(BoxSelectTool).callback = CustomJS( args=dict(txt=select_text), code=box_select_code ) # make the BoxSelect tool update the 'txt' Div widget with the currently selected range of dates. input_0.callback = CustomJS( args=dict( S_all=all_source, S_main=main_source_list[-1], s2=main_source_list[-2], S_fill=main_source_list[-3], S_save=save_source_list[-1], mainy=fig_list[0].y_range, main_laby=fig_list[0].yaxis[0], fill_lab=fig_list[2].yaxis[0], dt=data_table, ), code=input_code + key_source_code.replace('cb_obj', 'S_main')) input_1.callback = CustomJS( args=dict( S_all=all_source, S_main=main_source_list[-2], s2=main_source_list[-1], S_fill=main_source_list[-3], S_save=save_source_list[-1], mainy=fig_list[1].y_range,
spark_timer = Slider(value=0, start=0, end=100, step=1, title="Title") button_list = ["Start_Button", "Stop_Button", "Mass_of_m1", "Spark"] button_call = Select(title="Button call", options=sorted(button_list), value="Start_Button", width=200) select_code = """ to_show = cb_obj.value; options = cb_obj.options for (i=0;i<options.length;i++) { box = document.getElementsByClassName(options[i])[0]; if (!box.className.includes("hidden")) {box.className+=" hidden";} if (box.className.includes(to_show)) {box.className=box.className.replace(" hidden","");} } """ button_call.callback = CustomJS(code=select_code) box_1 = widgetbox(start_button, css_classes=['Start_Button']) box_2 = widgetbox(stop_button, css_classes=['Stop_Button', 'hidden']) box_3 = widgetbox(m1_text, css_classes=['Mass_of_m1', 'hidden']) box_4 = widgetbox(spark_timer, css_classes=['Spark', 'hidden']) grid = gridplot([[button_call], [box_1, box_2, box_3, box_4]], toolbar_location=None) curdoc().add_root(grid)
select.callback = CustomJS(args=dict(source=fill_source, source1=source1, source2=source2), code=codes) select = Select(options=['source1', 'source2'], value='source1') codes = """ var f = cb_obj.value; var sdata = source.data; var data1 = source1.data; var data2 = source2.data; for (key in data2) { sdata[key] = []; for (i=0;i<data2[key].length;i++){ sdata[key].push(data2[key][i]); } } console.log("Hello world"); source.change.emit(); """ select.on_change('value', newsource2) select.callback = CustomJS(args=dict(source=fill_source, source1=source1, source2=source1), code=codes) curdoc().add_root(column(widgetbox(select), fig, width=1100))
def create(default_clf): # Create ColumnDataSources to store the examples in example_sources_train = create_sources(data.X_TRAIN, data.Y_TRAIN) example_sources_test = create_sources(data.X_TEST, data.Y_TEST) # Figure # ------------------------------------------------------------------------- tools = [ HoverTool(tooltips=[("Index", "$index"), ("X", "@x"), ("Y", "@y")]), "pan, wheel_zoom, box_select, lasso_select, reset, save" ] fig = figure(tools=tools, plot_width=1110, plot_height=600, x_range=data.get_padded_range(data.X_TRAIN_TEST[:, 0]), y_range=data.get_padded_range(data.X_TRAIN_TEST[:, 1]), toolbar_location="right", background_fill_color="#fafafa", active_drag="pan", active_scroll="wheel_zoom", logo=None) fig.xaxis.visible = False fig.yaxis.visible = False fig.border_fill_color = None # Decision region # ------------------------------------------------------------------------- default_clf.train({ default_clf.slider1.title: default_clf.slider1.value, default_clf.slider2.title: default_clf.slider2.value }) d, x_min, y_min, dw, dh = default_clf.get_decision_boundary() source_region = ColumnDataSource(data={'d': [d]}) fig.image(image='d', x=x_min, y=y_min, dw=dw, dh=dh, source=source_region, palette=['#DC9C76', '#D6655A']) # Scatter plot # ------------------------------------------------------------------------- colors = ["#D9CFB0", "#42282E"] markers = ["circle", "triangle"] scatters = {} for i, (train_source, test_source, color, marker) in enumerate( zip(example_sources_train, example_sources_test, colors, markers)): scatters['train_scatter_class_%s' % i] = fig.scatter( x='x', y='y', source=train_source, size=10, fill_color=color, fill_alpha=.9, line_color='#111111', line_alpha=.9, marker=marker) scatters['test_scatter_class_%s' % i] = fig.scatter( x='x', y='y', source=test_source, size=10, fill_color=color, fill_alpha=.3, line_color='#111111', line_alpha=.3, marker=marker) # Checkboxes to show/hide data points # ------------------------------------------------------------------------- checkbox_show_points = CheckboxGroup( labels=["Show training data", "Show testing data"], active=[0, 1], callback=CustomJS(args=scatters, code=""" var show_training_data = cb_obj.active.indexOf(0) !== -1; var show_testing_data = cb_obj.active.indexOf(1) !== -1; var max_classes_to_check = 20; var source_name_train, source_name_test; var source_train, source_test; for (var class_nr=0; class_nr < max_classes_to_check; ++class_nr) { try { source_name_train = "train_scatter_class_"+class_nr.toString(); source_name_test = "test_scatter_class_"+class_nr.toString(); source_train = eval(source_name_train); source_test = eval(source_name_test); source_train.visible = show_training_data; source_test.visible = show_testing_data; } catch (e) { // Do nothing. // We end up in here if eval() name is undefined. } } """)) # Sliders # ------------------------------------------------------------------------- slider1, slider2 = default_clf.slider1, default_clf.slider2 slider1.width, slider2.width = 800, 800 # Classifier select box # ------------------------------------------------------------------------- select_clf = Select(title='Classifier', value=default_clf.name, options=Classifiers.get_classifier_names()) # Classifier select box callback # ------------------------------------------------------------------------- select_clf.callback = CustomJS(args=dict(slider1=slider1, slider2=slider2), code=""" var selected_clf = cb_obj.value; jQuery.ajax({ type: 'POST', url: '/get_classifier_info', data: {'newly_selected_clf': selected_clf}, dataType: 'json', success: function (json_from_server) { // Sliders have 'title' attribute but changing it // has no effect. Thus, change the label through jQuery. var slider1_label = $("label[for='" + slider1.id + "']"); var slider2_label = $("label[for='" + slider2.id + "']"); slider1_label.html(json_from_server.slider1.title + ':'); slider2_label.html(json_from_server.slider2.title + ':'); slider1.start = json_from_server.slider1.start; slider1.end = json_from_server.slider1.end; slider1.step = json_from_server.slider1.step; slider1.value = json_from_server.slider1.value; slider2.start = json_from_server.slider2.start; slider2.end = json_from_server.slider2.end; slider2.step = json_from_server.slider2.step; slider2.value = json_from_server.slider2.value; }, error: function() { alert("Oh no, something went wrong."); } }); """) # Slider callback # ------------------------------------------------------------------------- general_slider_callback = CustomJS(args=dict(select_clf=select_clf, slider1=slider1, slider2=slider2, source_region=source_region), code=""" var clf_name = select_clf.value; // Bokeh automatically adds ':' and whitespace to Slider label. // Let's remove them. var param1_name = $("label[for='" + slider1.id + "']").html().replace( ":", "").trim(); var param2_name = $("label[for='" + slider2.id + "']").html().replace( ":", "").trim(); var param1_val = slider1.value; var param2_val = slider2.value; jQuery.ajax({ type: 'POST', url: '/get_new_decision_boundary', data: {'clf_name': clf_name, 'param1_name': param1_name, 'param1_val': param1_val, 'param2_name': param2_name, 'param2_val': param2_val}, dataType: 'json', success: function (json_from_server) { source_region.data.d = [json_from_server.new_dec_bound]; source_region.trigger('change'); accuracy_text.text = "<h2 class='accuracy'>" + "Train accuracy: " + json_from_server.train_acc + "<br>" + "Test accuracy: " + json_from_server.test_acc + "</h2>"; }, error: function() { alert("Oh no, something went wrong."); } }); """) slider1.callback = general_slider_callback slider2.callback = general_slider_callback # Accuracy textbox # ------------------------------------------------------------------------- accuracy_text = Div(text="", width=600, height=100) general_slider_callback.args["accuracy_text"] = accuracy_text # Generate layout, HTML, CSS and JS # ------------------------------------------------------------------------- layout = column(row(select_clf, slider1), row(checkbox_show_points, slider2), row(fig), row(accuracy_text)) script, div = components(layout) return script, div, INLINE.render_js(), INLINE.render_css()
def popOverall(): df1 = pd.read_csv('BokehApp/Data/ageGroupYear.csv', delimiter=',') df1['color'] = viridis(len(df1.index)) df1['2009.'] = df1['2009'].values source1 = ColumnDataSource(data=dict(df1)) p1 = figure(x_range=list(df1['Age Groups'].values), plot_height=300, plot_width=500,title='Irish Population Breakdown by Age Group', tools='pan, wheel_zoom, box_zoom, reset', toolbar_location='right') p1.vbar(x='Age Groups', top='2009.', width=0.5, source=source1, color='color') #plot style p1.xaxis.major_label_orientation = 45 #p1.grid.grid_line_color=None p1.outline_line_color=None p1.axis.major_label_text_font_style = 'bold' #p1.toolbar.autohide = True p1.grid.grid_line_alpha = 0.6 p1.grid.grid_line_dash = 'dotted' p1.grid.grid_line_dash_offset = 5 p1.grid.grid_line_width = 2 hoverp1 = HoverTool() hoverp1.tooltips=[('Group Population', '@2009')] p1.add_tools(hoverp1) tick_labels_p1 = {'100':'100K','200':'200K','300':'300K','400':'400K'} p1.yaxis.major_label_overrides = tick_labels_p1 df = pd.read_csv('BokehApp/Data/OverAll.csv', delimiter=',', index_col='Year') df['color'] = viridis(len(df.index)) xrange = (2009,2018) xrange yrange = (df['Population'].min(), df['Population'].max()) source = ColumnDataSource(df) p = figure(plot_height=300, plot_width=400,title='Irish Population Growth by Year', y_range=Range1d(*yrange),tools='pan, wheel_zoom, box_zoom, reset', toolbar_location='above') p.vbar(x='Year', top='Population', source=source, width=0.5, color='color') #plot style #p.xaxis.major_label_orientation = 45 #p.grid.grid_line_color=None #p.x_range.start = 2009 p.x_range.end = 2018.5 p.grid.grid_line_alpha = 0.6 p.y_range.start = 4500 p.y_range.end = df['Population'].max()*1.003 p.outline_line_color=None p.axis.major_label_text_font_style = 'bold' p.toolbar.autohide = True p.grid.grid_line_dash = 'dotted' p.grid.grid_line_dash_offset = 5 p.grid.grid_line_width = 2 p.toolbar.autohide=True #p.yaxis.axis_line_color = None hoverp = HoverTool() hoverp.tooltips=[('Year','@Year'),('Population', '@Population{int}')] p.add_tools(hoverp) tick_labels_p = {'4500':'450M','4550':'455M','4600':'460M','4650':'465M','4700':'470M','4750':'475M', '4800':'480M','4850':'485M'} p.yaxis.major_label_overrides = tick_labels_p select = Select(title="Year:", align='center', value='2009.', width=60, height=25, options=['2009','2010', '2011', '2012','2013','2014','2015','2016','2017','2018']) p1.title.text = 'Irish Population by Age Group ' + str(select.value) callback = CustomJS(args={'source':source1, 'title':p1.title},code=""" console.log(' changed selected option', cb_obj.value); var data = source.data; title.text = 'Irish Population by Age Group ' + cb_obj.value // allocate column data['2009.'] = data[cb_obj.value]; // register the change source.change.emit()""") select.callback = callback layout = row(p,select, p1, margin=5) return layout
} source_sf_tag.trigger('change'); source_abq_tag.trigger('change'); source_det_tag.trigger('change'); source_sf_price.trigger('change'); source_abq_price.trigger('change'); source_det_price.trigger('change'); source_sf_rate.trigger('change'); source_abq_rate.trigger('change'); source_det_rate.trigger('change'); source_sf_area.trigger('change'); source_abq_area.trigger('change'); source_det_area.trigger('change'); """) select_city.callback = callback select_var.callback = callback plot.grid.grid_line_width = 2 plot.xaxis.major_label_text_font_size="12pt" plot.xaxis.axis_label = 'Variable' plot.yaxis.axis_label = 'Count' layout_bar1 = column(row(select_city, select_var), plot) #####!!!!prepare the data for bar plot2 from collections import Counter from filter_dataframe import * def var_by_tag(df, tag, var='price'): df_tag = find_by_tag(df, d[tag])