def make_table(source, src): table_columns = [ TableColumn(field='Date', title='Date', formatter=DateFormatter(format="%m/%d/%Y %H:%M:%S")) ] colonne = src.columns colonne = colonne.delete(0) table_columns += [TableColumn(field=col, title=col) for col in colonne] liste = [k for k in range(0, 10)] longueur = src.shape[0] for k in range(longueur - 10, longueur): liste.append(k) view1 = CDSView(source=source, filters=[IndexFilter(indices=liste)]) #table_source = ColumnDataSource(src) datatable = DataTable(source=source, columns=table_columns, width=1200, height=1000, view=view1) #print(datatable.fit_columns) return datatable
def __init__(self, scheduler): self.scheduler = scheduler names = ['Tasks', 'Stored', 'Processing', 'Waiting', 'No Worker', 'Erred', 'Released'] self.source = ColumnDataSource({name: [] for name in names}) columns = {name: TableColumn(field=name, title=name) for name in names} table = DataTable( source=self.source, columns=[columns[n] for n in names], height=70, ) self.root = table
def plotGraph(graph, title=None, graphSavePath=None, networkPath=None): for k, adjacencies in zip(list(graph.nodes.keys()), graph.adjacency()): graph.nodes[k]["degree"] = len(adjacencies[1]) if networkPath is not None: for city in graph.nodes(): graph.nodes[city]["code"] = graph.networkPath.stationList.getCode( city) plot_height = 700 plot = Plot(plot_width=900, plot_height=plot_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = title node_hover_tool = HoverTool( tooltips=[("Miasto", "@index"), ("Kod miasta", "@code"), ("Stopien wierzcholka", "@degree")]) plot.add_tools(WheelZoomTool(), PanTool(), SaveTool(), node_hover_tool, BoxZoomTool(), ResetTool()) # , TapTool()) graph_renderer = from_networkx(graph, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=12, fill_color="yellow") graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="blue") graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="red") graph_renderer.edge_renderer.glyph = MultiLine(line_color="green", line_alpha=0.3, line_width=1) graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="blue", line_width=1.2) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="red", line_width=1.2) plot.renderers.append(graph_renderer) columnCities = ColumnDataSource(data=dict(city=list(graph.nodes.keys()))) columnsNetwork = [ TableColumn(field="city", title="Miasto"), ] table = DataTable(source=columnCities, columns=columnsNetwork, width=155, height=plot_height) layout = row(plot, table) if graphSavePath is not None: output_file(graphSavePath, title) show(layout)
def performace_table(self, policy_names: list, decimals: int, height: int = 600, width: int = 900): """Table of the result using Bokeh. Parameters ---------- policy_names : list List of selected policy names decimals : int Number of decimal places to round height : int Height of the table width : int Width of the table Returns ------- None """ selected_performance_dict = { key: self.performance_dict[key] for key in policy_names } table = pd.concat([ pd.DataFrame(v, index=[k]).T for k, v in selected_performance_dict.items() ], axis=1) table.reset_index(inplace=True) table.rename(columns={"index": "metric"}, inplace=True) table = table.round(decimals) Columns = [TableColumn(field=Ci, title=Ci) for Ci in table.columns] # bokeh columns data_table = DataTable(columns=Columns, source=ColumnDataSource(table), fit_columns=False, height=height, width=width) # bokeh table data_table.index_position = None show(data_table)
def createVCTable(self): self.VCdata = { 'Class': [], 'Element': [], 'Voltage [p.u]': [], } self.CVsource = ColumnDataSource(self.VCdata) cols = [] for key in self.VCdata: cols.append(TableColumn(field=key, title=key)) VCTable = DataTable(source=self.CVsource, columns=cols, width=500, height=310) return VCTable
def __init__(self, worker): self.worker = worker names = [ 'Stored', 'Executing', 'Ready', 'Waiting', 'Connections', 'Serving' ] self.source = ColumnDataSource({name: [] for name in names}) columns = {name: TableColumn(field=name, title=name) for name in names} table = DataTable( source=self.source, columns=[columns[n] for n in names], height=70, ) self.root = table
def period(attrname, old, new): a.glyph.fill_color = '#084594' if select.value == 'latest': result4 = data.loc[data["Date_reported"] == ( data["Date_reported"].max() - datetime.timedelta(days=1)).strftime('%Y/%m/%d')] else: result4 = data.loc[data["Date_reported"] == select.value] result4 = result4.sort_values(" Cumulative_cases", ascending=False) yesterday = data.loc[data["Date_reported"] == ( result4['Date_reported'].max() - datetime.timedelta(days=1))] yesterday = yesterday[[" Cumulative_cases", " Country"]] yesterday = yesterday.rename( columns={' Cumulative_cases': 'yesterday_cases'}, inplace=False) result4 = pd.merge(result4, yesterday, left_on=' Country', right_on=' Country', how="left") result4['dzienny_przyrost'] = ( result4[' Cumulative_cases'] - result4['yesterday_cases']) / result4[' Cumulative_cases'] result4['dzienny_przyrost'] = result4['dzienny_przyrost'].round(decimals=3) plt.x_range.factors = [] plt.x_range.factors = list(result4[' Country_code'][0:20]) source2 = ColumnDataSource( data={ 'kraj': list(result4[' Country'][0:20]), 'kod': list(result4[' Country_code'][0:20]), 'cases': list(result4[' Cumulative_cases'][0:20]), 'new': list(result4[' New_cases'][0:20]), 'share': list(result4['share_of_all'][0:20]), 'deaths': list(result4[' New_deaths'][0:20]), 'increment': list(result4['dzienny_przyrost'][0:20]), 'in_pop': list(result4['udzial_w_populacji'][0:20]) }) source.data = dict(source2.data) table = result4.copy() table["Date_reported"] = table["Date_reported"].dt.strftime('%d/%m/%Y') table = table[[ 'Date_reported', ' Country', ' Country_code', ' New_cases', ' Cumulative_cases', ' New_deaths', ' Cumulative_deaths', ' WHO_region', 'udzial_w_populacji' ]] Columns = [TableColumn(field=Ci, title=Ci) for Ci in table.columns] data_table_source2 = ColumnDataSource(table) data_table_source.data = dict(data_table_source2.data)
def gen_data_table(df, chart_width): ''' Generate data into DataTable format ''' # Uniquify by real_time and op_group page df = df.loc[df.sub_type == 'FullOp', [ 'op_group', 'sub_type', 'cpu_time', 'real_time', 'runtime_ratio', 'scale_factor', 'lvheap_used', 'lvheap_allocated', 'shared_used' ]] df = df.drop_duplicates() # Show Top 20 rows df = df.sort_values(by="real_time", ascending=False) df = df.head(20) data = dict(df[[ 'op_group', 'sub_type', 'cpu_time', 'real_time', 'runtime_ratio', 'scale_factor', 'lvheap_used', 'lvheap_allocated', 'shared_used' ]]) #, 'fec', 'fgc', 'hec', 'hgc']]) source = ColumnDataSource(data) columns = [ TableColumn(field='op_group', title='Name'), TableColumn(field='sub_type', title='Sub-Op Type'), TableColumn(field='cpu_time', title='CPU time'), TableColumn(field='real_time', title='Real time'), TableColumn(field='runtime_ratio', title='Runtime ratio', formatter=NumberFormatter(format="0.00")), TableColumn(field='scale_factor', title='Scale factor', formatter=NumberFormatter(format="0.00")), TableColumn(field='lvheap_used', title='LVHEAP used'), TableColumn(field='lvheap_allocated', title='LVHEAP allocated'), TableColumn(field='shared_used', title='Shared used'), ] return DataTable(source=source, columns=columns, width=chart_width)
def make_table(self, current): table_columns = [TableColumn(field='eventID', title='eventID'), TableColumn(field='id', title='id'), TableColumn(field='時段', title='時段'), TableColumn(field='距離', title='距離'), TableColumn(field='Year', title='Year'), TableColumn(field='Month', title='Month'), TableColumn(field='locationID', title='locationID'), TableColumn(field='Count', title='Count'), TableColumn(field='vernacularName', title='vernacularName') ] self.source = ColumnDataSource(data=current) self.title = Paragraph(text='Table') self.carrier_table = DataTable(source=self.source, columns=table_columns, fit_columns=True, selectable=True, sortable=False, width=1000 ) return column(self.title, self.carrier_table)
def column_selection_change(): """Creates a datatable when user changes the selected table column(s)""" d = curdoc() _remove_fig(d) model_id, message_name, _ = run_handlers.get_modelid_messagename_type(d) sind = run_handlers.get_source_index(d.session_context.id, model_id, message_name) source = d.get_model_by_name(sind) _install_callback_and_cds(sind, model_id, message_name, stream_limit=1) sel_cols = d.get_model_by_name(COLUMN_MULTISELECT).value columns = [TableColumn(field=c, title=c) for c in sel_cols] data_table = DataTable(source=source, columns=columns, width=500, height=500) table_widget = widgetbox(data_table, name=FIGURE_MODEL) d.add_root(table_widget)
def create_rawtable(record_datasource, file, size): data_table = record_datasource.data[file][0] 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= 275, css_classes =['custom_header']) return datatable_
def _build_optresult_selector(self, optresults): # 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)) cds = ColumnDataSource(df) selector = DataTable( source=cds, columns=tab_columns, height=150, # fixed height for selector width=0, # set width to 0 so there is no min_width sizing_mode='stretch_width', fit_columns=True) return selector, cds
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 bokeh_table(columns, graph_dir, graph_name, dump_jpg, show_html, width=300, height=200): """Dump the (column name, column values) 'columns' dictionary as a bokeh table Parameters : columns (list) : List of columns to plot, with the format [(column_name, column_title, column_values)] column_name being a string, column_values being a list graph_dir (string) : folder where the output html and/or jpg figure will be dumped graph_name (string): name of the figure, the output in 'graph_dir' will be name 'graph_name.html' and 'graph_name.jpg' dum_jpg (boolean) : do not dump the jpg figure if set to False (default is True) width (integer) : width of the figure height (integer) : height of the figure """ """ create an output graphics file """ output_file(os.path.join(graph_dir, graph_name + ".html")) dataset = {col_name: col_values for (col_name, _, col_values) in columns} source = ColumnDataSource(dataset) table_columns = [ TableColumn(field=col_name, title=col_title) for (col_name, col_title, col_values) in columns ] data_table = DataTable(source=source, columns=table_columns, width=width, height=height) p = widgetbox(data_table, sizing_mode='fixed') """ show figure in browser """ if show_html == True: show(p) """ dump figure as png file """ if dump_jpg == True: export_png(p, filename=os.path.join(graph_dir, graph_name + ".png")) reset_output()
def gen_template_1(outputfile): df = corona_df[0] #df = df[['Country,Other','TotalCases']] df = df.head(21) df = df.fillna(method='ffill') data_table = DataTable( columns=[TableColumn(field=Ci, title=Ci) for Ci in df.columns], source=ColumnDataSource(df), width=800, ) df = pd.DataFrame(df).set_index("Country,Other") bar_graph = df.plot_bokeh.barh(xlabel='TotalCases Count', ylabel='Country', show_figure=False) pandas_bokeh.plot_grid([[data_table, bar_graph]], plot_width=800, plot_height=350)
def createTable(self,dictionaryIn): title = dictionaryIn["title"] div = Div(text=title, width=55, height=10) tableMetadata = dictionaryIn["metadata"] columns = [TableColumn( field=tableRowInfo["field"], title=tableRowInfo["title"], width=tableRowInfo["width"], formatter=tableRowInfo["formatter"] ) for tableRowInfo in tableMetadata] self.source = ColumnDataSource(dictionaryIn["data"]) dataTable = DataTable(source=self.source, columns=columns,index_position = None, width=400, height=280) self.gui = widgetbox(div,dataTable)
def cleaning_tab(df): # Calculate summary stats for table stats = pd.DataFrame(columns=[ 'user', 'start', 'end', 'average_impression_count', 'timelines', 'total_entries', 'missing values' ]) def getStats(df): user_list = df.user.unique() for user in user_list: data = df[(df['user'] == user)] stats.loc[user] = [ user, data.impressionTime.min(), data.impressionTime.max(), # max(df.impressionOrder), # min(df.groupby(['timeline'], sort=False)['impressionOrder'].max()), data.impressionOrder.mean(), data['timeline'].nunique(), data['id'].count(), data.isna().sum().sum() ] return stats stats = getStats(df) user_src = ColumnDataSource(stats) # Columns of table table_columns = [ TableColumn(field='user', title='Username'), TableColumn(field='start', title='Start'), TableColumn(field='end', title='End'), TableColumn(field='average_impression_count', title='Avg Impressions per Timeline'), TableColumn(field='timelines', title='# of Timelines'), TableColumn(field='total_entries', title='Total Entries'), TableColumn(field='missing values', title='Missing Values') ] user_table = DataTable(source=user_src, columns=table_columns, width=1000) tab = Panel(child=user_table, title='Cleaning') return tab
def create_table(source_data): """ Creates a table from the source data """ decimal_formatter = NumberFormatter(format='0.0') columns = [ TableColumn(field="ids", title="Id"), TableColumn(field="x", title="X", formatter=decimal_formatter), TableColumn(field="y", title="Y", formatter=decimal_formatter), TableColumn(field="names", title="Name"), TableColumn(field="phones", title="Phone"), TableColumn(field="color", title="Color"), ] data_table = DataTable(source=source_data, columns=columns, width=400, height=280) return data_table
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
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_datatable(datasource): "Get the Bokeh table of the data" columns = [ TableColumn(field="id", title="id"), # , formatter=DateFormatter() TableColumn(field="infection_from", title="infection_from"), TableColumn(field="case", title="Status"), TableColumn(field="healthCareDistrict", title="healthCareDistrict"), TableColumn(field="date", title="date", formatter=DateFormatter()), TableColumn(field="origin", title="origin"), ] dt = DataTable(source=datasource, columns=columns, width=500, height=750) return dt
def coroutine(config, width, height, xmin, xmax, ymin, ymax): self.fig.x_range.start = xmin self.fig.x_range.end = xmax self.fig.y_range.start = ymin self.fig.y_range.end = ymax self.fig.plot_width = width self.fig.plot_height = height category = config['c'] self.legend.text = '\n'.join( ['Categories:<ul style="list-style: none;padding-left: 0;">']+ [ '<li><span style="color: {};">◼</span>c[{}]={}</li>'.format( category[i]['color'], i, category[i]['label'] ) for i in range(len(category)) if category[i]['len'] > 0 ]+ ["</ul>"] ) # self.color_key = [c['color'] for c in category if c['len'] > 0] self.hide_hovertool_for_category = [ i for i in range(len(category)) if 'hide_hovertool' in category[i] if category[i]['hide_hovertool'] ] df = self.model.data _df = pd.DataFrame({k:[] for k in df.columns}) self.source.data = ColumnDataSource.from_df(_df) if self.table is not None: self.table.columns = [TableColumn(field=c, title=c) for c in _df.columns] glyph = self.model.bokeh_glyph() renderer = self.fig.add_glyph(self.source, glyph) if self.hovertool is None: tooltips = [ ("(x,y)","($x, $y)"), ] for k in df.columns: tooltips.append((k,"@"+str(k))) self.hovertool = HoverTool(tooltips = tooltips) self.fig.add_tools(self.hovertool) self.update_image()
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_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 __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 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 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 plot_table(self, **params): try: from bokeh.models.widgets import DataTable, TableColumn df, metrics = self._handle_data(**params) columns = list() for col in df.columns.to_list(): columns.append(TableColumn(field=col, title=col)) source = ColumnDataSource(df) p2 = DataTable(columns=columns, source=source, fit_columns=True, max_height=(self.plot_height - 20), max_width=(self.plot_width - 40), index_width=0) p2.width = (self.plot_width - 30) p2.height = (self.plot_height - 20) return p2 except Exception as e: return f"<br><br> Plot error: <br> {str(e)}"
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 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 })