def datatable_columns(df): for c, t in df.dtypes.items(): formatter = None # TODO also use col name.. then won't have to handle nans! width = 15 # in characters # for fixed width types, we can have something kind of reasonable if str(t).startswith('float'): l = df[c].dropna().map(str).str.len().max() width = 4 if np.isnan(l) else l if str(t).startswith('datetime'): formatter = DateFormatter(format='%Y%m%d %H%M%S %Z', nan_format='Nan') width = 15 elif str(t).startswith('timedelta'): # TODO warn if df contains stuff with duration >1D? # without nan_format, it results in NaN:Nan:Nan formatter = DateFormatter(format='%H:%M:%S', nan_format='Nan') width = 8 # if c == 'error': # # meh, but the only easy way to limit and ellipsize it I found # # aaand it still computes width in some weird way, ends up taking too much space # formatter = HTMLTemplateFormatter(template='<div style="text-overflow: ellipsis; overflow: hidden; width: 60ch;"><%= value %></div>') tc = TableColumn( field=c, title=c, **({} if formatter is None else dict(formatter=formatter)), width=width * one_char, ) yield tc
def get_expenses_table(selected_month=None, category=None): table_columns = [ TableColumn(field='Date', title='Date', formatter=DateFormatter()), TableColumn(field='Description', title='Description'), TableColumn(field='Category', title='Category'), TableColumn(field='Subcategory', title='Subcategory'), TableColumn(field='Cost', title='Cost') ] # which month is currently selected? subset data according to selection if selected_month is None: month_filter = [True] * len(expenses_source.data['Date']) else: source_datetimes = pd.DatetimeIndex(expenses_source.data['Date']) month_filter = [ date.month == selected_month for date in source_datetimes ] month_filter = BooleanFilter(month_filter) # filter for current category if category is None: category_filter = [True] * len(expenses_source.data['Category']) else: category_filter = [ cat == category for cat in expenses_source.data['Category'] ] category_filter = BooleanFilter(category_filter) view = CDSView(source=expenses_source, filters=[month_filter, category_filter]) return DataTable(source=expenses_source, columns=table_columns, view=view, sizing_mode='stretch_both')
def create_outages_datatable(df): #p("datatable columns\n"+df.columns) from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn datefmt = DateFormatter(format="dd M yy h:mm") df['startdate'] = pd.to_datetime(df['startdate'], unit='s').astype(str) df['finishdate'] = pd.to_datetime(df['finishdate'], unit='s').astype(str) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s').astype(str) source = ColumnDataSource(df) p(dir(TableColumn)) columns = [ TableColumn(field="startdate", title="Start"), TableColumn(field="finishdate", title="Finish"), TableColumn(field="availability", title="%", width=16), TableColumn(field="timestamp", title="Updated At"), ] table_height = len(df) * 24 + 30 data_table = DataTable(source=source, columns=columns, row_headers=True, width=600, height=table_height, sizing_mode='scale_both') return source, data_table
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 make_layout(): import pandas as pd plot, source = make_plot() template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>""" columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] df = pd.DataFrame([ ['this is a longer text that needs a tooltip, because otherwise we do not see the whole text', 'this is a short text'], ['this is another loooooooooooooooong text that needs a tooltip', 'not much here'], ], columns=['a', 'b']) columns = [TableColumn(field=c, title=c, width=20, formatter=HTMLTemplateFormatter(template=template)) for c in ['a', 'b']] source = ColumnDataSource(data=df) data_table = DataTable(source=source, columns = columns) l = layout([[data_table]]) return l data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", button_type="success") button.on_click(click_handler) buttons = WidgetBox(children=[button], width=400) column = Column(children=[buttons, plot, data_table]) return column
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 generate_table(title, cds, tooltip): print "cds column_names:", cds.column_names columns = [ TableColumn(field='AAPL_x', title='Date', formatter=DateFormatter()), TableColumn(field='AAPL_y', title='Price') ] data_table = DataTable(source=cds, columns=columns) # could use a widgetbox is multiple tables were involved script, div = components(data_table) return {'script': script, 'div': div}
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 generate(): # Obtain both the matches and item JSONS matches = getItems(suffix='matches', apiKey=apiKey) items = getItems(suffix='items', apiKey=apiKey) # Convert both to dataframe match_df = pd.DataFrame(matches) item_df = pd.DataFrame(items) # Filter to only the relevant columns item_df = item_df[['_id', 'bought', 'minPrice']] item_df = item_df.rename(columns={'bought': 'bought_item'}) match_df = match_df[['itemID', 'bought', 'matchedPrice', 'dateBought']] match_df['dateBought'] = pd.to_datetime(match_df['dateBought'], yearfirst=True, exact=False, format='%y-%m-%d') match_df = match_df.rename(columns={'bought': 'bought_match'}) # Merge DFs on item ids matched_items = match_df.merge(item_df, how='left', left_on='itemID', right_on='_id') matched_items = matched_items.loc[matched_items['bought_match'] == 1] matched_items['Profit'] = (matched_items['matchedPrice'] - matched_items['minPrice']) matched_items = matched_items.reset_index(drop=True) output_file('templates/sales-data.html') source = ColumnDataSource(matched_items) columns = [ TableColumn(field="dateBought", title="Date", formatter=DateFormatter(format='dd/mm/yy')), TableColumn(field="matchedPrice", title="Matched Price"), TableColumn(field="minPrice", title="Posted Price"), TableColumn(field="Profit", title="Profit") ] data_table = DataTable(source=source, columns=columns, width=600, height=500) save(widgetbox(data_table)) #t = app.jinja_environment.get_template(name='sales-data.html') #return(t) return (render_template('sales-data.html'))
def table_columns_from_df(df, minwidth=30, maxwidth=180): charToPix = 6 tcs = [] for col in df.columns: dt = df.dtypes[col] maxlen = min(df[col].str.len().max() if dt == object else minwidth, maxwidth) colwidth = maxlen * charToPix if dt == '<M8[ns]': tcs.append(TableColumn(field=col, title=col, width=colwidth, formatter=DateFormatter(format='%F %T.%N'))) else: tcs.append(TableColumn(field=col, width=colwidth, title=col)) return tcs
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 tableau(request): # # #source = ColumnDataSource(data=dict()) # # s1 = figure(width=250, plot_height=250, title=None) button = Button(label="Foo") # # # 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) # # table = widgetbox(data_table) # l = layout([widgetbox(button)]) # script, div = components(l) # print(script) # print(div) data = dict( dates=[date(2014, 3, i + 1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) table = widgetbox(data_table) w1 = Slider(start=0, end=10, value=1, step=.1, title="Stuff") script, div = components(widgetbox(button_group, w1)) return render_to_response( 'index.html', { 'title': 'Beautifulll', 'js_resources': js_resources, 'css_resources': css_resources, 'plot_script': script, 'plot_div': div })
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 __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 make_columns(name): new_data = get_data(name) source = ColumnDataSource(data=new_data) columns = [ TableColumn(field="Area", title="Area"), TableColumn(field="Date", title="Date", formatter=DateFormatter()), TableColumn(field="micro", title="μmol"), TableColumn(field="mg", title="mg/L"), TableColumn(field="horiba", title="Horiba"), TableColumn(field="merck", title="Merck"), TableColumn(field="F(Horiba)", title="F(Horiba)"), TableColumn(field="F(Merck)", title="F(Merck)") ] return DataTable(source=source, columns=columns, width=720, height=500)
def getColumns(): columns = [ TableColumn(field="dates", title="QuestionID", formatter=DateFormatter()), TableColumn(field="downloads", title="UserID"), TableColumn(field="Asked", title="Asked"), TableColumn(field="title", title="Title"), TableColumn(field="body", title="Body"), TableColumn(field="Asked", title="Asked"), TableColumn(field="title", title="Title"), TableColumn(field="body", title="Body"), ] return columns
def data_table(): data = dict( dates=[date(2014, 3, i + 1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) return data_table
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 update(attr, old, new): capteur_to_plot = [ capteur_selection.labels[i] for i in capteur_selection.active ] l = text_input.value L_text = [] for val in l.split('\n'): L_text.append(val) text_input_start = L_text[1] text_input_end = L_text[4] nom_capteur = select.value new_src = make_dataset(capteur_to_plot, text_input_start, text_input_end, nom_capteur, L_influx) new_source = ColumnDataSource(new_src) dictio = {} for i in range(0, len(new_src.columns)): dictio[new_src.columns[i]] = new_src[new_src.columns[i]] source.data = dictio table_columns = [ TableColumn(field='Date', title='Date', formatter=DateFormatter(format="%m/%d/%Y %H:%M:%S")) ] colonne = new_src.columns colonne = colonne.delete(0) table_columns += [TableColumn(field=col, title=col) for col in colonne] datatable.columns = table_columns liste = [k for k in range(0, 10)] longueur = new_src.shape[0] for k in range(longueur - 10, longueur): liste.append(k) view1 = CDSView(source=new_source, filters=[IndexFilter(indices=liste)]) datatable.view = view1
def get_bokeh_component(): plot = figure() plot.circle([1,2], [3,4]) script, div = components(plot) data = dict( dates=[date(2014, 3, i + 1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) script2, div2 = components(data_table) return script+script2, div, div2
def getBokehComponent(self): ## First, we construct the data source source = ColumnDataSource(self.data) source.selected.on_change('indices', self.getCallback()) #source.on_change('selected', callback_in) columns = [] for k in self.data.keys(): if k in self.date_keys: #print(k) columns.append(TableColumn(field=k, title=k, formatter=DateFormatter(format="%m/%d/%Y %H:%M:%S"))) else: columns.append(TableColumn(field=k, title=k)) if 'height' in self._settings: data_table = DataTable(source=source, columns=columns, width=self._settings['width'], height=self._settings['height']) else: data_table = DataTable(source=source, columns=columns, width=self._settings['width']) # assign class variables self.data_table = data_table self.source = source return self.data_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 bkapp_table(doc): """Create a Table App Arguments: doc {Document} -- bokeh document Returns: Document -- updated bokeh document """ data = sea_surface_temperature.copy() data.reset_index(inplace=True) source = ColumnDataSource(data=data) columns = [ TableColumn(field='time', title='Time', formatter=DateFormatter(format='yy-mm-dd')), TableColumn(field='temperature', title='Temperature') ] data_table = DataTable(source=source, columns=columns, width=400, selectable='checkbox', index_position=None) doc.theme = Theme(filename=os.path.join(cwd(), 'theme.yaml')) return doc.add_root(data_table)
def _create_data_table(source: ColumnDataSource, schema: ProcSchema, legend_col: str = None): """Return DataTable widget for source.""" column_names = [ schema.user_name, schema.user_id, schema.logon_id, schema.process_id, schema.process_name, schema.cmd_line, schema.parent_id, schema.parent_name, schema.target_logon_id, ] if legend_col and legend_col not in column_names: column_names.append(legend_col) date_fmt = "%F %T" columns = [ TableColumn( field=schema.time_stamp, title=schema.time_stamp, formatter=DateFormatter(format=date_fmt), ) ] columns2 = [ TableColumn(field=col, title=col) for col in column_names if col in source.column_names ] data_table = DataTable(source=source, columns=columns + columns2, width=950, height=150) return data_table
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 make_tracks_figure(doc): """ Create a Bokeh app for visualization of the tracks of hurricanes """ df = pd.read_csv('files/df_full_tracks_bokeh.csv', index_col=0, parse_dates=['Time']) # Remove last entry for each hurricane, add steps numbering, year_start, year_end, zone start df.dropna(subset=['x_end'], inplace=True) df.sort_values(by=['ID', 'Time'], inplace=True) steps = df.groupby(by='ID').Time.count() times = df.groupby(by='ID').Time.first() zones = df.groupby(by='ID').Zones.first() df['Step'] = [i for hur in steps.index for i in range(steps[hur])] df['Year_start'] = [times[hur].year for hur in steps.index for i in range(steps[hur])] df['Month_start'] = [times[hur].month for hur in steps.index for i in range(steps[hur])] df['Zones_start'] = [zones[hur]for hur in steps.index for i in range(steps[hur])] # Convert knots to km/h df['Max_Speed'] = df['Max_Speed'] * 1.852 # ----------------------------------------------------- # FIGURE # ----------------------------------------------------- year_min, year_max, lon_boundaries, lat_boundaries = get_boundaries(df) gulf_stream_lon1, gulf_stream_lon2, gulf_stream_lat1, gulf_stream_lat2 = get_gulf_stream() # credits of the map url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" add_paragraph = additional_legend(loc='spawns') # ----------------------------------------------------- # WIDGETS # ----------------------------------------------------- # definition and configuration of the number selection options_number = ['-1'] + [str(x) for x in list(np.arange(1, 21))] select_number = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection options_zone = ['All', 'Mexico_Caribbean', 'Atlantic'] select_zone = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and month sliders slider_year = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") slider_month = RangeSlider(start=1, end=12, value=(1, 12), step=1, title="Months") # definition and configuration of the number selection # select_number_season = Select(title='Number of hurricanes:', value='5', # options=options_number) # definition and configuration of the zone selection # select_zone_season = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and sliders # slider_year_season = RangeSlider(start=year_min, end=year_max, # value=(year_min, year_max), step=1, title="Years") # definition and configuration of the season selection # options_season = ['All', 'Winter', 'Spring', 'Summer', 'Autumn'] # select_season = Select(title='Season:', value='All', options=options_season) # ------------------------------------------------------- # DATA SOURCE AND RANDOMIZATION # ------------------------------------------------------- np.random.seed(42) n = 5 select_list = list(np.random.choice(df.ID.unique(), size=n, replace=False)) filtr = df.ID.map(lambda x: x in select_list) source = ColumnDataSource(data=df[filtr]) # Initialization of the map p = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c1 = p.circle(x='x_start', y='y_start', fill_color='green', size=5, source=source) c2 = p.circle(x='x_end', y='y_end', fill_color='green', size=5, source=source) # Line between start and end points s1 = p.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Configuration of the hovertool hover = HoverTool(tooltips=[("ID", "@ID"), ("Step", "@Step"), ("Distance", "@Distance")], renderers=[c1]) p.tools.append(hover) # Draw the Gulf Stream p.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p.legend.location = "top_left" # DataFrame display no_cols = ['x_start', 'x_end', 'y_start', 'y_end', 'Zones_start', 'ID', 'Time'] cols = ([TableColumn(field='ID', title='ID')] + [TableColumn(field='Time', title='Time', formatter=DateFormatter(format="%d/%m/%Y %H:%M"))] + [TableColumn(field=col, title=col) for col in df.columns if col not in no_cols]) data_table = DataTable(columns=cols, source=source, width=1100, selectable=False) # updating process of the data underlying the map depending on user actions. def update_map_se(attr, old, new): yr = slider_year.value month = slider_month.value zone = select_zone.value n = select_number.value n = int(n) if zone == 'All': df_temp = df.loc[(df['Year_start'] >= yr[0]) & (df['Year_start'] <= yr[1]) & (df['Month_start'] >= month[0]) & (df['Month_start'] <= month[1])] else: df_temp = df.loc[(df.Zones_start == zone) & (df['Year_start'] >= yr[0]) & (df['Year_start'] <= yr[1]) & (df['Month_start'] >= month[0]) & (df['Month_start'] <= month[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.ID.unique(), size=n, replace=False)) filtr = df_temp.ID.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) # activation of the changes on user action select_number.on_change('value', update_map_se) slider_year.on_change('value', update_map_se) slider_month.on_change('value', update_map_se) select_zone.on_change('value', update_map_se) layout = column(row(column(slider_year, slider_month, select_number, select_zone), p, add_paragraph), data_table) # Make document doc.add_root(layout) doc.title = 'Hurricanes_Tracks' doc.theme = Theme(filename="theme.yaml")
line0.visible = true; } else if (cb_obj.active == 2){ line1.visible = true; line0.visible = false; } else if (cb_obj.active == 0){ line1.visible = true; line0.visible = true; } """) # Datatable functionality table_data = dict(dates=df['date'], count=df['count']) table_source = ColumnDataSource(table_data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="count", title="Abort Count"), ] data_table = DataTable(source=table_source, columns=columns, width=400, height=280) # Structure the widgets/charts in a layout show(widgetbox(data_table)) inputs = widgetbox([timeframe, radios]) l = layout([ [inputs, my_plot], [data_table],
range_rool.overlay.fill_color = "navy" range_rool.overlay.fill_alpha = 0.2 #select.line('date', 'sy_max', source=source) add_plot_lines(select, source, plot_sources, Spectral6) select.ygrid.grid_line_color = None select.add_tools(range_rool) select.toolbar.active_multi = range_rool select.background_fill_color = "#f5f5f5" select.grid.grid_line_color = "white" select.x_range.range_padding = 0.01 # define a tabela columns = [ TableColumn(field="date", title="Data", formatter=DateFormatter()), #format="%%Y/%m/%d %H") TableColumn(field="r_max", title="r_max", formatter=NumberFormatter(format="0.000")), TableColumn(field="r_avg", title="r_avg", formatter=NumberFormatter(format="0.000")), TableColumn(field="r_p90", title="r_p90", formatter=NumberFormatter(format="0.000")), TableColumn(field="us_max", title="us_max", formatter=NumberFormatter(format="0.000")), TableColumn(field="us_avg", title="us_avg", formatter=NumberFormatter(format="0.000")),
def create_table(status_dict): """Create interactive ``bokeh`` table containing the logfile status results. Parameters ---------- status_dict : dict Nested dictionary with status results from all logfiles """ # Rearrange the nested dictionary into a non-nested dict for the table filenames = [] dates = [] missings = [] results = [] for key in status_dict: filenames.append(status_dict[key]['logname']) dates.append(datetime.fromtimestamp(status_dict[key]['latest_time'])) missings.append(str(status_dict[key]['missing_file'])) results.append(status_dict[key]['status']) # div to color the boxes in the status column success_template = """ <div style="background:<%= (function colorfromstr(){ if(value == "success"){ return("green")} else{return("red")} }()) %>; color: white"> <%= value %></div> """ # div to color the boxes in the column for possibly late logfiles missing_template = """ <div style="background:<%= (function colorfrombool(){ if(value == "True"){ return("orange")} else{return("green")} }()) %>; color: white"> <%= value %></div> """ success_formatter = HTMLTemplateFormatter(template=success_template) missing_formatter = HTMLTemplateFormatter(template=missing_template) data = dict(name=list(status_dict.keys()), filename=filenames, date=dates, missing=missings, result=results) source = ColumnDataSource(data) datefmt = DateFormatter(format="RFC-2822") columns = [ TableColumn(field="name", title="Monitor Name", width=200), TableColumn(field="filename", title="Most Recent File", width=350), TableColumn(field="date", title="Most Recent Time", width=200, formatter=datefmt), TableColumn(field="missing", title="Possible Missing File", width=200, formatter=missing_formatter), TableColumn(field="result", title="Status", width=100, formatter=success_formatter), ] data_table = DataTable(source=source, columns=columns, width=800, height=280, index_position=None) # Get output directory for saving the table files output_dir = get_config()['outputs'] output_filename = 'cron_status_table' # Save full html html_outfile = os.path.join(output_dir, 'monitor_cron_jobs', '{}.html'.format(output_filename)) output_file(html_outfile) save(data_table) try: set_permissions(html_outfile) except PermissionError: logging.warning( 'Unable to set permissions for {}'.format(html_outfile)) logging.info('Saved Bokeh full HTML file: {}'.format(html_outfile))
date(2010, 12, 29), date(2013, 3, 2), date(2015, 3, 21), date(2017, 1, 1) ] prices = [2.25, 2.25, 2.50, 2.75] pct_change = pd.Series(prices).pct_change() hike_data = dict(start_dates=start_dates, end_dates=end_dates, prices=prices, pct_change=pct_change) hike_data_source = ColumnDataSource(hike_data) columns = [ TableColumn(field='start_dates', title='Start Date', formatter=DateFormatter(format='m/d/yy')), TableColumn(field='end_dates', title='End Date', formatter=DateFormatter(format='m/d/yy')), TableColumn(field='prices', title='Price', formatter=NumberFormatter(format='$0,0.00')), TableColumn(field='pct_change', title='% Change', formatter=NumberFormatter(format='+0.00%')) ] hike_table = DataTable(source=hike_data_source, columns=columns, row_headers=False, sortable=False, selectable=False,