Python bokeh.models() Examples

The following are 12 code examples of bokeh.models(). 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 , or try the search function .
Example #1
Source File: axes.py    From chartify with Apache License 2.0 5 votes vote down vote up
def set_xaxis_tick_format(self, num_format):
        """Set x-axis tick label number format.

        Args:
            num_format (string): the number format for the x-axis tick labels

        Examples:
            Decimal precision
            >>> ch.set_xaxis_tick_format('0.0')
            Label format: 1000 -> 1000.0

            Percentage
            >>> ch.set_xaxis_tick_format("0%")
            Label format: 0.9748 -> 97%
            0.974878234 ‘0.000%’    97.488%

            Currency:
            >>> ch.set_xaxis_tick_format('$0,0.00')
            Label format: 1000.234 -> $1,000.23

            Auto formatting:
            >>> ch.set_xaxis_tick_format('0 a')
            Label format: 10000 -> 10 K

            Additional documentation: http://numbrojs.com/old-format.html

        Returns:
            Current chart object
        """
        self._chart.figure.xaxis[0].formatter = (
            bokeh.models.NumeralTickFormatter(format=num_format)
            )
        return self._chart 
Example #2
Source File: axes.py    From chartify with Apache License 2.0 5 votes vote down vote up
def set_yaxis_tick_format(self, num_format):
        """Set y-axis tick label number format.

        Args:
            num_format (string): the number format for the y-axis tick labels

        Examples:
            Decimal precision
            >>> ch.set_yaxis_tick_format('0.0')
            Label format: 1000 -> 1000.0

            Percentage
            >>> ch.set_yaxis_tick_format("0%")
            Label format: 0.9748 -> 97%
            0.974878234 ‘0.000%’    97.488%

            Currency:
            >>> ch.set_yaxis_tick_format('$0,0.00')
            Label format: 1000.234 -> $1,000.23

            Auto formatting:
            >>> ch.set_xaxis_tick_format('0a')
            Label format: 10000 -> 10 K

            Additional documentation: http://numbrojs.com/old-format.html

        Returns:
            Current chart object
        """
        self._chart.figure.yaxis[self._y_axis_index].formatter = (
                bokeh.models.NumeralTickFormatter(format=num_format))
        return self._chart 
Example #3
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 #4
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def recursive_model_update(model, props):
    """
    Recursively updates attributes on a model including other
    models. If the type of the new model matches the old model
    properties are simply updated, otherwise the model is replaced.
    """
    updates = {}
    valid_properties = model.properties_with_values()
    for k, v in props.items():
        if isinstance(v, Model):
            nested_model = getattr(model, k)
            if type(v) is type(nested_model):
                nested_props = v.properties_with_values(include_defaults=False)
                recursive_model_update(nested_model, nested_props)
            else:
                try:
                    setattr(model, k, v)
                except Exception as e:
                    if isinstance(v, dict) and 'value' in v:
                        setattr(model, k, v['value'])
                    else:
                        raise e
        elif k in valid_properties and v != valid_properties[k]:
            if isinstance(v, dict) and 'value' in v:
                v = v['value']
            updates[k] = v
    model.update(**updates) 
Example #5
Source File: element.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def model_changed(self, model):
        """
        Determines if the bokeh model was just changed on the frontend.
        Useful to suppress boomeranging events, e.g. when the frontend
        just sent an update to the x_range this should not trigger an
        update on the backend.
        """
        callbacks = [cb for cbs in self.traverse(lambda x: x.callbacks)
                     for cb in cbs]
        stream_metadata = [stream._metadata for cb in callbacks
                           for stream in cb.streams if stream._metadata]
        return any(md['id'] == model.ref['id'] for models in stream_metadata
                   for md in models.values()) 
Example #6
Source File: notebook.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_mimebundle(model, doc, comm, manager=None, location=None):
    """
    Displays bokeh output inside a notebook using the PyViz display
    and comms machinery.
    """
    if not isinstance(model, LayoutDOM):
        raise ValueError('Can only render bokeh LayoutDOM models')
    add_to_doc(model, doc, True)
    if manager is not None:
        doc.add_root(manager)
    if location is not None:
        loc = location._get_model(doc, model, model, comm)
        doc.add_root(loc)
    return render_model(model, comm) 
Example #7
Source File: geoplot.py    From Pandas-Bokeh with MIT License 5 votes vote down vote up
def _add_backgroundtile(
    p, tile_provider, tile_provider_url, tile_attribution, tile_alpha
):
    """Add a background tile to the plot. Either uses predefined Tiles from Bokeh 
    (parameter: tile_provider) or user passed a tile_provider_url of the form 
    '<url>/{Z}/{X}/{Y}*.png' or '<url>/{Z}/{Y}/{X}*.png'."""

    from bokeh.models import WMTSTileSource

    if not tile_provider_url is None:
        if (
            "/{Z}/{X}/{Y}" not in tile_provider_url
            and "/{Z}/{Y}/{X}" not in tile_provider_url
        ):
            raise ValueError(
                "<tile_provider_url> has to be of the form '<url>/{Z}/{X}/{Y}*.png' or <url>/{Z}/{Y}/{X}*.png'."
            )
        if not isinstance(tile_attribution, str):
            raise ValueError("<tile_attribution> has to be a string.")
        t = p.add_tile(
            WMTSTileSource(url=tile_provider_url, attribution=tile_attribution)
        )
        t.alpha = tile_alpha

    elif not tile_provider is None:
        if not isinstance(tile_provider, str):
            raise ValueError(
                f"<tile_provider> only accepts the values: {TILE_PROVIDERS}"
            )
        elif _get_background_tile(tile_provider) != False:
            t = p.add_tile(_get_background_tile(tile_provider))
        else:
            raise ValueError(
                f"<tile_provider> only accepts the values: {TILE_PROVIDERS}"
            )
        t.alpha = tile_alpha

    return p 
Example #8
Source File: geoplot.py    From Pandas-Bokeh with MIT License 5 votes vote down vote up
def get_tick_formatter(formatter_arg):

    if issubclass(formatter_arg.__class__, TickFormatter):
        return formatter_arg
    elif isinstance(formatter_arg, str):
        return NumeralTickFormatter(format=formatter_arg)
    else:
        raise ValueError(
            "<colorbar_tick_format> parameter only accepts a string or a objects of bokeh.models.formatters."
        ) 
Example #9
Source File: plots.py    From autogluon with Apache License 2.0 5 votes vote down vote up
def plot_summary_of_models(results, output_directory, save_file='SummaryOfModels.html', plot_title="Models produced during fit()"):
    """ Plot dynamic scatterplot summary of each model encountered during fit(), based on the returned Results object. 
    """
    num_trials = len(results['trial_info'])
    attr_color = None
    attr_size = None
    datadict = {'trial_id': sorted(results['trial_info'].keys())}
    datadict['performance'] = [results['trial_info'][trial_id][results['reward_attr']] for trial_id in datadict['trial_id']]
    datadict['hyperparameters'] = [_formatDict(results['trial_info'][trial_id]['config']) for trial_id in datadict['trial_id']]
    hidden_keys = []
    # Determine x-axis attribute:
    if 'latency' in results['metadata']:
        datadict['latency'] = [results['trial_info'][trial_id]['metadata']['latency'] for trial_id in datadict['trial_id']]
        attr_x = 'latency'
    else:
        attr_x = list(results['best_config'].keys())[0]
        datadict[attr_x] = [results['trial_info'][trial_id]['config'][attr_x] for trial_id in datadict['trial_id']]
        hidden_keys.append(attr_x)
    # Determine size attribute:
    if 'memory' in results['metadata']:
        datadict['memory'] = [results['trial_info'][trial_id]['metadata']['memory'] for trial_id in datadict['trial_id']]
        attr_size = 'memory'
    
    # Determine color attribute:
    if 'training_loss' in results:
        datadict['training_loss'] = [results['trial_info'][trial_id]['training_loss'] for trial_id in datadict['trial_id']]
        attr_color = 'training_loss'

    save_path = os.path.join(output_directory, save_file) if output_directory else None
    mousover_plot(datadict, attr_x=attr_x, attr_y='performance', attr_color=attr_color, 
        attr_size=attr_size, save_file=save_path, plot_title=plot_title, hidden_keys=hidden_keys)
    if save_path is not None:
        print("Plot summary of models saved to file: %s" % save_file) 
Example #10
Source File: axes.py    From chartify with Apache License 2.0 4 votes vote down vote up
def set_xaxis_tick_format(self, date_format):
        """Set x-axis tick label date format.

        Args:
            date_format (string): the date format
            for the x-axis tick labels.

        Examples:
            Daily precision
            >>> ch.set_xaxis_tick_format('%Y-%m-%d')
            Label format: YYYY-MM-DD

            Monthly precision
            >>> ch.set_xaxis_tick_format("%Y-%m")
            Label format: YYYY-MM

            Yearly precision
            >>> ch.set_xaxis_tick_format("%Y")
            Label format: YYYY

            Second Precision
            >>> ch.set_xaxis_tick_format("%Y-%m-%d %H:%M:%S")
            Label format: YYYY-MM-DD HH:MM:SS

            Day of week and day of month
            >>> ch.set_xaxis_tick_format("%a%d")
            Label format: Wed07

            Month and year
            >>> ch.set_xaxis_tick_format("%b%y")
            Label format: Jan17

        See bokeh.models.DatetimeTickFormatter documentation
        for more formatting options.

        Returns:
            Current chart object
        """
        self._chart.figure.xaxis[
            0].formatter = bokeh.models.DatetimeTickFormatter(
                milliseconds=[date_format],
                seconds=[date_format],
                minsec=[date_format],
                minutes=[date_format],
                hourmin=[date_format],
                hours=[date_format],
                days=[date_format],
                months=[date_format],
                years=[date_format])
        return self._chart 
Example #11
Source File: element.py    From holoviews with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _init_tools(self, element, callbacks=[]):
        """
        Processes the list of tools to be supplied to the plot.
        """
        tooltips, hover_opts = self._hover_opts(element)
        tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name))
                    if isinstance(ttp, Dimension) else ttp for ttp in tooltips]
        if not tooltips: tooltips = None

        callbacks = callbacks+self.callbacks
        cb_tools, tool_names = [], []
        hover = False
        for cb in callbacks:
            for handle in cb.models+cb.extra_models:
                if handle and handle in TOOLS_MAP:
                    tool_names.append(handle)
                    if handle == 'hover':
                        tool = tools.HoverTool(
                            tooltips=tooltips, tags=['hv_created'],
                            **hover_opts)
                        hover = tool
                    else:
                        tool = TOOLS_MAP[handle]()
                    cb_tools.append(tool)
                    self.handles[handle] = tool

        tool_list = [
            t for t in cb_tools + self.default_tools + self.tools
            if t not in tool_names]

        copied_tools = []
        for tool in tool_list:
            if isinstance(tool, tools.Tool):
                properties = tool.properties_with_values(include_defaults=False)
                tool = type(tool)(**properties)
            copied_tools.append(tool)

        hover_tools = [t for t in copied_tools if isinstance(t, tools.HoverTool)]
        if 'hover' in copied_tools:
            hover = tools.HoverTool(tooltips=tooltips, tags=['hv_created'], **hover_opts)
            copied_tools[copied_tools.index('hover')] = hover
        elif any(hover_tools):
            hover = hover_tools[0]
        if hover:
            self.handles['hover'] = hover
        return copied_tools 
Example #12
Source File: plot.py    From Pandas-Bokeh with MIT License 4 votes vote down vote up
def _initialize_rangetool(p, x_axis_type, source):
    """
    Initializes the range tool chart and slider.
    
    Parameters
    ----------
    p : Bokeh.plotting.figure
        Bokeh plot that the figure tool is going to supplement.
    x_axis_type : str
        Type of the xaxis (ex. datetime)
    source : Bokeh.models.sources
        Data

    Returns
    -------
        Bokeh.plotting.figure
    """

    max_y_range = 0
    # Initialize range tool plot
    p_rangetool = figure(
        title="Drag the box to change the range above.",
        plot_height=130,
        plot_width=p.plot_width,
        y_range=p.y_range,
        x_axis_type=x_axis_type,
        y_axis_type=None,
        tools="",
        toolbar_location=None,
    )

    # Need to explicitly set the initial range of the plot for the range tool.
    start_index = int(0.75 * len(source["__x__values"]))
    p.x_range = Range1d(source["__x__values"][start_index], source["__x__values"][-1])

    range_tool = RangeTool(x_range=p.x_range)
    range_tool.overlay.fill_color = "navy"
    range_tool.overlay.fill_alpha = 0.2

    p_rangetool.ygrid.grid_line_color = None
    p_rangetool.add_tools(range_tool)
    p_rangetool.toolbar.active_multi = range_tool

    return p_rangetool