当前位置: 首页>>代码示例>>Python>>正文


Python bokeh.models方法代码示例

本文整理汇总了Python中bokeh.models方法的典型用法代码示例。如果您正苦于以下问题:Python bokeh.models方法的具体用法?Python bokeh.models怎么用?Python bokeh.models使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bokeh的用法示例。


在下文中一共展示了bokeh.models方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_xaxis_tick_format

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:spotify,项目名称:chartify,代码行数:35,代码来源:axes.py

示例2: set_yaxis_tick_format

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:spotify,项目名称:chartify,代码行数:34,代码来源:axes.py

示例3: compute_plot_size

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:holoviz,项目名称:holoviews,代码行数:41,代码来源:util.py

示例4: recursive_model_update

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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) 
开发者ID:holoviz,项目名称:holoviews,代码行数:29,代码来源:util.py

示例5: model_changed

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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()) 
开发者ID:holoviz,项目名称:holoviews,代码行数:15,代码来源:element.py

示例6: render_mimebundle

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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) 
开发者ID:holoviz,项目名称:panel,代码行数:16,代码来源:notebook.py

示例7: _add_backgroundtile

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:PatrikHlobil,项目名称:Pandas-Bokeh,代码行数:40,代码来源:geoplot.py

示例8: get_tick_formatter

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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."
        ) 
开发者ID:PatrikHlobil,项目名称:Pandas-Bokeh,代码行数:12,代码来源:geoplot.py

示例9: plot_summary_of_models

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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) 
开发者ID:awslabs,项目名称:autogluon,代码行数:35,代码来源:plots.py

示例10: _init_tools

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:holoviz,项目名称:holoviews,代码行数:48,代码来源:element.py

示例11: _initialize_rangetool

# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import models [as 别名]
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 
开发者ID:PatrikHlobil,项目名称:Pandas-Bokeh,代码行数:46,代码来源:plot.py


注:本文中的bokeh.models方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。