Python bokeh.plotting.Figure() Examples

The following are 19 code examples of bokeh.plotting.Figure(). 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.plotting , or try the search function .
Example #1
Source File: plot.py    From umap with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show(plot_to_show):
    """Display a plot, either interactive or static.

    Parameters
    ----------
    plot_to_show: Output of a plotting command (matplotlib axis or bokeh figure)
        The plot to show

    Returns
    -------
    None
    """
    if isinstance(plot_to_show, plt.Axes):
        show_static()
    elif isinstance(plot_to_show, bpl.Figure):
        show_interactive(plot_to_show)
    else:
        raise ValueError(
            "The type of ``plot_to_show`` was not valid, or not understood."
        ) 
Example #2
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_holoviews_link_after_adding_item(document, comm):
    from bokeh.models.tools import RangeTool
    from holoviews.plotting.links import RangeToolLink

    c1 = hv.Curve([])
    c2 = hv.Curve([])

    RangeToolLink(c1, c2)

    layout = Row(Pane(c1, backend='bokeh'))
    row = layout.get_root(document, comm=comm)

    assert len(row.children) == 1
    p1, = row.children

    assert isinstance(p1, Figure)
    range_tool = row.select_one({'type': RangeTool})
    assert range_tool is None

    layout.append(Pane(c2, backend='bokeh'))
    _, p2 = row.children
    assert isinstance(p2, Figure)
    range_tool = row.select_one({'type': RangeTool})
    assert isinstance(range_tool, RangeTool)
    assert range_tool.x_range == p2.x_range 
Example #3
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_holoviews_link_across_panes(document, comm):
    from bokeh.models.tools import RangeTool
    from holoviews.plotting.links import RangeToolLink

    c1 = hv.Curve([])
    c2 = hv.Curve([])

    RangeToolLink(c1, c2)

    layout = Row(Pane(c1, backend='bokeh'), Pane(c2, backend='bokeh'))
    row = layout.get_root(document, comm=comm)

    assert len(row.children) == 2
    p1, p2 = row.children

    assert isinstance(p1, Figure)
    assert isinstance(p2, Figure)

    range_tool = row.select_one({'type': RangeTool})
    assert isinstance(range_tool, RangeTool)
    assert range_tool.x_range == p2.x_range 
Example #4
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_holoviews_pane_switch_backend(document, comm):
    curve = hv.Curve([1, 2, 3])
    pane = Pane(curve)

    # Create pane
    row = pane.get_root(document, comm=comm)
    assert isinstance(row, BkRow)
    assert len(row.children) == 1
    model = row.children[0]
    assert pane._models[row.ref['id']][0] is model
    assert model.text.startswith('<img src=')

    # Replace Pane.object
    pane.backend = 'bokeh'
    model = row.children[0]
    assert isinstance(model, Figure)

    # Cleanup
    pane._cleanup(row)
    assert pane._models == {} 
Example #5
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_pane_initialize_empty(document, comm):
    pane = HoloViews()

    # Create pane
    row = pane.get_root(document, comm=comm)

    assert isinstance(row, BkRow)
    assert len(row.children) == 1
    model = row.children[0]
    assert isinstance(model, BkSpacer)

    pane.object = hv.Curve([1, 2, 3])
    model = row.children[0]
    assert isinstance(model, Figure) 
Example #6
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_link_within_pane(document, comm):
    from bokeh.models.tools import RangeTool
    from holoviews.plotting.links import RangeToolLink

    c1 = hv.Curve([])
    c2 = hv.Curve([])

    RangeToolLink(c1, c2)

    pane = Pane(Pane(hv.Layout([c1, c2]), backend='bokeh'))
    column = pane.get_root(document, comm=comm)

    assert len(column.children) == 1
    subcolumn = column.children[0]
    assert isinstance(subcolumn, BkColumn)
    assert len(subcolumn.children) == 2
    toolbar, subsubcolumn = subcolumn.children
    assert isinstance(subsubcolumn, GridBox)
    assert len(subsubcolumn.children) == 2
    (p1, _, _), (p2, _, _) = subsubcolumn.children

    assert isinstance(p1, Figure)
    assert isinstance(p2, Figure)

    range_tool = subsubcolumn.select_one({'type': RangeTool})
    assert isinstance(range_tool, RangeTool)
    assert range_tool.x_range == p2.x_range 
Example #7
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_not_linked_axes(document, comm):
    c1 = hv.Curve([1, 2, 3])
    c2 = hv.Curve([1, 2, 3])

    layout = Row(
        HoloViews(c1, backend='bokeh'),
        HoloViews(c2, backend='bokeh', linked_axes=False)
    )

    row_model = layout.get_root(document, comm=comm)

    p1, p2 = row_model.select({'type': Figure})

    assert p1.x_range is not p2.x_range
    assert p1.y_range is not p2.y_range 
Example #8
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_shared_axes_opt_not_linked_axes(document, comm):
    c1 = hv.Curve([1, 2, 3])
    c2 = hv.Curve([1, 2, 3]).opts(shared_axes=False, backend='bokeh')

    layout = Row(HoloViews(c1, backend='bokeh'), HoloViews(c2, backend='bokeh'))

    row_model = layout.get_root(document, comm=comm)

    p1, p2 = row_model.select({'type': Figure})

    assert p1.x_range is not p2.x_range
    assert p1.y_range is not p2.y_range 
Example #9
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_linked_x_axis(document, comm):
    c1 = hv.Curve([1, 2, 3])
    c2 = hv.Curve([1, 2, 3], vdims='y2')

    layout = Row(HoloViews(c1, backend='bokeh'), HoloViews(c2, backend='bokeh'))

    row_model = layout.get_root(document, comm=comm)

    p1, p2 = row_model.select({'type': Figure})

    assert p1.x_range is p2.x_range
    assert p1.y_range is not p2.y_range 
Example #10
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_linked_axes(document, comm):
    c1 = hv.Curve([1, 2, 3])
    c2 = hv.Curve([1, 2, 3])

    layout = Row(HoloViews(c1, backend='bokeh'), HoloViews(c2, backend='bokeh'))

    row_model = layout.get_root(document, comm=comm)

    p1, p2 = row_model.select({'type': Figure})

    assert p1.x_range is p2.x_range
    assert p1.y_range is p2.y_range 
Example #11
Source File: plot_history.py    From tick with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_bokeh_history(solvers, x, y, x_arrays, y_arrays, mins, legends,
                       log_scale, show):
    import bokeh.plotting as bk

    min_x, max_x, min_y, max_y = mins
    if log_scale:
        # Bokeh has a weird behaviour when using logscale with 0 entries...
        # We use the difference between smallest value of second small
        # to set the range of y
        all_ys = np.hstack(y_arrays)
        y_range_min = np.min(all_ys[all_ys != 0])
        if y_range_min < 0:
            raise ValueError("Cannot plot negative values on a log scale")

        fig = bk.Figure(plot_height=300, y_axis_type="log",
                        y_range=[y_range_min, max_y])
    else:
        fig = bk.Figure(plot_height=300, x_range=[min_x, max_x],
                        y_range=[min_y, max_y])

    for i, (solver, x_array, y_array, legend) in enumerate(
            zip(solvers, x_arrays, y_arrays, legends)):
        color = get_plot_color(i)
        fig.line(x_array, y_array, line_width=3, legend=legend, color=color)
    fig.xaxis.axis_label = x
    fig.yaxis.axis_label = y
    fig.xaxis.axis_label_text_font_size = "12pt"
    fig.yaxis.axis_label_text_font_size = "12pt"
    if show:
        bk.show(fig)
        return None
    else:
        return fig 
Example #12
Source File: test_holoviews.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_holoviews_pane_bokeh_renderer(document, comm):
    curve = hv.Curve([1, 2, 3])
    pane = Pane(curve)

    # Create pane
    row = pane.get_root(document, comm=comm)
    assert isinstance(row, BkRow)
    assert len(row.children) == 1
    model = row.children[0]
    assert isinstance(model, Figure)
    assert pane._models[row.ref['id']][0] is model
    renderers = [r for r in model.renderers if isinstance(r, GlyphRenderer)]
    assert len(renderers) == 1
    assert isinstance(renderers[0].glyph, Line)

    # Replace Pane.object
    scatter = hv.Scatter([1, 2, 3])
    pane.object = scatter
    model = row.children[0]
    assert isinstance(model, Figure)
    renderers = [r for r in model.renderers if isinstance(r, GlyphRenderer)]
    assert len(renderers) == 1
    assert isinstance(renderers[0].glyph, Scatter)
    assert pane._models[row.ref['id']][0] is model

    # Cleanup
    pane._cleanup(row)
    assert pane._models == {} 
Example #13
Source File: testlayoutplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_layout_plot_with_adjoints(self):
        layout = (Curve([]) + Curve([]).hist()).cols(1)
        plot = bokeh_renderer.get_plot(layout)
        toolbar, grid = plot.state.children
        self.assertIsInstance(toolbar, ToolbarBox)
        self.assertIsInstance(grid, GridBox)
        for (fig, _, _) in grid.children:
            self.assertIsInstance(fig, Figure)
        self.assertTrue([len([r for r in f.renderers if isinstance(r, GlyphRenderer)])
                         for (f, _, _) in grid.children], [1, 1, 1]) 
Example #14
Source File: testlayoutplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_layout_gridspaces(self):
        layout = (GridSpace({(i, j): Curve(range(i+j)) for i in range(1, 3)
                             for j in range(2,4)}) +
                  GridSpace({(i, j): Curve(range(i+j)) for i in range(1, 3)
                             for j in range(2,4)}) +
                  Curve(range(10))).cols(2)
        layout_plot = bokeh_renderer.get_plot(layout)
        plot = layout_plot.state

        # Unpack until getting down to two rows
        self.assertIsInstance(plot, Column)
        self.assertEqual(len(plot.children), 2)
        toolbar, grid = plot.children
        self.assertIsInstance(toolbar, ToolbarBox)
        self.assertIsInstance(grid, GridBox)
        self.assertEqual(len(grid.children), 3)
        (col1, _, _), (col2, _, _), (fig, _, _) = grid.children
        self.assertIsInstance(col1, Column)
        self.assertIsInstance(col2, Column)
        grid1 = col1.children[0]
        grid2 = col2.children[0]

        # Check the row of GridSpaces
        self.assertEqual(len(grid1.children), 3)
        _, (col1, _, _), _ = grid1.children
        self.assertIsInstance(col1, Column)
        inner_grid1 = col1.children[0]

        self.assertEqual(len(grid2.children), 3)
        _, (col2, _, _), _ = grid2.children
        self.assertIsInstance(col2, Column)
        inner_grid2 = col2.children[0]
        for grid in [inner_grid1, inner_grid2]:
            self.assertEqual(len(grid.children), 4)
            (gfig1, _, _), (gfig2, _, _), (gfig3, _, _), (gfig4, _, _) = grid.children
            self.assertIsInstance(gfig1, Figure)
            self.assertIsInstance(gfig2, Figure)
            self.assertIsInstance(gfig3, Figure)
            self.assertIsInstance(gfig4, Figure) 
Example #15
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 #16
Source File: gui.py    From pysdr with GNU General Public License v3.0 5 votes vote down vote up
def utilization_bar(max_y):
    plot = Figure(plot_width = 150, # this is more for the ratio, because we have auto-width scaling
                  plot_height = 150,
                  tools = [], # no tools needed for this one
                  title = 'Utilization')
    plot.toolbar.logo = None  # hides logo
    plot.x_range = Range1d(0, 1) 
    plot.y_range = Range1d(0, max_y)  # sometimes you want it to be way less than 1, to see it move
    plot.xaxis.visible = False # hide x axis
    # Add input buffer
    manager = Manager()
    plot._input_buffer = manager.dict()
    return plot 
Example #17
Source File: gui.py    From pysdr with GNU General Public License v3.0 4 votes vote down vote up
def base_plot(x_label, y_label, title, **kwargs):
    
    # This allows disabling of horizontal zooming, which gets annoying in most dsp plots
    # e.g. usage: fft_plot = pysdr.base_plot('Freq', 'PSD', 'Frequency', disable_horizontal_zooming=True)
    if 'disable_horizontal_zooming' in kwargs and kwargs['disable_horizontal_zooming']: # if it's specified and is set True
        tools = [WheelZoomTool(dimensions='height')]
    else:
        tools = [WheelZoomTool()]

    # Similar to above, except disable all zooming, perfect for waterfall plots
    if 'disable_all_zooming' in kwargs and kwargs['disable_all_zooming']: # if it's specified and is set True
        tools = [] # removes the WheelZoomTool we just added above
    
    if 'plot_height' in kwargs:
        plot_height = kwargs['plot_height']
    else:
        plot_height = 200
    
    # Create the Bokeh figure
    plot = Figure(plot_width = 300, # this is more for the ratio, because we have auto-width scaling
                  plot_height = plot_height,
                  y_axis_label = y_label,
                  x_axis_label = x_label,
                  tools = tools + [BoxZoomTool(), ResetTool(), SaveTool()], # all the other tools we want- reference http://bokeh.pydata.org/en/0.10.0/docs/reference/models/tools.html
                  title = title)  # use min_border=30 to add padding between plots, if we ever want it
    
    # sets wheel zoom active by default (tools[0] is the wheelzoom), unless zooming was disabled
    if 'disable_all_zooming' not in kwargs:
        plot.toolbar.active_scroll = plot.toolbar.tools[0] 
    
    # hides stupid bokeh logo
    plot.toolbar.logo = None 
    
    # add more intuitive functions to set x and y ranges
    def _set_x_range(min_x, max_x): # without the underscore it wont work, bokeh/core/has_props.py overloads __setattr__ to intercept attribute setting that is not private
        plot.x_range = Range1d(min_x, max_x)
    def _set_y_range(min_y, max_y):
        plot.y_range = Range1d(min_y, max_y)
    plot._set_x_range = _set_x_range # add functions to object
    plot._set_y_range = _set_y_range
    
    # Add input buffer
    manager = Manager()
    plot._input_buffer = manager.dict()

    # return the bokeh figure object
    return plot  



# The idea behind this utilization bar is to have an "included by default" widget to show
#    how well the process_samples is keeping up with the incoming samples, in a realtime manner 
Example #18
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 4 votes vote down vote up
def _create_plot() -> (Figure, ColumnDataSource):
    """Utility function for creating and styling the bar plot."""
    global source, aspects, stats
    pos_counts, neg_counts = (
        [stats.loc[(asp, pol, False), "Quantity"] for asp in aspects] for pol in POLARITIES
    )
    np.seterr(divide="ignore")
    source = ColumnDataSource(
        data={
            "aspects": aspects,
            "POS": pos_counts,
            "NEG": neg_counts,
            "log-POS": np.log2(pos_counts),
            "log-NEG": np.log2(neg_counts),
        }
    )
    np.seterr(divide="warn")
    p = figure(
        plot_height=145,
        sizing_mode="scale_width",
        x_range=aspects,
        toolbar_location="right",
        tools="save, tap",
    )
    rs = [
        p.vbar(
            x=dodge("aspects", -0.207, range=p.x_range),
            top="log-POS",
            width=0.4,
            source=source,
            color="limegreen",
            legend=value("POS"),
            name="POS",
        ),
        p.vbar(
            x=dodge("aspects", 0.207, range=p.x_range),
            top="log-NEG",
            width=0.4,
            source=source,
            color="orangered",
            legend=value("NEG"),
            name="NEG",
        ),
    ]
    for r in rs:
        p.add_tools(
            HoverTool(tooltips=[("Aspect", "@aspects"), (r.name, "@" + r.name)], renderers=[r])
        )
    p.add_layout(
        Title(text=" " * 7 + "Sentiment Count (log scale)", align="left", text_font_size="23px"),
        "left",
    )
    p.yaxis.ticker = []
    p.y_range.start = 0
    p.xgrid.grid_line_color = None
    p.xaxis.major_label_text_font_size = "20pt"
    p.legend.label_text_font_size = "20pt"
    return p, source 
Example #19
Source File: ui.py    From nlp-architect with Apache License 2.0 4 votes vote down vote up
def _create_plot() -> (Figure, ColumnDataSource):
    """Utility function for creating and styling the bar plot."""
    global source, aspects, stats
    pos_counts, neg_counts = (
        [stats.loc[(asp, pol, False), "Quantity"] for asp in aspects] for pol in POLARITIES
    )
    np.seterr(divide="ignore")
    source = ColumnDataSource(
        data={
            "aspects": aspects,
            "POS": pos_counts,
            "NEG": neg_counts,
            "log-POS": np.log2(pos_counts),
            "log-NEG": np.log2(neg_counts),
        }
    )
    np.seterr(divide="warn")
    p = figure(
        plot_height=145,
        sizing_mode="scale_width",
        x_range=aspects,
        toolbar_location="right",
        tools="save, tap",
    )
    rs = [
        p.vbar(
            x=dodge("aspects", -0.207, range=p.x_range),
            top="log-POS",
            width=0.4,
            source=source,
            color="limegreen",
            legend=value("POS"),
            name="POS",
        ),
        p.vbar(
            x=dodge("aspects", 0.207, range=p.x_range),
            top="log-NEG",
            width=0.4,
            source=source,
            color="orangered",
            legend=value("NEG"),
            name="NEG",
        ),
    ]
    for r in rs:
        p.add_tools(
            HoverTool(tooltips=[("Aspect", "@aspects"), (r.name, "@" + r.name)], renderers=[r])
        )
    p.add_layout(
        Title(text=" " * 7 + "Sentiment Count (log scale)", align="left", text_font_size="23px"),
        "left",
    )
    p.yaxis.ticker = []
    p.y_range.start = 0
    p.xgrid.grid_line_color = None
    p.xaxis.major_label_text_font_size = "20pt"
    p.legend.label_text_font_size = "20pt"
    return p, source