def _get_columns(self, element, data): columns = [] for d in element.dimensions(): col = dimension_sanitizer(d.name) kind = data[col].dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif kind == 'M' or (kind == 'O' and len(data[col]) and type(data[col][0]) in datetime_types): dimtype = element.get_dimension_type(0) dformat = Dimension.type_formatters.get( dimtype, '%Y-%m-%d %H:%M:%S') formatter = DateFormatter(format=dformat) editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() column = TableColumn(field=dimension_sanitizer(d.name), title=d.pprint_label, editor=editor, formatter=formatter) columns.append(column) return columns
def create(self): self.sources['table'] = ColumnDataSource(dict(x=[], y=[])) self.sources['background'] = ColumnDataSource(dict(x=[], y=[])) columns = [ TableColumn(field="x", title="ppm", formatter=NumberFormatter(format="0.00")), TableColumn(field="y", title="y", formatter=NumberFormatter(format="0.00")) ] self.dataTable = DataTable(source=self.sources['table'], columns=columns, reorderable=False, width=500) self.sources['table'].on_change('selected', lambda attr, old, new: self.rowSelect(new['1d']['indices'])) self.sources['table'].on_change('data', lambda attr, old, new: self.dataChanged(old, new)) self.manual = CustomButton(label="Manual Peaks", button_type="success", width=500, error="Please select area using the peak picking tool.") self.manual.on_click(self.manualPeakPicking) self.peak = CustomButton(label="Peak By Peak", button_type="primary", width=250, error="Please select area using the peak by peak tool.") self.peak.on_click(self.peakByPeakPicking) self.peakTool = CustomTapTool.Create(self.peak, tapTool=PeakByPeakTapTool, auto=True, id="peakByPeakTool") self.createManualTool() self.createDeselectButton() self.createDeleteButton() self.chemicalShiftReportTitle = Div(text="<strong>Chemical Shift Report</strong>" if getLabel(self.udic) == "13C" else "") self.chemicalShiftReport = Paragraph(text=self.getChemicalShiftReport(), width=500)
def create(self): self.sources['table'] = ColumnDataSource( dict(xStart=[], xStop=[], top=[], bottom=[], integral=[])) columns = [ TableColumn(field="xStart", title="start", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00")), TableColumn(field="xStop", title="stop", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00")), TableColumn(field="integral", title="integral", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00")) ] self.dataTable = DataTable(source=self.sources['table'], columns=columns, reorderable=False, width=500, editable=True) self.sources['table'].on_change( 'selected', lambda attr, old, new: self.rowSelect(new['1d']['indices'])) self.sources['table'].on_change( 'data', lambda attr, old, new: self.changeData(old, new)) self.manual = CustomButton( label="Manual Integration", button_type="primary", width=250, error="Please select area using the integration tool.") self.manual.on_click(self.manualIntegration) self.createDeselectButton() self.createDeleteButton() callback = CustomJS(args=dict(button=self.manual), code=""" /// get BoxSelectTool dimensions from cb_data parameter of Callback var geometry = cb_data['geometry']; button.data = { x0: geometry['x0'], x1: geometry['x1'], y0: geometry['y0'], y1: geometry['y1'] }; // Callback to the backend button.clicks++; """) self.tool = CustomBoxSelectTool(tool_name="Integration", icon="my_icon_integration", dimensions="width", callback=callback, id="integrationTool")
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'] = source columns = [] dims = element.dimensions() for d in dims: col = dimension_sanitizer(d.name) kind = data[col].dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif kind == 'M' or (kind == 'O' and len(data[col]) and type(data[col][0]) in datetime_types): dimtype = element.get_dimension_type(0) dformat = Dimension.type_formatters.get( dimtype, '%Y-%m-%d %H:%M:%S') formatter = DateFormatter(format=dformat) editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() column = TableColumn(field=d.name, title=d.pprint_label, editor=editor, formatter=formatter) columns.append(column) style['reorderable'] = False table = DataTable(source=source, columns=columns, height=self.height, width=self.width, **style) self.handles['plot'] = table self.handles['glyph_renderer'] = table self._execute_hooks(element) self.drawn = True for cb in self.callbacks: cb.initialize() return table
def get_leaderboard(self): source = ColumnDataSource(self.ratings) float_formatter = NumberFormatter(format='0,0.00') percentage_formatter = NumberFormatter(format='0.0%') columns = [] for col_name in self.ratings.columns: col_title = col_name formatter = float_formatter if col_name == 'num_games': col_title = '# Games' elif col_name == 'rating_lb': col_title = 'Rating (Lowerbound)' elif col_name == 'rating': col_title = 'Rating' elif 'vs_' in col_name: continue elif col_name == 'vs_med': col_title = "Expected point diff vs median" formatter = percentage_formatter elif col_name == 'vs_mean': col_title = "Expected point diff vs mean" formatter = percentage_formatter elif col_name == 'vs_best': col_title = "Expected point diff vs best" formatter = percentage_formatter elif col_name == 'ppg_vs_mean': col_title = 'Expected points per game vs mean' formatter = percentage_formatter elif col_name == 'avg_rating_diff': col_title = 'Average ratings advantage' elif col_name == 'rank_lb': col_title = 'Rank (Lowerbound)' elif col_name == 'rank_pure': col_title = 'Rank (Pure)' col_type = self.ratings[col_name].dtype if str(col_type) == 'int64': column = TableColumn(field=col_name, title=col_title) elif str(col_type) == 'float64': column = TableColumn(field=col_name, title=col_title, formatter=formatter) else: raise Exception("Unknown column type!") columns.append(column) columns = [TableColumn(field='name', title='Username')] + columns data_table = DataTable(columns=columns, index_position=None, source=source, width=1620) return data_table
def __init__(self, **kwargs): names = ['processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen', 'memory_percent', 'host'] self.source = ColumnDataSource({k: [] for k in names}) columns = {name: TableColumn(field=name, title=name.replace('_percent', ' %')) for name in names} cnames = ['host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent'] formatters = {'cpu': NumberFormatter(format='0.0 %'), 'memory_percent': NumberFormatter(format='0.0 %'), 'memory': NumberFormatter(format='0 b'), 'latency': NumberFormatter(format='0.00000'), 'last-seen': NumberFormatter(format='0.000'), 'disk-read': NumberFormatter(format='0 b'), 'disk-write': NumberFormatter(format='0 b'), 'net-send': NumberFormatter(format='0 b'), 'net-recv': NumberFormatter(format='0 b')} table = DataTable( source=self.source, columns=[columns[n] for n in cnames], ) for name in cnames: if name in formatters: table.columns[cnames.index(name)].formatter = formatters[name] mem_plot = Plot( title=Title(text="Memory Usage (%)"), toolbar_location=None, x_range=Range1d(start=0, end=1), y_range=Range1d(start=-0.1, end=0.1), **kwargs ) mem_plot.add_glyph( self.source, Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5) ) mem_plot.add_layout(LinearAxis(), 'below') hover = HoverTool( point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span> </div> """ ) mem_plot.add_tools(hover, BoxSelectTool()) if 'sizing_mode' in kwargs: sizing_mode = {'sizing_mode': kwargs['sizing_mode']} else: sizing_mode = {} self.root = column(mem_plot, table, id='bk-worker-table', **sizing_mode)
def make_statistics_table(metrics): with open (join(dirname(__file__), 'data/metrics.j')) as filehandle: metrics = json.load(filehandle) source = ColumnDataSource(data=dict()) source.data = metrics columns = [ TableColumn(field="Metric", title="Metric"), TableColumn(field="Reads", title="Reads", formatter=NumberFormatter(format="0,0")), TableColumn(field="Contigs", title="Contigs", formatter=NumberFormatter(format="0,0")), TableColumn(field="Genes", title="Genes", formatter=NumberFormatter(format="0,0")) ] data_table = DataTable(source=source, columns=columns, width=600) return data_table
def metrics_to_table(metrics_df): metric_formats = OrderedDict([('n_trades', '0'), ('n_win', '0'), ('n_loss', '0'), ('hit_ratio', '0.000'), ('avg_trade_win', '0.0000'), ('avg_trade_loss', '0.0000'), ('unit_return', '0.000'), ('total_pnl', '0.00'), ('cr_trade', '0.000'), ('cr_day', '0.000'), ('cum_ret', '0.000'), ('vol_not_ann', '0.000'), ('sharpe_ratio', '0.000'), ('max_drawdown', '0.000'), ('drawdown_days', '0'), ('max_runup', '0.000'), ('runup_days', '0'), ('time_in_market', '0.000'), ('rina', '0.000')]) # Add table of metrics s = ColumnDataSource(metrics_df) tbl_columns = [TableColumn(field='run_label', title='run', width=100)] tbl_columns += [ TableColumn(field=mm, title=mm, width=100, formatter=NumberFormatter(format=fmt)) for mm, fmt in metric_formats.iteritems() if mm in metrics_df.columns ] data_table = DataTable(source=s, columns=tbl_columns, width=900, height=200, fit_columns=False) return data_table
def make_page_flow(doc): # return make_document(doc) # if __name__=='__main__': # df = pd.read_csv('salary_data.csv') # else: # # df = pd.read_csv('./bokeh_pages/salary_data.csv') df = pd.read_csv(fileName_csv_source) # source = ColumnDataSource(data=dict()) def update(): print ("slider update") # current = df[df['salary'] <= slider.value].dropna() # df ## # adjustment by https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/fPAoHTyMcuQ current = df[df['salary'] <= slider.value].dropna() # df ## # print (list(current.name)) # print (type(current.salary)) # <class 'pandas.core.series.Series'> # print (type(current.years_experience)) source.data = { 'name' : list(current.name), 'salary' : list(current.salary), 'years_experience' : list(current.years_experience), } slider = Slider(title="values range", start=0, end=100000, value=20000, step=1) slider.on_change('value', lambda attr, old, new: update()) def on_button_change(): print("visiting on button change") button = Button(label="Phase #1 ", button_type="success") # button_type: ‘default’, ‘primary’, ‘success’, ‘warning’, ‘danger’, ‘link’ button.on_click(on_button_change) # button.callback = CustomJS(args=dict(source=source), # code=open(join(dirname(__file__), "download.js")).read()) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) controls = widgetbox(slider, button) table = widgetbox(data_table) total_row = row(controls, table) doc_add_root(doc, total_row, title = 'work flow page') # if __name__!='__main__': # print("doc : ", str(doc)) # print("name : ",__name__) # doc().add_root(row(controls, table)) # doc().title = "work flow page, from caller" # elif __name__=='__main__': # print("doc : ", str(doc)) # doc.add_root(row(controls, table)) # doc.title = "work flow page, from main" update()
def outcome(width, height): df = pd.read_sql( """SELECT [A].[COL], [A].[VALUE] FROM ( SELECT [T1].[Koszt], [T1].[Wartość], [T2].[Przychody], [T3].[Premium] FROM (SELECT -SUM([CURR_COST]) AS [Koszt], SUM([CURR_VALUE]) AS [Wartość] FROM [PORTFEL_VW]) AS [T1], (SELECT SUM([SEC_VALUE]) AS [Przychody] FROM [TRANSAKCJE] WHERE [POZYCJA] IN (2,3)) AS [T2], (SELECT [ROK], SUM([VAL]) AS [Premium] FROM [PREMIUM_VW] WHERE [ROK] = YEAR(GETDATE()) GROUP BY [ROK]) AS [T3]) AS [T] CROSS APPLY (VALUES ('Koszt', [Koszt]), ('Wartość',[Wartość]), ('Bilans',[Koszt] + [Wartość]), ('Przychody',[Przychody]), ('Wynik',[Koszt] + [Wartość] + [Przychody]), ('Przychody w tym roku',[Premium]), ('ROI',-[Premium]/[Koszt]*100) ) AS [A] ([COL],[VALUE])""", conn) #dane source = ColumnDataSource(data=df) #kolumny columns = [ TableColumn(field="COL", title='Podsumowanie'), TableColumn(field="VALUE", title='', width=int(width / 2 * 3), formatter=NumberFormatter(format='(0,0.00)')) ] #tabela t = DataTable(source=source, columns=columns, width=width, height=height) t = finalize_table(t, True, False, False, False) return t
def plot_data(train_loss, test_loss, lr_values, file_name): output_file(file_name) f = figure() f.title.text = "Loss" f.plot_width = 640 f.plot_height = 480 epoches, train_losses = zip(*train_loss) _, test_losses = zip(*test_loss) _, learning_rates = zip(*lr_values) f.line(epoches, train_losses, color='blue', legend="Train loss", line_width=2) f.line(epoches, test_losses, color='red', legend="Test loss", line_width=2) f.xaxis.axis_label = "Epoch" f.yaxis.axis_label = "LogLoss" f_lr = figure() f_lr.title.text = "Learning rate" f_lr.plot_width = 640 f_lr.plot_height = 480 f_lr.line(epoches, learning_rates, color='blue', legend="LR", line_width=2) f_lr.xaxis.axis_label = "Epoch" # table with data source = ColumnDataSource({ 'epoch': epoches, 'train_loss': train_losses, 'test_loss': test_losses, 'lr': learning_rates }) columns = [ TableColumn(field='epoch', title='Epoch'), TableColumn(field='train_loss', title='Train loss', formatter=NumberFormatter(format="0.0000")), TableColumn(field='test_loss', title='Test loss', formatter=NumberFormatter(format="0.0000")), TableColumn(field='lr', title='LR', formatter=NumberFormatter(format="0.0000")), ] data_table = DataTable(source=source, columns=columns, width=1200, height=600) save(column(row(f, f_lr), data_table))
def tabular(self): os.chdir(self.sa) DF_ag=NumberFormatter(format="0.00") columns = [ TableColumn(field="t", title="Tiempo"), TableColumn(field="al",title="Elevación (Grados)",formatter=DF_ag,sortable=True), TableColumn(field="az",title="Azimut (Grados)",formatter=DF_ag,sortable=True) ] data_table = DataTable(source=self.source, columns=columns ,width=450, height=450) save(data_table,"data_table.html",validate=True) os.chdir(self.raiz)
def _create_top_services_tbl(): """Creates top services table""" global GLOBAL_SUB_SERVICE_GRP global GLOBAL_TOP_SERVICE_SOURCE # Top services table cols = [] for col in GLOBAL_SUB_SERVICE_GRP.columns: if col == CONST_COL_NAME_COST: cols.append( TableColumn( field=col, title=col, formatter=NumberFormatter(format="$0,0[.]00", text_align="right", language="it"), width=100, )) elif col == CONST_COL_NAME_PERC: cols.append( TableColumn( field=col, title=col, formatter=NumberFormatter(format="0,0[.]00%", text_align="right", language="it"), width=50, )) elif col in [CONST_COL_NAME_ANGLE, "color"]: continue else: cols.append(TableColumn(field=col, title=col)) top_services_table = DataTable(columns=cols, source=GLOBAL_TOP_SERVICE_SOURCE, width=400) return top_services_table
def _get_columns(self): if self.value is None: return [] index = [self.value.index.name or 'index'] col_names = index + list(self.value.columns) columns = [] for col in col_names: if col in self.value.columns: data = self.value[col] else: data = self.value.index kind = data.dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif isdatetime(data) or kind == 'M': formatter = DateFormatter(format='%Y-%m-%d %H:%M:%S') editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() if col in self.editors: editor = self.editors[col] if col in self.formatters: formatter = self.formatters[col] if str(col) != col: self._renamed_cols[str(col)] = col width = self.widths.get(str(col)) column = TableColumn(field=str(col), title=str(col), editor=editor, formatter=formatter, width=width) columns.append(column) return columns
def divdeamon(width, height): df = pd.read_sql( """WITH [N] AS ( SELECT [ISIN], [ZAMKNIECIE] FROM [NOTOWANIA_GPW] WHERE [DATA] = (SELECT MAX(DATA) FROM [NOTOWANIA_GPW]) ) SELECT [D].[DATA_PRAW] AS [TERMIN], [D].[NAZWA], [D].[ISIN], [D].[DATA_WYP] AS [WYPŁATA], [D].[VAL] AS [DYWIDENDA], [N].[ZAMKNIECIE] AS [KURS], [D].[VAL] / [N].[ZAMKNIECIE] AS [%] FROM [DYWIDENDY] AS [D], [N] WHERE [D].[ISIN] = [N].[ISIN] AND [D].[DATA_PRAW] < DATEADD(DAY, 30, GETDATE()) AND [D].[DATA_PRAW] > DATEADD(DAY, 3, GETDATE()) ORDER BY [D].[DATA_PRAW]""", conn) #dane source = ColumnDataSource(data=df) #kolumny columns = [ TableColumn(field="TERMIN", title="Termin", width=125), TableColumn(field="NAZWA", title="Spółka"), TableColumn(field="ISIN", title="ISIN", width=200), TableColumn(field="WYPŁATA", title="Data wypłaty", width=125), TableColumn(field="DYWIDENDA", title="Dywidenda", formatter=NumberFormatter(format='0.00'), width=85), TableColumn(field="KURS", title="Kurs", formatter=NumberFormatter(format='0.00'), width=65), TableColumn(field="%", title="%", formatter=NumberFormatter(format='0.00%'), width=65), ] #tabela t = DataTable(source=source, columns=columns, width=width, height=height) t = finalize_table(t, True, False, False, True) return t
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 tabela_orcamento(source_gastos, gastos_cols, gastos_cols_titles, plot_width): columns_gastos = [ TableColumn(field=col, title=title) for col, title in zip( gastos_cols, gastos_cols_titles, ) ] columns_gastos[-1].formatter = NumberFormatter(format='0,0.00', language='pt-br', text_align='right') columns_gastos[-2].formatter = NumberFormatter(format='0,0.00', language='pt-br', text_align='right') tabela = DataTable( source=source_gastos, columns=columns_gastos, row_headers=False, fit_columns=True, width=plot_width, ) return tabela
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 make_page_flow(doc): # return make_document(doc) # if __name__=='__main__': # df = pd.read_csv('salary_data.csv') # else: # # df = pd.read_csv('./bokeh_pages/salary_data.csv') df = pd.read_csv(fileName) # source = ColumnDataSource(data=dict()) def update(): print ("slider update") current = df[df['salary'] <= slider.value].dropna() # df ## source.data = { 'name' : current.name, 'salary' : current.salary, 'years_experience' : current.years_experience, } slider = Slider(title="values range", start=0, end=100000, value=50000, step=1) slider.on_change('value', lambda attr, old, new: update()) def on_button_change(): print("visiting on button change") button = Button(label="phase #1 ", button_type="success") # button_type: ‘default’, ‘primary’, ‘success’, ‘warning’, ‘danger’, ‘link’ button.on_click(on_button_change) # button.callback = CustomJS(args=dict(source=source), # code=open(join(dirname(__file__), "download.js")).read()) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) controls = widgetbox(slider, button) table = widgetbox(data_table) if __name__!='__main__': print("doc : ", doc) print("name : ",__name__) doc().add_root(row(controls, table)) doc().title = "work flow page, from caller" elif __name__=='__main__': doc.add_root(row(controls, table)) doc.title = "work flow page, from main" # if __name__=='__main__': update()
def __define_layout_objects(self): # Report heading data self.select_plan = Select(title='Plan:', width=400) self.button_refresh_plans = Button(label='Scan DICOM Inbox', button_type='primary') self.select_protocol = Select(title='Protocol:', options=self.protocols.protocol_names, value='TG101', width=150) self.select_fx = Select(title='Fractions:', value='3', options=self.fractionation_options, width=60) self.button_calculate = Button(label='Calculate Scorecard', button_type='primary') self.button_delete_roi = Button(label='Delete Constraint', button_type='warning') self.button_calculate_dvhs = Button(label='Calculate DVHs', button_type='primary', width=200) self.select_roi_template = Select(title='Template ROI:') self.select_roi = Select(title='Plan ROI:') self.max_dose_volume = Div(text="<b>Point defined as %scc" % MAX_DOSE_VOLUME) self.columns = [TableColumn(field="roi_template", title="Template ROI"), TableColumn(field="roi_name", title="ROI"), TableColumn(field='volume', title='Volume (cc)', formatter=NumberFormatter(format="0.00")), TableColumn(field='min_dose', title='Min Dose (Gy)', formatter=NumberFormatter(format="0.00")), TableColumn(field='mean_dose', title='Mean Dose (Gy)', formatter=NumberFormatter(format="0.00")), TableColumn(field='max_dose', title='Max Dose (Gy)', formatter=NumberFormatter(format="0.00")), TableColumn(field='constraint', title='Constraint'), TableColumn(field='constraint_calc', title='Value', formatter=NumberFormatter(format="0.00")), TableColumn(field='pass_fail', title='Pass/Fail', formatter=self.__pass_fail_formatter)] self.data_table = DataTable(source=self.source_data, columns=self.columns, index_position=None, width=1000, height=300) tools = "pan,wheel_zoom,box_zoom,reset,crosshair,save" self.plot = figure(plot_width=800, plot_height=475, tools=tools, active_drag="box_zoom") # Set x and y axis labels self.plot.xaxis.axis_label = "Dose (Gy)" self.plot.yaxis.axis_label = "Normalized Volume" self.plot.min_border_left = 60 self.plot.min_border_bottom = 60 self.plot.add_tools(HoverTool(show_arrow=False, line_policy='next', tooltips=[('Plan ROI', '@roi'), ('Dose', '$x'), ('Volume', '$y')])) self.plot.xaxis.axis_label_text_font_size = "12pt" self.plot.yaxis.axis_label_text_font_size = "12pt" self.plot.xaxis.major_label_text_font_size = "10pt" self.plot.yaxis.major_label_text_font_size = "10pt" self.plot.yaxis.axis_label_text_baseline = "bottom" self.plot.lod_factor = 100 # level of detail during interactive plot events self.plot.multi_line('x', 'y', source=self.source_plot, selection_color='color', line_width=3, alpha=0, line_dash='solid', nonselection_alpha=0, selection_alpha=1) columns = [TableColumn(field="roi", title="Select Structures to Plot")] self.plot_rois = DataTable(source=self.source_plot, columns=columns, index_position=None, width=200, height=350)
def __init__(self,data): tfmt = DateFormatter(format="%M:%S") tfmt = NumberFormatter(format="00:00:00") self.metadata = [ self.generateTableMetadataEntry(field="name", title="Time",width=3,formatter=tfmt), self.generateTableMetadataEntry(field="lyrics", title="Lyrics",width=50), ] dictionary = { "title":"Lyrics", "data":data, "metadata":self.metadata } self.createTable(dictionary)
def convert_df(df): columns = [] for column in df.columns: if df.dtypes[column].kind == 'f': formatter = NumberFormatter(format='0.000') else: formatter = None table_col = TableColumn(field=column, title=column, formatter=formatter) columns.append(table_col) data_table = DataTable(columns=columns, source=ColumnDataSource(df), height=200) return data_table
def worker_table_plot(width=600, height="auto", **kwargs): """ Column data source and plot for host table """ names = [ 'workers', 'cpu', 'memory-percent', 'memory', 'cores', 'processes', 'processing', 'latency', 'last-seen', 'disk-read', 'disk-write', 'network-send', 'network-recv' ] source = ColumnDataSource({k: [] for k in names}) columns = {name: TableColumn(field=name, title=name) for name in names} slow_names = [ 'workers', 'cores', 'processes', 'memory', 'latency', 'last-seen' ] slow = DataTable(source=source, columns=[columns[n] for n in slow_names], width=width, height=height, **kwargs) slow.columns[3].formatter = NumberFormatter(format='0.0 b') slow.columns[4].formatter = NumberFormatter(format='0.00000') slow.columns[5].formatter = NumberFormatter(format='0.000') fast_names = [ 'workers', 'cpu', 'memory-percent', 'processing', 'disk-read', 'disk-write', 'network-send', 'network-recv' ] fast = DataTable(source=source, columns=[columns[n] for n in fast_names], width=width, height=height, **kwargs) fast.columns[1].formatter = NumberFormatter(format='0.0 %') fast.columns[2].formatter = NumberFormatter(format='0.0 %') fast.columns[4].formatter = NumberFormatter(format='0 b') fast.columns[5].formatter = NumberFormatter(format='0 b') fast.columns[6].formatter = NumberFormatter(format='0 b') fast.columns[7].formatter = NumberFormatter(format='0 b') table = vplot(slow, fast) return source, table
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.title = Paragraph(text=TITLE) self.data_table = DataTable( source=self.source, width=390, height=275, columns=[ TableColumn(field="zipcode", title="Zipcodes", width=100), TableColumn(field="population", title="Population", width=100, formatter=NumberFormatter(format="0,0")), TableColumn(field="city", title="City") ]) return column(self.title, self.data_table)
def update(): var = 'newsalaryperfte' if selectVariable.value == 'Previous Salary (AY 2016-2017)': var = 'cursalaryperfte' campus = selectCampus.value if campus == 'All': campusSelection = (salaries.campus == salaries.campus) else: campusSelection = (salaries.campus == campus) college = selectCollege.value if college == 'All': collegeSelection = (salaries.college == salaries.college) else: collegeSelection = (salaries.college == college) def p25(x): return x.quantile(0.25) def p75(x): return x.quantile(0.75) df = salaries.loc[campusSelection & collegeSelection].groupby([ 'campus', 'college', 'dept' ])[var].agg(['size', 'count', 'min', p25, 'median', p75, 'max', gini]).reset_index() columns = [ TableColumn(field='campus', title='Campus'), TableColumn(field='college', title='College'), TableColumn(field='dept', title='Department'), TableColumn(field='size', title='# of Employees'), TableColumn(field='count', title='# with Data'), TableColumn(field='min', title='Min', formatter=NumberFormatter(format="$0,0")), TableColumn(field='p25', title='25th Percentile', formatter=NumberFormatter(format="$0,0")), TableColumn(field='median', title='Median', formatter=NumberFormatter(format="$0,0")), TableColumn(field='p75', title='75th Percentile', formatter=NumberFormatter(format="$0,0")), TableColumn(field='max', title='Max', formatter=NumberFormatter(format="$0,0")), TableColumn(field='gini', title='Gini Coefficient', formatter=NumberFormatter(format="0.000")), ] # Note: there is a bug where the last row of the DataTable cuts off. This appears to be a bug in Bokeh to which there is currently no workaround. l.children[2] = DataTable(source=ColumnDataSource(df), columns=columns, height=650, width=1600, selectable=True, scroll_to_selection=True)
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 make_table(): if __name__ == '__main__': df = pd.read_csv('salary_data.csv') else: # df = pd.read_csv('./bokeh_pages/salary_data.csv') df = pd.read_csv('salary_data.csv') source = ColumnDataSource(data=dict()) def update(): current = df[df['salary'] <= slider.value].dropna() source.data = { 'name': current.name, 'salary': current.salary, 'years_experience': current.years_experience, } slider = Slider(title="Max Salary", start=10000, end=250000, value=150000, step=1000) slider.on_change('value', lambda attr, old, new: update()) button = Button(label="Download", button_type="success") button.callback = CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read()) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) controls = widgetbox(slider, button) table = widgetbox(data_table) curdoc().add_root(row(controls, table)) curdoc().title = "Export CSV" update()
def wallettable(width, height): #kwerenda do wyciągania przychodów df = pd.read_sql("""SELECT * FROM [PORTFEL_VW]""", conn) #dane source = ColumnDataSource(data=df) #formatowanie warunkowe cndtemplate = """ <div style="color:<%= (function colorfromint(){ if(value < 0){ return("red")} else{return("green")} }()) %>"> <%= (value).toFixed(2) %></div> """ cndformatter = HTMLTemplateFormatter(template=cndtemplate) #kolumny columns = [ TableColumn(field="NAZWA", title="Nazwa"), TableColumn(field="CURR_COUNT", title="Pakiet"), TableColumn(field="PUR_PRICE", title="Zakup", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="PRICE_TODAY", title="Obecnie", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="PRICE_MIN", title="Próg", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="CURR_COST", title="Koszt całk.", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="CURR_VALUE", title="Wart. całk.", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="TAX", title="Podatek", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="YIELD", title="Zysk", formatter=cndformatter), TableColumn(field="%", title="%", formatter=NumberFormatter(format='0,0.00%')) ] #tabela t = DataTable(source=source, columns=columns, width=width, height=height) t = finalize_table(t, True, False, False, False) return t
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 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