def init_basic_layout(self): self.env.tabs_widget_col = column(name='tabs_widget_col', children=[Spacer()]) self.env.doc.add_root(self.env.tabs_widget_col) self.env.sidebar = column( name='sidebar_col', width=250, children=[Spacer()], css_classes=['sidebar_col'], ) self.env.doc.add_root(self.env.sidebar)
def plot_balance_report(user_id): current_month = get_current_month() current_month_trends = data_observer.get_balances_trends( user_id, current_month["period"]) current_title = f"Изменение остатков {current_month['name']}" last_month = get_last_month() last_month_trends = data_observer.get_balances_trends( user_id, last_month["period"]) last_title = f"Изменение остатков {last_month['name']}" current_month_figure = make_trends_figure(current_month_trends, current_title, current_month) last_month_figure = make_trends_figure(last_month_trends, last_title, last_month) vertical_space = round(current_month_figure.plot_height * 0.1) return column( current_month_figure, Spacer(height=vertical_space), last_month_figure )
def reset_bokeh(self): ''' Reset the layout values in order to prepare them for the next loading time ''' lg.info('-- RESET VALUES ON THE FORM (> SPACERS)') # The problem is >> I can update only the children of elements # So the main form elements should have children >> a row or column for instance # Keep the bridge row tabs_widget_col = self.env.doc.select_one(dict(name='tabs_widget_col')) tabs_widget_col.children.clear() tabs_widget_col.children.append(Spacer()) sidebar_col = self.env.doc.select_one(dict(name='sidebar_col')) sidebar_col.children.clear() sidebar_col.children.append(Spacer()) self.reset_env()
def plot_expense_reports(user_id): cats_plot = plot_categories(user_id) trends_current_plot = plot_expense_trends( user_id, get_current_month() ) trends_last_plot = plot_expense_trends( user_id, get_last_month() ) vertical_space = round(cats_plot.plot_height * 0.2) return column(cats_plot, Spacer(height=vertical_space), trends_current_plot, Spacer(height=vertical_space), trends_last_plot, Spacer(height=vertical_space) )
def on_lvl_select(self, attr, old, new): """ Callback for ``self.lvl_select``. The method re-searches the available geojson's and sets the options of ``self.id_select`` to the newly selected level, while trying to remain in the same dataset. If the dataset is not in the selected NUTS level, the selected and displayed dataset is changed. This method triggers a redraw of the map and the observation plot. :param attr: attribute that triggered this callback :param old: the old value of the attribute :param new: the new value of the attribute """ eurostats = self.get_eurostats_geojson_list() # collect ID by level self.set_available_ids() old_selection = self.id_select.value self.id_select.options = self.available_ids[new] if old_selection in self.available_ids[new]: self.id_select.value = old_selection # TODO: Check empty cases!! if new == 'Custom': self.current_dataset = gpd.GeoDataFrame.from_file( self.dataset_path_custom_prefix + self.id_select.value + ".geojson") else: self.current_dataset = gpd.GeoDataFrame.from_file( self.dataset_path_prefix + "nuts_" + new[-1] + "/" + self.id_select.value + ".geojson") self.update_datasource(self.current_map_CDS, self.current_dataset, new, self.id_select.value, 10) style = {"font-size": "20px"} unit = self.current_map_CDS.data['unit'][0] mean = np.mean(self.current_map_CDS.data['observation']) deviation = np.std(self.current_map_CDS.data['observation']) p_mean_title = Div(text="Mean:", style=style) p_mean_value = Div(text="{:10,.3} {}".format(mean, unit), style=style) p_deviation_title = Paragraph(text="Standard Deviation:", style=style) p_deviation_value = Paragraph(text="{:10,.3} {}".format(deviation, unit), style=style) hist, edges = np.histogram( self.current_map_CDS.data['observation'], density=True, bins=30) p2 = figure(height=300) p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], color=PuBu[7][2]) self.layout.children[2] = column( row(p_mean_title, p_mean_value), row(p_deviation_title, p_deviation_value), Spacer(height=46), p2, width=500)
def _set_textbox(self, specs): fig = column(row(Spacer(height=specs.height)), row(Spacer(width=specs.width), self._paragraph)) return fig
def tap_callback(self, attr, old, new): if len(new["1d"]["indices"]) > 0: new_data = {} new_data['observation'] = [0] new_data['NUTS_ID'] = ['0'] new_data['unit'] = [' '] new_data['color'] = ['#000000'] old_data = self.current_map_CDS.data temporal_data = {'NUTS_ID': [], 'observations': [], 'periods': [], 'units': [], 'colors': []} for indices in new["1d"]["indices"]: new_data['observation'].append(old_data['observation'][indices]) new_data['unit'].append(old_data['unit'][indices]) new_data['NUTS_ID'].append(old_data['NUTS_ID'][indices]) new_data['color'].append(self.color_by_id[old_data['NUTS_ID'][indices]]) raw_index = self.current_dataset.loc[:, :][ self.current_dataset.loc[:, 'NUTS_ID'] == old_data['NUTS_ID'][indices]].index[0] observations = self.current_dataset.loc[raw_index, :]['OBSERVATIONS'][self.id_select.value] sorted_obs = sorted(observations, key=lambda k: k['period']) periods = [] for timestamp in [k['period'] for k in sorted_obs]: s = timestamp.split('-') periods.append(date(int(s[0]), int(s[1]), int(s[2]))) temporal_data['NUTS_ID'].append(old_data['NUTS_ID'][indices]) temporal_data['periods'].append(periods) temporal_data['observations'].append([float(k['value']) for k in sorted_obs]) temporal_data['units'].append([k['unit'] for k in sorted_obs]) temporal_data['colors'].append(PuBu[7][2]) testdata_source = ColumnDataSource(new_data) # dont work with to large datasets x_label = "Region" y_label = "Selected Indicator in {}".format(new_data['unit'][1]) title = "Visualisation" p2 = figure(plot_width=500, plot_height=300, tools="save", x_axis_label=x_label, y_axis_label=y_label, title=title, x_minor_ticks=2, x_range=testdata_source.data["NUTS_ID"], y_range=ranges.Range1d(start=min(testdata_source.data['observation']), end=max(testdata_source.data['observation']))) labels = LabelSet(x='NUTS_ID', y='observation', text='observation', level='glyph', x_offset=-13.5, y_offset=0, source=testdata_source, render_mode='canvas') p2.vbar(source=testdata_source, x='NUTS_ID', top='observation', bottom=0, width=0.3, color='color') p2.toolbar.logo = None p3 = figure(plot_width=500, plot_height=300, tools="save", x_axis_type='datetime', y_axis_label=y_label, x_axis_label='Period', title='Time Series' ) p3.toolbar.logo = None for index, value in enumerate(temporal_data['NUTS_ID']): tmp_CDS = ColumnDataSource( {'NUTS_ID': [value]*len(temporal_data['observations'][index]), 'observations': temporal_data['observations'][index], 'periods': temporal_data['periods'][index], 'units': temporal_data['units'][index] }) p3.line(x='periods', y='observations', color=self.color_by_id[value], source=tmp_CDS) da = pd.DataFrame(np.diff(np.log(tmp_CDS.data['observations']))) #da.index = tmp_CDS.data['periods'] #model = pf.GARCH(p=1, q=1, data=da) #model.adjust_prior(1, pf.TruncatedNormal(0.01, 0.5, lower=0.0, upper=1.0)) #model.adjust_prior(2, pf.TruncatedNormal(0.97, 0.5, lower=0.0, upper=1.0)) #res = model.fit('M-H', nsims=20000) #print('success') #pre_data = model.predict(10) #print(pre_data) self.layout.children[2] = column(Spacer(height=144), p2, p3) else: style = {"font-size": "20px"} unit = self.current_map_CDS.data['unit'][0] mean = np.mean(self.current_map_CDS.data['observation']) deviation = np.std(self.current_map_CDS.data['observation']) p_mean_title = Div(text="Mean:", style=style) p_mean_value = Div(text="{:10,.3} {}".format(mean, unit), style=style) p_deviation_title = Paragraph(text="Standard Deviation:", style=style) p_deviation_value = Paragraph(text="{:10,.3} {}".format(deviation, unit), style=style) hist, edges = np.histogram( self.current_map_CDS.data['observation'], density=True, bins=30) p2 = figure(height=300) p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], color=PuBu[7][2]) self.layout.children[2] = column( row(p_mean_title, p_mean_value), row(p_deviation_title, p_deviation_value), Spacer(height=46), p2, width=500)
description, row( column( row( time_plot, column( def_undef_choices_text, mass_input, stiffness_input, solve_system_button ) ), row( column(mode_one,modes[1].frequency_text,modes[1].multiplier_text), column(mode_two,modes[0].frequency_text,modes[0].multiplier_text), Spacer(width=80) ) ), column( Erdbebenzonen_text,Erdbebenzonen_choices, Bedeutungsbeiwert_text,Bedeutungsbeiwert_choices, untergrundParamter_text,untergrundParamter_choices ), column( ERSplot, ERS_plot_text, calculate_ERS_button, data_table_text, data_table, data_table_text_two, data_table_two
time_slider.value = time_slider.start structure.update_system(displacement) re_plot_button = Button(label="Refresh", button_type="success") re_plot_button.on_click(re_plot) ''' ############################################################################### Plot everything ############################################################################### ''' curdoc().add_root( row( column( Spacer(height=80), row( Spacer(width=20), column( signal_choices, structure_plot, time_slider, playPause_button, stop_button, re_plot_button, ), )), column( max_displacement_plot, signal_plot, ), column(
################################### # Page Layout # ################################### description_filename = join(dirname(__file__), "description.html") description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=1000) p_rt1 = Paragraph(text="""Left support: """) p_rt2 = Paragraph(text="""Right support: """) #p_rt3 = Paragraph(text="""Cross-section: """) p_rt4 = Paragraph(text="""Load Amplitude:""") doc_layout = layout(children=[ column(row(Spacer(width=700),lang_button), description, row(column( Spacer(height=20,width=400), widgetbox(radio_button_group), row(widgetbox(p_rt1, width=120), widgetbox(radio_group_left)), row(widgetbox(p_rt2, width=120), widgetbox(radio_group_right)), row(widgetbox(p_rt4, width=120), widgetbox(radio_group_ampl)), load_position_slider, reset_button, line_button), column(plot_main,plot_normalF,plot_deform ) ) ) ] ) curdoc().add_root(doc_layout)
plot.patch(x='x', y='y', color='red',source=source_reflection, alpha=.1) # reflection area plot.patch(x='x', y='y', color='blue', source=source_shadow, alpha=.1) # shadow area plot.scatter(x='x',y='y', source=source_value_plotter, size=10) # value probing plot.toolbar.logo = None initialize() # add app description description_filename = join(dirname(__file__), "description.html") description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=1130) # add area image area_image = Div(text=""" <p> <img src=/Diffraction/static/images/Diffraction_areas.jpg width=300> </p> <p> Characteristic regions and wave parameters </p>""" , render_as_text=False, width=580) # create layout controls = widgetbox([phi0_slider,wavelength_slider,textbox],width=580) # all controls curdoc().add_root(column(description, row(plot,Spacer(width=50),column(surface,sizing_mode='stretch_both')), row(controls,Spacer(width=150),area_image) ) ) # add plots and controls to root curdoc().add_periodic_callback(update, target_frame_time) # update function curdoc().title = split(dirname(__file__))[-1].replace('_',' ').replace('-',' ') # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '
################################### # Buttons and Sliders ################################### slider_angle = LatexSlider(title='\\text{Inclination of ladder:}', value_unit='^{\\circ}', value=0.0, start=0.0, end=90, step=90/20) slider_angle.on_change('value',slider_func) button_structural_system = Button(label="Show/Hide structural system", button_type="success", width=300) button_structural_system.on_click(show_structural_system) lang_button = Button(label='Zu Deutsch wechseln', button_type="success") lang_button.on_click(changeLanguage) ################################### # Page Layout ################################### # add app description text description_filename = join(dirname(__file__), "description.html") description = Div(text=open(description_filename).read(), render_as_text=False, width=880) caption_filename = join(dirname(__file__), "caption.html") caption = Div(text=open(caption_filename).read(), render_as_text=False, width=300) # send to window doc_layout=layout(children=[ column(row(Spacer(width=600),lang_button),description, row( column( widgetbox(slider_angle), widgetbox(button_structural_system), Spacer(height=50,width=300), caption, fig_2), column(fig_1) ) ) ] ) curdoc().add_root(doc_layout) curdoc().title = split(dirname(__file__))[-1].replace('_',' ').replace('-',' ') # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '
def bk_basic_interactive(doc, df=None, plot_height=700, plot_width=900): '''run a basic interactive chart as a server app - powered by the bokeh plotting library. Run the app in the jupyter notebook as follows: .. code:: python from functools import partial import pandas as pd import interactive_plotting as ip from bokeh.io import show, output_notebook from bokeh.application.handlers import FunctionHandler from bokeh.application import Application output_notebook() proposal = 'p1' df = pd.read_pickle('dill/ds_' + proposal + '.pkl') handler = FunctionHandler(partial(ip.bk_basic_interactive, df=df)) app = Application(handler) show(app) inputs doc (required input) do not change this input df (dataframe) calculated dataset input, this is a required input plot_height (integer) height of plot in pixels plot_width (integer) width of plot in pixels Add plot_height and/or plot_width parameters as kwargs within the partial method: .. code:: python handler = FunctionHandler(partial(ip.bk_basic_interactive, df=df, plot_height=450, plot_width=625)) Note: the "df" argument is not optional, a valid dataset variable must be assigned. ''' max_month = df['mnum'].max() # set up color column egs = df['eg'].values sdict = pd.read_pickle('dill/dict_settings.pkl') cdict = pd.read_pickle('dill/dict_color.pkl') eg_cdict = cdict['eg_color_dict'] clr = np.empty(len(df), dtype='object') for eg in eg_cdict.keys(): np.put(clr, np.where(egs == eg)[0], eg_cdict[eg]) df['c'] = clr df['a'] = .7 df['s'] = 5 # date list for animation label background date_list = list(pd.date_range(start=sdict['starting_date'], periods=max_month, freq='M')) date_list = [x.strftime('%Y %b') for x in date_list] slider_height = plot_height - 200 # create empty data source template source = ColumnDataSource(data=dict(x=[], y=[], c=[], s=[], a=[])) slider_month = Slider(start=0, end=max_month, value=0, step=1, title='month', height=slider_height, tooltips=False, bar_color='#ffe6cc', direction='rtl', orientation='vertical',) display_attrs = ['age', 'jobp', 'cat_order', 'spcnt', 'lspcnt', 'jnum', 'mpay', 'cpay', 'snum', 'lnum', 'ylong', 'mlong', 'idx', 'retdate', 'ldate', 'doh', 's_lmonths', 'new_order'] sel_x = Select(options=display_attrs, value='age', title='x axis attribute:', width=115, height=45) sel_y = Select(options=display_attrs, value='spcnt', title='y axis attribute:', width=115, height=45) label = Label(x=20, y=plot_height - 150, x_units='screen', y_units='screen', text='', text_alpha=.25, text_color='#b3b3b3', text_font_size='70pt') spacer1 = Spacer(height=plot_height, width=30) but_1add = Button(label='FWD', width=60) but_1sub = Button(label='BACK', width=60) add_sub = widgetbox(but_1add, but_1sub) def make_plot(): this_df = get_df() xcol = sel_x.value ycol = sel_y.value source.data = dict(x=this_df[sel_x.value], y=this_df[sel_y.value], c=this_df['c'], a=this_df['a'], s=this_df['s']) non_invert = ['age', 'idx', 's_lmonths', 'mlong', 'ylong', 'cpay', 'mpay'] if xcol in non_invert: xrng = Range1d(df[xcol].min(), df[xcol].max()) else: xrng = Range1d(df[xcol].max(), df[xcol].min()) if ycol in non_invert: yrng = Range1d(df[ycol].min(), df[ycol].max()) else: yrng = Range1d(df[ycol].max(), df[ycol].min()) p = figure(plot_width=plot_width, plot_height=plot_height, x_range=xrng, y_range=yrng, title='') p.circle(x='x', y='y', color='c', size='s', alpha='a', line_color=None, source=source) pcnt_cols = ['spcnt', 'lspcnt'] if xcol in pcnt_cols: p.x_range.end = -.001 p.xaxis[0].formatter = NumeralTickFormatter(format="0.0%") if ycol in pcnt_cols: p.y_range.end = -.001 p.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") if xcol in ['cat_order']: p.x_range.end = -50 if ycol in ['cat_order']: p.y_range.end = -50 if xcol in ['jobp', 'jnum']: p.x_range.end = .95 if ycol in ['jobp', 'jnum']: p.y_range.end = .95 p.xaxis.axis_label = sel_x.value p.yaxis.axis_label = sel_y.value label.plot = None p.add_layout(label) label.text = date_list[slider_month.value] return p def get_df(): filter_df = df[df.mnum == slider_month.value][[sel_x.value, sel_y.value, 'c', 's', 'a']] return filter_df def update_data(attr, old, new): this_df = get_df() source.data = dict(x=this_df[sel_x.value], y=this_df[sel_y.value], c=this_df['c'], a=this_df['a'], s=this_df['s']) label.text = date_list[new] controls = [sel_x, sel_y] wb_controls = [sel_x, sel_y, slider_month] for control in controls: control.on_change('value', lambda attr, old, new: insert_plot()) slider_month.on_change('value', update_data) sizing_mode = 'fixed' inputs = widgetbox(*wb_controls, width=190, sizing_mode=sizing_mode) def insert_plot(): lo.children[0] = make_plot() def animate_update(): mth = slider_month.value + 1 if mth > max_month: mth = 0 slider_month.value = mth def add1(): slider_val = slider_month.value if slider_val < max_month: slider_month.value = slider_val + 1 def sub1(): slider_val = slider_month.value if slider_val > 0: slider_month.value = slider_val - 1 but_1sub.on_click(sub1) but_1add.on_click(add1) def animate(): if play_button.label == '► Play': play_button.label = '❚❚ Pause' doc.add_periodic_callback(animate_update, 350) else: play_button.label = '► Play' doc.remove_periodic_callback(animate_update) def reset(): slider_month.value = 0 play_button = Button(label='► Play', width=60) play_button.on_click(animate) reset_button = Button(label='Reset', width=60) reset_button.on_click(reset) lo = row(make_plot(), spacer1, inputs, column(play_button, reset_button, add_sub)) doc.add_root(lo)
lang_button.on_click(changeLanguage) ################################### # Page Layout ################################### ### Add description from HTML file description_filename = join(dirname(__file__), "description.html") description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=1140) ### Arrange layout doc_layout = layout(children=[ column( row(Spacer( width=860), lang_button), row(description), row(Spacer(height=30)), row( column( figure1, row( Spacer(height=10, width=50), column(Normal_X_slider, Normal_Z_slider, Tangential_XZ_slider))), column( figure2, row(Spacer(height=10, width=50), column(draw_button, show_button, reset_button))), column(figure3, row(Spacer(height=10, width=50), Plane_Angle_slider)))) ]) curdoc().add_root(doc_layout)
width=600) area_image = Div(text=""" <h2> Technical Information for Boat and Swimmers </h2> <p> <img src="/Boat_with_three_swimmers/static/images/High_resolution_picture.png" width=400> </p> """, render_as_text=False, width=400) curdoc().add_root( column( row(description, Spacer(width=100), column(Spacer(height=100), area_image)), Spacer(height=50), scene, Spacer(height=50), row( column( numberPersonsSlider, play_button, #pause_button, jump_button, reset_button), Spacer(width=100), velocity_diagram, ))) # get path of parent directory and only use the name of the Parent Directory
(s + '=\"' + strings[s][lang] + '\"').encode(encoding='utf-8')) lang_button = Button(button_type="success", label="Zu Deutsch wechseln") lang_button.on_click(changeLanguage) ################################################################################ ###add app description ################################################################################ description_filename = join(dirname(__file__), "description.html") description1_filename = join(dirname(__file__), "description1.html") description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=750) description1 = LatexDiv(text=open(description1_filename).read(), render_as_text=False, width=750) ################################################################################ ###Send to the browser ################################################################################ curdoc().add_root( column( row(Spacer(width=450), lang_button), description, column(plot, row(mag_slider, loc_slider), row(button, rbutton), description1))) curdoc().title = split(dirname(__file__))[-1].replace('_', ' ').replace( '-', ' ' ) # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '
protocolSelect.on_change('value', lambda attr, old, new: g_update()) protocolSelect.on_change('value', lambda attr, old, new: t_update()) protocolSelect.on_change('value', lambda attr, old, new: so_update()) protocolSelect.on_change('value', lambda attr, old, new: title_update()) protocolSelect.on_change('value', lambda attr, old, new: divs_update()) protocolSelect.on_change('value', lambda attr, old, new: price_update()) curdoc().unhold() gmetric.on_change('value', lambda attr, old, new: g_update()) tmetric.on_change('value', lambda attr, old, new: t_update()) sometric.on_change('value', lambda attr, old, new: so_update()) #### Layouts, Initialization curdoc().add_root(column(protocolSelect, protocolTitle)) #GitHub & StackOverflow glayout = column(gsection_title, row(gmetric, Spacer(width=300)), gfig) #Social/Search solayout = column(sosection_title, row(sometric, Spacer(width=300)), sofig) #Transactions tlayout = column(tsection_title, row(tmetric, Spacer(width=300)), tfig) #Divs playout = column(Price, Pricev) alayout = column(Algorithm, Algorithmv) blnlayout = column(BlockNumber, BlockNumberv) blrlayout = column(BlockReward, BlockRewardv) nhlayout = column(NetHashesPerSecond, NetHashesPerSecondv) prlayout = column(ProofType, ProofTypev) tclayout = column(TotalCoinsMined, TotalCoinsMinedv) nelayout = column(NumberofExchanges, NumberofExchangesv)
############################################################################### ''' # add app description description_filename = join(dirname(__file__), "description.html") description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=1200) curdoc().add_root( column( description, row( column( row( time_plot, Spacer(width=25), column( def_undef_choices_text, row( undef_config_button, Spacer(width=25), def_config_button, Spacer( width=75 ) # needed such that the mode plots below don't overlap ), mass_input, stiffness_input, solve_system_button)), row( column(mode_one,
def _build_layout(self): layout = row(self._console_1.figure, Spacer(width=10), self._text_inbetween.figure, self._console_2.figure) return layout