Python bokeh.models.widgets.DataTable() Examples

The following are 21 code examples of bokeh.models.widgets.DataTable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.models.widgets , or try the search function .
Example #1
Source File: population.py    From bigquery-bokeh-dashboard with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: optbrowser.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def modify_document(self, doc):

        controller = self.network.notes[0]
        notes_df = pd.DataFrame(self.network.notes[1]).reset_index()
        notes_df.columns = ["index", "notes"]
        notes = ColumnDataSource(notes_df)
        self.columns = [
            TableColumn(field="index", title="Timestamp"),
            TableColumn(field="notes", title="Notes"),
        ]
        self.data_table = DataTable(source=notes, columns=self.columns)
        layout = row([self.data_table])
        doc.add_root(layout)
        doc.title = "Notes for {}".format(controller)
        # doc.add_periodic_callback(self.update_data,100)
        return doc 
Example #4
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pad_plots(plots):
    """
    Accepts a grid of bokeh plots in form of a list of lists and
    wraps any DataTable or Tabs in a WidgetBox with appropriate
    padding. Required to avoid overlap in gridplot.
    """
    widths = []
    for row in plots:
        row_widths = []
        for p in row:
            width = pad_width(p)
            row_widths.append(width)
        widths.append(row_widths)
    plots = [[WidgetBox(p, width=w) if isinstance(p, (DataTable, Tabs)) else p
              for p, w in zip(row, ws)] for row, ws in zip(plots, widths)]
    return plots 
Example #5
Source File: ui.py    From nlp-architect with Apache License 2.0 5 votes vote down vote up
def _update_events(events: DataTable, in_domain: bool) -> None:
    """Utility function for updating the content of the events table."""
    i = source.selected.indices
    events.source.data.update(
        {
            pol + "_events": stats.loc[aspects[i[0]], pol, in_domain]["Sent_1":].replace(np.nan, "")
            if i
            else []
            for pol in POLARITIES
        }
    ) 
Example #6
Source File: process_tree.py    From msticpy with MIT License 5 votes vote down vote up
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 
Example #7
Source File: ui.py    From nlp-architect with Apache License 2.0 5 votes vote down vote up
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;}
    </style>
    <%= value %>"""
    )
    columns = [
        TableColumn(field="POS_events", title="Positive Examples", formatter=formatter),
        TableColumn(field="NEG_events", title="Negative Examples", formatter=formatter),
    ]
    return DataTable(
        source=ColumnDataSource(),
        columns=columns,
        height=400,
        index_position=None,
        width=2110,
        sortable=False,
        editable=True,
        reorderable=False,
    ) 
Example #8
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 5 votes vote down vote up
def _create_examples_table() -> DataTable:
    """Utility function for creating and styling the events table."""

    formatter = HTMLTemplateFormatter(
        template="""
    <style>
        .AS {color: #0000FF; font-weight: bold;}
        .OP {color: #0000FF; font-weight: bold;}
    </style>
    <div><%= value %></div>"""
    )
    columns = [
        TableColumn(
            field="Examples", title='<span class="header">Examples</span>', formatter=formatter
        )
    ]
    empty_source = ColumnDataSource()
    empty_source.data = {"Examples": []}
    return DataTable(
        source=empty_source,
        columns=columns,
        height=500,
        index_position=None,
        width=1500,
        sortable=False,
        editable=False,
        reorderable=False,
        header_row=True,
    ) 
Example #9
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 5 votes vote down vote up
def _update_events(events: DataTable, in_domain: bool) -> None:
    """Utility function for updating the content of the events table."""
    i = source.selected.indices
    events.source.data.update(
        {
            pol + "_events": stats.loc[aspects[i[0]], pol, in_domain]["Sent_1":].replace(np.nan, "")
            if i
            else []
            for pol in POLARITIES
        }
    ) 
Example #10
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 5 votes vote down vote up
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;}
    </style>
    <%= value %>"""
    )
    columns = [
        TableColumn(field="POS_events", title="Positive Examples", formatter=formatter),
        TableColumn(field="NEG_events", title="Negative Examples", formatter=formatter),
    ]
    return DataTable(
        source=ColumnDataSource(),
        columns=columns,
        height=400,
        index_position=None,
        width=2110,
        sortable=False,
        editable=True,
        reorderable=False,
    ) 
Example #11
Source File: make_plots.py    From Pandas-Bokeh with MIT License 5 votes vote down vote up
def plot_Scatterplot():

    plotname = inspect.stack()[0][3][5:]
    pandas_bokeh.output_file(os.path.join(PLOT_DIR, f"{plotname}.html"))

    df = df_iris()
    df = df.sample(frac=1)

    # Create Bokeh-Table with DataFrame:
    from bokeh.models.widgets import DataTable, TableColumn
    from bokeh.models import ColumnDataSource

    data_table = DataTable(
        columns=[TableColumn(field=Ci, title=Ci) for Ci in df.columns],
        source=ColumnDataSource(df.head(10)),
    )

    # Create Scatterplot:
    p_scatter = df.plot_bokeh.scatter(
        x="petal length (cm)",
        y="sepal width (cm)",
        category="species",
        title="Iris DataSet Visualization",
        show_figure=False,
    )

    # Combine Div and Scatterplot via grid layout:
    pandas_bokeh.plot_grid([[data_table, p_scatter]], plot_width=400, plot_height=350) 
Example #12
Source File: test_bokeh_routines.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_array_to_bokeh_table(self):
        dataframe = DataFrame(self.rng.rand(2, 3), columns=[str(i) for i in range(3)])
        self.assertTrue(isinstance(array_to_bokeh_table(dataframe), DataTable))
        # Pass logger
        self.assertTrue(isinstance(array_to_bokeh_table(dataframe, logger=logging.getLogger('test')), DataTable))
        # Pass sortable and width
        self.assertTrue(isinstance(array_to_bokeh_table(dataframe,
                                                        sortable={'1' : True, '2' : True},
                                                        width={'1' : 100, '0' : 200}),
                                   DataTable))
        # Pass invalid specifications
        self.assertRaises(ValueError, array_to_bokeh_table, dataframe, sortable={'7' : True, '2' : True})
        self.assertRaises(ValueError, array_to_bokeh_table, dataframe, width={'1' : 100, 10 : 200}) 
Example #13
Source File: NeoPredViz.py    From NeoPredPipe with GNU Lesser General Public License v3.0 5 votes vote down vote up
def SummaryTable(self):

        Columns = [TableColumn(field=Ci, title=Ci) for Ci in self.summaryData.columns]  # bokeh columns
        data_table = DataTable(columns=Columns, source=ColumnDataSource(self.summaryData) ,width=1200, height=200)  # bokeh table

        return(data_table) 
Example #14
Source File: NeoPredViz.py    From NeoPredPipe with GNU Lesser General Public License v3.0 5 votes vote down vote up
def EpitopeTable(self):
        Columns = [TableColumn(field=Ci, title=Ci) for Ci in self.neosData.columns]  # bokeh columns
        data_table = DataTable(columns=Columns, source=ColumnDataSource(self.neosData) ,width=1200, height=200)  # bokeh table

        return(data_table) 
Example #15
Source File: client_demo.py    From pairstrade-fyp-2019 with MIT License 5 votes vote down vote up
def build_widgets_wb(stock_list, metrics):
    # CODE SECTION: setup buttons, widgetbox name = controls_wb
    WIDGET_WIDTH = 250

    # ========== Select Stocks ============= #
    select_stk_1 = Select(width = WIDGET_WIDTH, title='Select Stock 1:', value = backtest_params["stk_0"], options=stock_list)
    select_stk_2 = Select(width = WIDGET_WIDTH, title='Select Stock 2:', value = backtest_params["stk_1"], options=stock_list)

    # ========== Strategy Type ============= #
    strategy_list = ['kalman', 'distance', 'cointegration', 'reinforcement learning']
    select_strategy = Select(width = WIDGET_WIDTH, title='Select Strategy:', value = backtest_params["strategy_type"], options=strategy_list)

    # ========== set start/end date ============= #
    # date time variables
    MAX_START = datetime.strptime(backtest_params["max_start"], "%Y-%m-%d").date()
    MAX_END = datetime.strptime(backtest_params["max_end"], "%Y-%m-%d").date()
    DEFAULT_START = datetime.strptime(backtest_params["backtest_start"], "%Y-%m-%d").date()
    DEFAULT_END = datetime.strptime(backtest_params["backtest_end"], "%Y-%m-%d").date()
    STEP = 1

    backtest_dates = DateRangeSlider(width = WIDGET_WIDTH, 
                                     start=MAX_START, end=MAX_END, 
                                     value=(DEFAULT_START, DEFAULT_END), 
                                     step=STEP, title="Backtest Date Range:")

    start_bt = Button(label="Backtest", button_type="success", width = WIDGET_WIDTH)

    # controls = column(select_stk_1, select_stk_2, select_strategy, backtest_dates, start_bt)
    controls_wb = widgetbox(select_stk_1, select_stk_2, select_strategy, backtest_dates, start_bt, width=300)

    # CODE SECTION: setup table, widgetbox name = metrics_wb
    master_wb = None
    if metrics is not None:
        metric_source = ColumnDataSource(metrics)
        metric_columns = [
            TableColumn(field="Metrics", title="Metrics"),
            TableColumn(field="Value", title="Performance"),
        ]

        metric_table = DataTable(source=metric_source, columns=metric_columns, width=300)
        master_wb = row(controls_wb, widgetbox(metric_table))
        
    else:
        logging.info("creating controls without table")
        master_wb = row(controls_wb)
    return master_wb, select_stk_1, select_stk_2, select_strategy, backtest_dates, start_bt 
Example #16
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pad_width(model, table_padding=0.85, tabs_padding=1.2):
    """
    Computes the width of a model and sets up appropriate padding
    for Tabs and DataTable types.
    """
    if isinstance(model, Row):
        vals = [pad_width(child) for child in model.children]
        width = np.max([v for v in vals if v is not None])
    elif isinstance(model, Column):
        vals = [pad_width(child) for child in model.children]
        width = np.sum([v for v in vals if v is not None])
    elif isinstance(model, Tabs):
        vals = [pad_width(t) for t in model.tabs]
        width = np.max([v for v in vals if v is not None])
        for model in model.tabs:
            model.width = width
            width = int(tabs_padding*width)
    elif isinstance(model, DataTable):
        width = model.width
        model.width = int(table_padding*width)
    elif isinstance(model, (WidgetBox, Div)):
        width = model.width
    elif model:
        width = model.plot_width
    else:
        width = 0
    return width 
Example #17
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_plot_size(plot):
    """
    Computes the size of bokeh models that make up a layout such as
    figures, rows, columns, widgetboxes and Plot.
    """
    if isinstance(plot, GridBox):
        ndmapping = NdMapping({(x, y): fig for fig, y, x in plot.children}, kdims=['x', 'y'])
        cols = ndmapping.groupby('x')
        rows = ndmapping.groupby('y')
        width = sum([max([compute_plot_size(f)[0] for f in col]) for col in cols])
        height = sum([max([compute_plot_size(f)[1] for f in row]) for row in rows])
        return width, height
    elif isinstance(plot, (Div, ToolbarBox)):
        # Cannot compute size for Div or ToolbarBox
        return 0, 0
    elif isinstance(plot, (Row, Column, WidgetBox, Tabs)):
        if not plot.children: return 0, 0
        if isinstance(plot, Row) or (isinstance(plot, ToolbarBox) and plot.toolbar_location not in ['right', 'left']):
            w_agg, h_agg = (np.sum, np.max)
        elif isinstance(plot, Tabs):
            w_agg, h_agg = (np.max, np.max)
        else:
            w_agg, h_agg = (np.max, np.sum)
        widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
        return w_agg(widths), h_agg(heights)
    elif isinstance(plot, (Figure, Chart)):
        if plot.plot_width:
            width = plot.plot_width
        else:
            width = plot.frame_width + plot.min_border_right + plot.min_border_left
        if plot.plot_height:
            height = plot.plot_height
        else:
            height = plot.frame_height + plot.min_border_bottom + plot.min_border_top
        return width, height
    elif isinstance(plot, (Plot, DataTable, Spacer)):
        return plot.width, plot.height
    else:
        return 0, 0 
Example #18
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def modify_document(self, doc):
        self.network.whois()
        devices_df = self.network.devices
        dev = ColumnDataSource(devices_df)
        columns = [
            TableColumn(field=" Device ID", title="Dev ID"),
            TableColumn(field="Address", title="Address"),
            TableColumn(field="Manufacturer", title="Manuf"),
            TableColumn(field="Name", title="Name"),
        ]
        data_table = DataTable(source=dev, columns=columns)
        layout = row([data_table])
        doc.add_root(layout)
        doc.title = "BACnet devices"
        return doc 
Example #19
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def modify_document(self, doc):
        self.network.whois()
        devices_df = self.network.devices
        dev = ColumnDataSource(devices_df)
        columns = [
            TableColumn(field=" Device ID", title="Dev ID"),
            TableColumn(field="Address", title="Address"),
            TableColumn(field="Manufacturer", title="Manuf"),
            TableColumn(field="Name", title="Name"),
        ]
        data_table = DataTable(source=dev, columns=columns)
        layout = row([data_table])
        doc.add_root(layout)
        doc.title = "BACnet devices"
        return doc 
Example #20
Source File: plotted_tables.py    From flight_review with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_logged_messages(logged_messages, plot_width):
    """
    get a bokeh widgetbox object with a table of the logged text messages
    :param logged_messages: ulog.logged_messages
    """
    log_times = []
    log_levels = []
    log_messages = []
    for m in logged_messages:
        m1, s1 = divmod(int(m.timestamp/1e6), 60)
        h1, m1 = divmod(m1, 60)
        log_times.append("{:d}:{:02d}:{:02d}".format(h1, m1, s1))
        log_levels.append(m.log_level_str())
        log_messages.append(m.message)
    log_data = dict(
        times=log_times,
        levels=log_levels,
        messages=log_messages)
    source = ColumnDataSource(log_data)
    columns = [
        TableColumn(field="times", title="Time",
                    width=int(plot_width*0.15), sortable=False),
        TableColumn(field="levels", title="Level",
                    width=int(plot_width*0.1), sortable=False),
        TableColumn(field="messages", title="Message",
                    width=int(plot_width*0.75), sortable=False),
        ]
    data_table = DataTable(source=source, columns=columns, width=plot_width,
                           height=300, sortable=False, selectable=False)
    div = Div(text="""<b>Logged Messages</b>""", width=int(plot_width/2))
    return widgetbox(div, data_table, width=plot_width) 
Example #21
Source File: test_PandasBokeh.py    From Pandas-Bokeh with MIT License 4 votes vote down vote up
def test_scatterplot(df_iris):
    "Test for scatterplot"

    # Create Bokeh-Table with DataFrame:
    from bokeh.models.widgets import DataTable, TableColumn
    from bokeh.models import ColumnDataSource

    data_table = DataTable(
        columns=[TableColumn(field=Ci, title=Ci) for Ci in df_iris.columns],
        source=ColumnDataSource(df_iris.head(10)),
    )

    data_table_accessor = DataTable(
        columns=[TableColumn(field=Ci, title=Ci) for Ci in df_iris.columns],
        source=ColumnDataSource(df_iris.head(10)),
    )

    # Create Scatterplot:
    arguments = dict(
        x="petal length (cm)",
        y="sepal width (cm)",
        category="species",
        title="Iris DataSet Visualization",
        show_figure=False,
    )

    p_scatter = df_iris.plot_bokeh(kind="scatter", **arguments)
    p_scatter_accessor = df_iris.plot_bokeh.scatter(**arguments)

    p_scatter_pandas_backend = df_iris.plot(kind="scatter", **arguments)
    p_scatter_accessor_pandas_backend = df_iris.plot.scatter(**arguments)

    # Combine Div and Scatterplot via grid layout:
    output = pandas_bokeh.plot_grid(
        [[data_table, p_scatter], [data_table_accessor, p_scatter_accessor]],
        show_plot=False,
        return_html=True,
    )

    with open(os.path.join(DIRECTORY, "Plots", "Scatterplot.html"), "w") as f:
        f.write(output)

    assert True