def final_sketch(self): controls = [self.options, self.date_from, self.date_to] for control in controls: control.on_change('value', lambda attr, old, new: self.update()) self.radio_button_group.on_change('active', lambda attr, old, new: self.update()) columns = [ TableColumn(field="Date", title="Date", formatter=DateFormatter()), TableColumn(field="Sessions", title="Sessions"), ] self.data_table = DataTable(source=self.source, columns=columns, width=400, height=400) #self.inputs = widgetbox([self.radio_button_group, *controls], sizing_mode='fixed') self.inputs = row(self.radio_button_group, *controls) return self.inputs
def data_table(source, columns=None, titlemap=None, width=400, height=500, fit_columns=False): tcols = table_columns_from_source(source, columns=columns, titlemap=titlemap) kwargs = dict(source=source, columns=tcols, fit_columns=fit_columns) if width is not None: kwargs['width'] = width if height is not None: kwargs['height'] = height res = DataTable(**kwargs) return res
def table_widget(entry): from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, TableColumn entry_dict = copy(entry.__dict__) # Note: iterate over old dict, not the copy that is changing for k, v in entry.__dict__.items(): if k == 'id' or k == '_sa_instance_state': del entry_dict[k] # use _units keys to rename corresponding quantity if k[-6:] == '_units': prop = k[:-6] new_key = "{} [{}]".format(prop, entry_dict[k]) del entry_dict[k] entry_dict[new_key] = entry_dict.pop(prop) # order entry dict entry_dict = OrderedDict([(k, entry_dict[k]) for k in sorted(list(entry_dict.keys()))]) data = dict( labels=[str(k) for k in entry_dict], values=[str(v) for v in entry_dict.values()], ) source = ColumnDataSource(data) columns = [ TableColumn(field="labels", title="Properties"), TableColumn(field="values", title="Values"), ] data_table = DataTable(source=source, columns=columns, width=500, height=570, index_position=None, fit_columns=False) json_str = json.dumps(entry_dict, indent=2) btn_download_table.callback = bmd.CustomJS(args=dict( string=json_str, filename=entry_dict['name'] + '.json'), code=download_js) return widgetbox(data_table)
def _build_optresult_selector( self, optresults) -> Tuple[DataTable, ColumnDataSource]: # 1. build a dict with all params and all user columns data_dict = defaultdict(list) for optres in optresults: for param_name, _ in optres[0].params._getitems(): param_val = optres[0].params._get(param_name) data_dict[param_name].append(param_val) for usercol_label, usercol_fnc in self._usercolumns.items(): data_dict[usercol_label].append(usercol_fnc(optres)) # 2. build a pandas DataFrame df = DataFrame(data_dict) # 3. now sort and limit result if self._sortcolumn is not None: df = df.sort_values(by=[self._sortcolumn], ascending=self._sortasc) if self._num_result_limit is not None: df = df.head(self._num_result_limit) # 4. build column info for Bokeh table tab_columns = [] for colname in data_dict.keys(): formatter = NumberFormatter(format='0.000') if len(data_dict[colname]) > 0 and isinstance( data_dict[colname][0], int): formatter = StringFormatter() tab_columns.append( TableColumn(field=colname, title=f'{colname}', sortable=False, formatter=formatter)) # TODO: currently table size is hardcoded cds = ColumnDataSource(df) selector = DataTable(source=cds, columns=tab_columns, width=1600, height=150) return selector, cds
def get_arbitrage_table(game): optimizer = ArbitrageOptimizer() optimizer.load_game(game) arbitrage_opportunity = optimizer.get_arbitrage_opportunity() if arbitrage_opportunity['arbitrage'] != 'yes': return None else: column_1 = [ arbitrage_opportunity['bet']['1']['bookie'], arbitrage_opportunity['bet']['1']['odds'], str(round(arbitrage_opportunity['bet']['1']['bet_size'], 3)), ] column_X = [ arbitrage_opportunity['bet']['X']['bookie'], arbitrage_opportunity['bet']['X']['odds'], str(round(arbitrage_opportunity['bet']['X']['bet_size'], 3)), ] column_2 = [ arbitrage_opportunity['bet']['2']['bookie'], arbitrage_opportunity['bet']['2']['odds'], str(round(arbitrage_opportunity['bet']['2']['bet_size'], 3)), ] data = dict( column_1=column_1, column_X=column_X, column_2=column_2, ) source = ColumnDataSource(data) columns = [ TableColumn(field="column_1", title="1"), TableColumn(field="column_X", title="X"), TableColumn(field="column_2", title="2"), ] data_table = DataTable(source=source, columns=columns, width=500, height=200) return data_table, arbitrage_opportunity['profit'], arbitrage_opportunity['league'], \ arbitrage_opportunity['match_title'], arbitrage_opportunity['date'], \ arbitrage_opportunity['time_to_match']
def generate_summary_table(self): # Output tables of stats rows = ['Input data'] + self.fitted_stats.keys() means = [np.mean(self.daily_returns) ] + [float(s[0]) for s in self.fitted_stats.values()] variances = [np.var(self.daily_returns) ] + [float(s[1]) for s in self.fitted_stats.values()] skews = [skew(self.daily_returns) ] + [float(s[2]) for s in self.fitted_stats.values()] kurtosises = [kurtosis(self.daily_returns) ] + [float(s[3]) for s in self.fitted_stats.values()] raw_data = dict(rows=rows, means=means, variances=variances, skews=skews, kurtosises=kurtosises) source = ColumnDataSource(raw_data) number_formatter = NumberFormatter(format='-0.0000') columns = [ TableColumn(field="rows", title="", width=200), TableColumn(field="means", title="Mean", width=80, formatter=number_formatter), TableColumn(field="variances", title="Variance", width=80, formatter=number_formatter), TableColumn(field="skews", title="Skewness", width=80, formatter=number_formatter), TableColumn(field="kurtosises", title="Kurtosis", width=80, formatter=number_formatter) ] data_table = DataTable(source=source, columns=columns, width=550, height=150, row_headers=False) return data_table
def render_table(cleaned_data, keys): """ creates the visual bokeh- table Args: cleaned_data: (dictionary of lists) Returns: DataTable """ source = ColumnDataSource(cleaned_data) columns = [] for i in keys: columns.append(TableColumn(field=str(i), title=str(i))) data_table = DataTable(source=source, columns=columns, width=1200) return data_table
def create_data_table(): source = ColumnDataSource(df_corr) columns = [ TableColumn(field="name", title='Names'), TableColumn(field="SAT_score", title="SAT score", formatter=NumberFormatter(format='.00')), TableColumn(field="SAT Math Avg. Score", title="SAT Maths - Average"), TableColumn(field="SAT Writing Avg. Score", title="SAT Writing - Average"), TableColumn(field="ell_percent", title='% English Learners'), TableColumn(field="white_per", title="% White Students"), TableColumn(field="asian_per", title="% Asian Students"), TableColumn(field="black_per", title="% Black Students"), TableColumn(field="hispanic_per", title="% Hispanic Students") ] data_table = DataTable(source=source, columns=columns, width=1010) output_file("./templates/SAT_corr_table.html") save((widgetbox(data_table)))
def gen_hdb_data_table(df, chart_width): ''' Generate data into DataTable format ''' data = dict(df[['op', 'HDB 0', 'HDB 1', 'HDB 2', 'HDB 3', 'HDB 4', 'Sum']]) source = ColumnDataSource(data) columns = [ TableColumn(field='op', title='Operation'), TableColumn(field='HDB 0', title='HDB 0'), TableColumn(field='HDB 1', title='HDB 1'), TableColumn(field='HDB 2', title='HDB 2'), TableColumn(field='HDB 3', title='HDB 3'), TableColumn(field='HDB 4', title='HDB 4'), TableColumn(field='Sum', title='Sum'), ] return DataTable(source=source, columns=columns, width=chart_width)
def create_pred_table(path, name): """Create table of prediction data""" P = get_results(path, 'tepitope', name) df = P.data[:10] data = dict(peptide=df.peptide.values, pos=df.pos.values, score=df.score.values, allele=df.allele.values) #print (df) source = ColumnDataSource(data) columns = [ TableColumn(field="peptide", title="peptide"), TableColumn(field="pos", title="pos"), TableColumn(field="score", title="score"), TableColumn(field="allele", title="allele"), ] table = DataTable(source=source, columns=columns, width=400, height=280) return table
def to_html(self, dir_plot_destination): fn_dest = join(dir_plot_destination, "t11c-country_latest_table.html") output_file(fn_dest) self.df_latest = self.df_latest.fillna(-1) source = ColumnDataSource(self.df_latest) columns = [ TableColumn(field="Country/State", title="Country/State"), TableColumn(field="Cumulative ConfirmedCases", title="Cumulative ConfirmedCases", formatter=NumberFormatter()), TableColumn(field="Cumulative Fatalities", title="Cumulative Fatalities", formatter=NumberFormatter()), TableColumn(field="Cumulative Total Tests", title="Cumulative Total Tests", formatter=NumberFormatter()), TableColumn(field="Cumulative Negative Cases", title="Cumulative Negative Cases", formatter=NumberFormatter()), TableColumn(field="Cumulative Tests per Million", title="Cumulative Tests per Million", formatter=NumberFormatter()), TableColumn(field="Cumulative Confirmed/Tests (%)", title="Cumulative Confirmed/Tests (%)", formatter=NumberFormatter()), TableColumn(field="Population", title="Population", formatter=NumberFormatter()), TableColumn(field="Extended", title=" Last Point Extended") ] data_table = DataTable(source=source, columns=columns, sizing_mode="stretch_both", index_position=None) show( column([ data_table, Div(text="<span>Last Updated on " + str(self.update_date) + "<br/>Cells with -1 represent missing values<span>", style={'color': 'whitesmoke'}) ], sizing_mode="stretch_width", background='rgb(70,70,70)'))
def make_timeseries_datatable_bokeh_server(df): source = ColumnDataSource(df) columns = [ TableColumn(field="Date", title="Date", formatter=DateFormatter()), TableColumn(field="Target", title="Target Timeseries", formatter=StringFormatter(font_style="bold", text_color='red')), TableColumn(field="Hedge", title="Hedge Timeseries", formatter=StringFormatter(font_style="bold", text_color='blue')), TableColumn(field="Correlation", title="Correlation", formatter=StringFormatter(font_style="bold", text_color='darkgreen')) ] data_table = DataTable(source=source, columns=columns, width=1000) return data_table
def make_layout(): plot, source = make_plot() columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", type="success") button.on_click(click_handler) buttons = VBox(children=[button]) vbox = VBox(children=[buttons, plot, data_table]) return vbox
def create_table(): # create list of TableColumn objects TODO: reverse order maybe and don't include file path columns table_cols = [] for col in table_source.source.column_names: # create TableColumn object with column if col != 'imgs' and col != 'thumbs' and col != 'index': # if col in {'Image Index', 'Patient Gender', 'Finding Labels', 'PCA_X', 'PCA_Y'}: new_col = [TableColumn(field=col, title=col)] # append column to list table_cols = new_col + table_cols # create DataTable object using TableColumn objects in list data_table = DataTable(source=source, columns=table_cols, view=table_source, width=1500) return data_table
def displayResultTable(sortedKeys, dictionnary, name): #display a table in source = ColumnDataSource(dictionnary) columns = [ TableColumn(field=key, title=key) for key in sortedKeys ] area = DataTable(source=source, columns=columns, width=600, height=800) button = Button(label="Download", button_type="success") button.callback = CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read()) controls=widgetbox(button) output_file(name+".html", title=name) save(row(area,controls))
def display_EOD(programs, pb, indicators, name, demand,electricity_prices): defaults.height=400 defaults.width = 400 demand = pb.demand def time_step_hour (i) : return pb.time_step_to_string(i) area1 = plot_lines(programs, time_step_hour) area1.title.text = "Production plans" area2 = stack_lines(programs, time_step_hour) area2.title.text = "Cumulative production" area2.line([i+1.5 for i in range(len(demand))],demand,line_width=2,line_color="black",legend="Demand") data = dict( indicator=[indicator for indicator in indicators], value=[indicators[indicator] for indicator in indicators ] ) source = ColumnDataSource(data) columns = [ TableColumn(field="indicator", title="indicator"), TableColumn(field="value", title="value"), ] area3 = DataTable(source=source, columns=columns, width=400, height=280) area4 = plot_lines({"price":electricity_prices}, time_step_hour,ylabel="euros/MWh") area4.title.text = "Electricity_price" output_file("global_programs.html", title=name, mode="inline") save(row(area3,area1,area2,area4))
def common_table(df: DataFrame): logger.debug('Common table') ddf = df.Игра.groupby(df.Результат).count().to_frame() source = ColumnDataSource( data=dict(y=ddf.index.values, fights_count=ddf.values, skill_sum=df.Скилл.groupby(df.Результат).sum().values)) columns = [ TableColumn(field="y", title="Результат"), TableColumn(field="fights_count", title="Количество"), TableColumn(field="skill_sum", title="Суммарный скилл", formatter=NumberFormatter(format="0.0")) ] data_table = DataTable(source=source, columns=columns, width=800) return data_table
def _create_events_table() -> DataTable: """Utility function for creating and styling the events table.""" formatter = HTMLTemplateFormatter(template=''' <style> .AS_POS {color: #0000FF; font-weight: bold;} .AS_NEG {color: #0000FF; font-weight: bold;} .OP_POS {color: #1aaa0d; font-style: bold;} .OP_NEG {color: #f40000;font-style: bold;} .NEG_POS {font-style: italic;} .NEG_NEG {color: #f40000; font-style: italic;} .INT_POS {color: #1aaa0d; font-style: italic;} .INT_NEG {color: #f40000; font-style: italic;} * {font-size: 105%;} </style> <%= value %>''') columns = [TableColumn(field='POS_events', title='Positive Events', formatter=formatter), TableColumn(field='NEG_events', title='Negative Events', formatter=formatter)] return DataTable(source=ColumnDataSource(), columns=columns, height=400, index_position=None, width=1500, sortable=False, editable=False, reorderable=False)
def __init__(self, **kwargs): self.model = kwargs['model'] self.lock = Lock() self.source = kwargs.get('source', ColumnDataSource(self.model.empty_df())) self.table = DataTable( source=self.source, sizing_mode='stretch_both', width_policy='max', selectable=True, ) self.table.columns = [ TableColumn(field=c, title=c) for c in self.model.empty_df() ] self.load_button = Button( label='Load', align="end", button_type="success", width=100, width_policy="fixed", height=40, height_policy="fixed", ) self.stream_and_save_button = Button( label='Update', align="end", button_type="success", width=100, width_policy="fixed", height=40, height_policy="fixed", ) view = column( row(self.load_button, self.stream_and_save_button, sizing_mode='stretch_width'), self.table, sizing_mode='stretch_both', ) super(TableViewController, self).__init__(view, **kwargs) self.load_button.on_click(self.load) self.stream_and_save_button.on_click(self.stream_and_save)
def initialize_plot(self, ranges=None, plot=None, plots=None, source=None): """ Initializes a new plot object with the last available frame. """ # Get element key and ranges for frame element = self.hmap.last key = self.keys[-1] self.current_frame = element self.current_key = key style = self.lookup_options(element, 'style')[self.cyclic_index] data, _, style = self.get_data(element, ranges, style) if source is None: source = self._init_datasource(data) self.handles['source'] = self.handles['cds'] = source self.handles['selected'] = source.selected if self.selected is not None: source.selected.indices = self.selected columns = self._get_columns(element, data) style['reorderable'] = False table = DataTable(source=source, columns=columns, height=self.height, width=self.width, **style) self.handles['table'] = table self.handles['glyph_renderer'] = table self._execute_hooks(element) self.drawn = True title = self._get_title_div(self.keys[-1], '10pt') if title: plot = Column(title, table) self.handles['title'] = title else: plot = table self.handles['plot'] = plot for cb in self.callbacks: cb.initialize() return plot
def write_table(self, run_list=None, raft_list=None, type_list=None): data = dict(rafts=raft_list, runs=run_list, types=type_list) dashboard = ColumnDataSource(data) columns = [ TableColumn(field="rafts", title="Raft"), TableColumn(field="types", title="Type"), TableColumn(field="runs", title="Run", formatter=HTMLTemplateFormatter(template="<a href= \ 'http://slac.stanford.edu/~richard/LSST/<%= rafts %>-<%= runs %>.html' \ ><%= runs %></a>")) ] data_table = DataTable(source=dashboard, columns=columns, width=400, height=280) return data_table
def getBokehComponent(self): ## First, we construct the data source if self.data is None: self.data = {} source = ColumnDataSource(self.data) source.selected.on_change('indices', self.getCallback()) #source.on_change('selected', callback_in) columns = [] for k in self.data.keys(): columns.append(TableColumn(field=k, title=k)) #TableColumn(field="dates", title="StartDate", formatter=DateFormatter()), data_table = DataTable(source=source, columns=columns, width=300, height=280) # assign class variables self.data_table = data_table self.source = source return self.data_table
def make_table(cds, properties): """ Create the table widget Args: csd : ColumnDataSource ColumnDataSource properties : dict Dictionary with attribute names as keys and printable names as values """ table_columns = [] for attr, name in properties.items(): table_columns.append(TableColumn(field=attr, title=name)) table = DataTable(source=cds, columns=table_columns, width=PLOT_WIDTH, height=PLOT_HEIGHT) return table
def _table(self, source): """The table of replacement dates and segment positions. Params: ------- source : pandas.DataFrame Data source. Returns: -------- bokeh.plotting.Figure Table of replacement dates and segment positions. """ columns = [ TableColumn(field='ReplacementDate', title='Installation Date', formatter=DateFormatter(format='d M yy')), TableColumn(field='SegmentPosition', title='Segment'), TableColumn(field='DaysSinceReplacement', title='Days Since Installation') ] return vform(DataTable(source=source, columns=columns, row_headers=False, width=400, height=1000))
def get_allocation_table(fund): allocation_data = pd.read_csv(StringIO( fund.get('allocation_file_content'))) data = {col: allocation_data[col] for col in allocation_data.columns} source = ColumnDataSource(data) columns = [ TableColumn(field=col, title=col) for col in allocation_data.columns ] data_table = DataTable(source=source, columns=columns, sizing_mode='scale_width', height=400) script, alloc_data = components( widgetbox(data_table, sizing_mode='scale_width')) return script, alloc_data
def generate_app(doc): df = pd.read_csv('data/headcount.csv', sep = '\t') df = df.pivot_table(values = 'Headcount', index = ['FT or PT'],columns='Month').reset_index() source = ColumnDataSource(data=df) """def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = dict(ColumnDataSource(data=data).data) """ slider = Slider(start=0, end=30, value=0, step=2, title="Smoothing by N Days") #slider.on_change('value', callback) columns = [] for column in df.columns: columns.append(TableColumn(field=column, title=column)) data_table = DataTable(source=source, columns=columns, width=1200, height=800) doc.add_root(Column(slider, data_table))
def updatetable(width, height): #kwerenda do wyciągania przychodów df = pd.read_sql( """SELECT MAX(DATA) AS [DATA], 'GPW' AS [RYNEK] FROM [NOTOWANIA_GPW] UNION SELECT MAX(DATA) AS [DATA], 'New Connect' AS [RYNEK] FROM [NOTOWANIA_NC] UNION SELECT MAX(DATA) AS [DATA], 'Catalyst' AS [RYNEK] FROM [NOTOWANIA_CATALYST]""", conn) #dane source = ColumnDataSource(data=df) #kolumny columns = [ TableColumn(field="RYNEK", title="Rynek"), TableColumn(field="DATA", title="Data") ] #tabela t = DataTable(source=source, columns=columns, width=width, height=height) t = finalize_table(t, True, False, False, False) return t
def create_typetable(record_datasource, file, size): data_table = record_datasource.data[file][0] data_table = data_table.dtypes.astype(str).rename( 'Data-Types').reset_index() column_list = data_table.columns.tolist() column_titles = list() for i in range(0, len(column_list)): column_titles.append( TableColumn(field=column_list[i], title=column_list[i])) datatable_ = DataTable(source = ColumnDataSource(data_table.to_dict(orient='list')),\ columns = column_titles,\ width = size, \ height= 150, css_classes =['custom_header']) return datatable_
def get(self, request): diabetesLogic = DiabetesLogic() dataset_file_path = "dataset_management/diabetes.txt" df = diabetesLogic.read_dataset(dataset_file_path) source = ColumnDataSource(df) columns = [TableColumn(field=Ci, title=Ci) for Ci in df.columns] # bokeh columns data_table = DataTable(source=source, columns=columns, width=1000, editable=True, fit_columns=True) script, div = components(widgetbox(data_table)) return render(request, 'vis_diabetes.html', { 'script': script, 'div': div, 'dataset_file_path': dataset_file_path })
def build_stock_table(data): source = ColumnDataSource(data) columns = [ TableColumn(field="symbol", title="Symbol"), TableColumn(field="lastTrade", title="LastTrade"), TableColumn(field="change", title="Change"), TableColumn(field="high", title="High"), TableColumn(field="low", title="Low"), TableColumn(field="bid", title="Bid"), TableColumn(field="ask", title="Ask"), TableColumn(field="spread", title="Spread") ] data_table = DataTable(source=source, columns=columns, width=500, height=280) return data_table