Python bokeh.models.ColorBar() Examples

The following are 9 code examples of bokeh.models.ColorBar(). 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 , or try the search function .
Example #1
Source File: vtk.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _construct_colorbars(self, color_mappers=None):
        if not color_mappers:
            color_mappers = self.color_mappers
        from bokeh.models import Plot, ColorBar, FixedTicker
        cbs = []
        for color_mapper in color_mappers:
            ticks = np.linspace(color_mapper.low, color_mapper.high, 5)
            cbs.append(ColorBar(
                color_mapper=color_mapper,
                title=color_mapper.name,
                ticker=FixedTicker(ticks=ticks),
                label_standoff=5, background_fill_alpha=0, orientation='horizontal', location=(0, 0)
            ))
        plot = Plot(toolbar_location=None, frame_height=0, sizing_mode='stretch_width',
                    outline_line_width=0)
        [plot.add_layout(cb, 'below') for cb in cbs]
        return plot 
Example #2
Source File: visualize_utils.py    From embedding with MIT License 5 votes vote down vote up
def visualize_between_sentences(sentences, vec_list, palette="Viridis256",
                                filename="/notebooks/embedding/between-sentences.png",
                                use_notebook=False):
    df_list, score_list = [], []
    for sent1_idx, sentence1 in enumerate(sentences):
        for sent2_idx, sentence2 in enumerate(sentences):
            vec1, vec2 = vec_list[sent1_idx], vec_list[sent2_idx]
            if np.any(vec1) and np.any(vec2):
                score = cosine_similarity(X=[vec1], Y=[vec2])
                df_list.append({'x': sentence1, 'y': sentence2, 'similarity': score[0][0]})
                score_list.append(score[0][0])
    df = pd.DataFrame(df_list)
    color_mapper = LinearColorMapper(palette=palette, low=np.max(score_list), high=np.min(score_list))
    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
    p = figure(x_range=sentences, y_range=list(reversed(sentences)),
                x_axis_location="above", plot_width=900, plot_height=900,
                toolbar_location='below', tools=TOOLS,
                tooltips=[('sentences', '@x @y'), ('similarity', '@similarity')])
    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_standoff = 0
    p.xaxis.major_label_orientation = 3.14 / 3
    p.rect(x="x", y="y", width=1, height=1,
            source=df,
            fill_color={'field': 'similarity', 'transform': color_mapper},
            line_color=None)
    color_bar = ColorBar(ticker=BasicTicker(desired_num_ticks=5),
                        color_mapper=color_mapper, major_label_text_font_size="7pt",
                        label_standoff=6, border_line_color=None, location=(0, 0))
    p.add_layout(color_bar, 'right')
    if use_notebook:
        output_notebook()
        show(p)
    else:
        export_png(p, filename)
        print("save @ " + filename) 
Example #3
Source File: visualize_utils.py    From embedding with MIT License 5 votes vote down vote up
def visualize_between_words(words, vecs, palette="Viridis256", filename="/notebooks/embedding/between-words.png",
                            use_notebook=False):
    df_list = []
    for word1_idx, word1 in enumerate(words):
        for word2_idx, word2 in enumerate(words):
            vec1 = vecs[word1_idx]
            vec2 = vecs[word2_idx]
            if np.any(vec1) and np.any(vec2):
                score = cosine_similarity(X=[vec1], Y=[vec2])
                df_list.append({'x': word1, 'y': word2, 'similarity': score[0][0]})
    df = pd.DataFrame(df_list)
    color_mapper = LinearColorMapper(palette=palette, low=1, high=0)
    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
    p = figure(x_range=list(words), y_range=list(reversed(list(words))),
               x_axis_location="above", plot_width=900, plot_height=900,
               toolbar_location='below', tools=TOOLS,
               tooltips=[('words', '@x @y'), ('similarity', '@similarity')])
    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_standoff = 0
    p.xaxis.major_label_orientation = 3.14 / 3
    p.rect(x="x", y="y", width=1, height=1,
           source=df,
           fill_color={'field': 'similarity', 'transform': color_mapper},
           line_color=None)
    color_bar = ColorBar(ticker=BasicTicker(desired_num_ticks=5),
                         color_mapper=color_mapper, major_label_text_font_size="7pt",
                         label_standoff=6, border_line_color=None, location=(0, 0))
    p.add_layout(color_bar, 'right')
    if use_notebook:
        output_notebook()
        show(p)
    else:
        export_png(p, filename)
        print("save @ " + filename) 
Example #4
Source File: testquadmeshplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_quadmesh_colorbar(self):
        n = 21
        xs = np.logspace(1, 3, n)
        ys = np.linspace(1, 10, n)
        qmesh = QuadMesh((xs, ys, np.random.rand(n-1, n-1))).options(colorbar=True)
        plot = bokeh_renderer.get_plot(qmesh)
        self.assertIsInstance(plot.handles['colorbar'], ColorBar)
        self.assertIs(plot.handles['colorbar'].color_mapper, plot.handles['color_mapper']) 
Example #5
Source File: testradialheatmap.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_radial_heatmap_colorbar(self):
        hm = HeatMap([(0, 0, 1), (0, 1, 2), (1, 0, 3)]).options(radial=True, colorbar=True)
        plot = bokeh_renderer.get_plot(hm)
        self.assertIsInstance(plot.handles.get('colorbar'), ColorBar) 
Example #6
Source File: NeoPredViz.py    From NeoPredPipe with GNU Lesser General Public License v3.0 5 votes vote down vote up
def HeatTable(self):
        ready = {}
        for item in self.sharedCount:
            ready.update({ (item.split(',')[0],item.split(',')[1]): self.sharedCount[item] })

        k = np.array([item for item in ready])
        v = np.array([ready[item] for item in ready])

        unq_keys, key_idx = np.unique(k, return_inverse=True)
        key_idx = key_idx.reshape(-1, 2)
        n = len(unq_keys)
        adj = np.zeros((n, n), dtype=v.dtype)
        adj[key_idx[:, 0], key_idx[:, 1]] = v
        adj += adj.T

        adj = adj.astype(float)
        for i in range(0,adj.shape[0]):
            for k in range(0,adj.shape[1]):
                if k<=i:
                    adj[i,k]=np.nan

        dfout = pd.DataFrame(data=np.log10(adj+0.01),index = unq_keys, columns = unq_keys)
        dfout.index.name = 'Sam1'
        dfout.columns.name = 'Sam2'
        df = pd.DataFrame(dfout.stack(), columns=['Neoantigens']).reset_index()

        source = ColumnDataSource(df)

        import bokeh.palettes as p
        colors = p.Plasma256
        mapper = LinearColorMapper(palette=colors, low=df.Neoantigens.min(), high=df.Neoantigens.max())

        p = figure(title = "log10( Shared Neoantigens )", plot_height=400, plot_width=400, x_range=list(dfout.index), y_range=list(reversed(dfout.columns)),
           toolbar_location=None, tools="", x_axis_location="below")
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = None
        p.axis.major_label_text_font_size = "5pt"
        p.axis.major_label_standoff = 0
        p.xaxis.major_label_orientation = np.pi / 3
        p.rect(x='Sam1',y='Sam2', source=source, width=1, height=1, fill_color={'field':'Neoantigens','transform':mapper}, line_color=None)

        color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                             ticker=BasicTicker(desired_num_ticks=int(len(colors)/10)))

        p.add_layout(color_bar, 'right')
        return(p) 
Example #7
Source File: configurator_footprint.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_contour(self, p, contour_data, x_range, y_range):
        """Plot contour data.

        Parameters
        ----------
        p: bokeh.plotting.figure
            figure to be drawn upon
        contour_data: Dict[str -> np.array]
            dict from labels to array with contour data
        x_range: List[float, float]
            min and max of x-axis
        y_range: List[float, float]
            min and max of y-axis

        Returns
        -------
        handles: dict[str -> tuple(ImageGlyph, tuple(float, float))]
            mapping from label to image glyph and min/max-tuple
        """
        unique = np.unique(np.concatenate([contour_data[label][2] for label in contour_data.keys()]))
        color_mapper = LinearColorMapper(palette="Viridis256", low=np.min(unique), high=np.max(unique))
        handles = {}
        default_label = 'combined' if 'combined' in contour_data.keys() else list(contour_data.keys())[0]
        for label, data in contour_data.items():
            unique = np.unique(contour_data[label][2])
            handles[label] = (p.image(image=contour_data[label], x=x_range[0], y=y_range[0],
                                      dw=x_range[1] - x_range[0], dh=y_range[1] - y_range[0],
                                      color_mapper=color_mapper),
                              (np.min(unique), np.max(unique)))

            if not label == default_label and len(contour_data) > 1:
                handles[label][0].visible = False
        color_bar = ColorBar(color_mapper=color_mapper,
                             ticker=BasicTicker(desired_num_ticks=15),
                             label_standoff=12,
                             border_line_color=None, location=(0, 0))
        color_bar.major_label_text_font_size = '12pt'
        p.add_layout(color_bar, 'right')
        return handles, color_mapper 
Example #8
Source File: plot.py    From arlpy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def image(img, x=None, y=None, colormap='Plasma256', clim=None, clabel=None, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, xtype='auto', ytype='auto', width=None, height=None, hold=False, interactive=None):
    """Plot a heatmap of 2D scalar data.

    :param img: 2D image data
    :param x: x-axis range for image data (min, max)
    :param y: y-axis range for image data (min, max)
    :param colormap: named color palette or Bokeh ColorMapper (see `Bokeh palettes <https://bokeh.pydata.org/en/latest/docs/reference/palettes.html>`_)
    :param clim: color axis limits (min, max)
    :param clabel: color axis label
    :param title: figure title
    :param xlabel: x-axis label
    :param ylabel: y-axis label
    :param xlim: x-axis limits (min, max)
    :param ylim: y-axis limits (min, max)
    :param xtype: x-axis type ('auto', 'linear', 'log', etc)
    :param ytype: y-axis type ('auto', 'linear', 'log', etc)
    :param width: figure width in pixels
    :param height: figure height in pixels
    :param interactive: enable interactive tools (pan, zoom, etc) for plot
    :param hold: if set to True, output is not plotted immediately, but combined with the next plot

    >>> import arlpy.plot
    >>> import numpy as np
    >>> arlpy.plot.image(np.random.normal(size=(100,100)), colormap='Inferno256')
    """
    global _figure
    if x is None:
        x = (0, img.shape[1]-1)
    if y is None:
        y = (0, img.shape[0]-1)
    if xlim is None:
        xlim = x
    if ylim is None:
        ylim = y
    if _figure is None:
        _figure = _new_figure(title, width, height, xlabel, ylabel, xlim, ylim, xtype, ytype, interactive)
    if clim is None:
        clim = [_np.amin(img), _np.amax(img)]
    if not isinstance(colormap, _bmodels.ColorMapper):
        colormap = _bmodels.LinearColorMapper(palette=colormap, low=clim[0], high=clim[1])
    _figure.image([img], x=x[0], y=y[0], dw=x[-1]-x[0], dh=y[-1]-y[0], color_mapper=colormap)
    cbar = _bmodels.ColorBar(color_mapper=colormap, location=(0,0), title=clabel)
    _figure.add_layout(cbar, 'right')
    if not hold and not _hold:
        _show(_figure)
        _figure = None 
Example #9
Source File: test_vtk.py    From panel with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_vtk_pane_more_complex(document, comm, tmp_path):
    renWin = pyvista_render_window()
    pane = VTK(renWin)

    # Create pane
    model = pane.get_root(document, comm=comm)
    assert isinstance(model, VTKSynchronizedPlot)
    assert pane._models[model.ref['id']][0] is model

    colorbars_infered = pane.construct_colorbars().object

    assert len(colorbars_infered.below) == 2 # infer only actor color bars
    assert all(isinstance(cb, ColorBar) for cb in colorbars_infered.below)

    colorbars_in_scene = pane.construct_colorbars(infer=False).object()
    assert len(colorbars_in_scene.below) == 3
    assert all(isinstance(cb, ColorBar) for cb in colorbars_in_scene.below)
    # add axes
    pane.axes = dict(
        origin = [-5, 5, -2],
        xticker = {'ticks': np.linspace(-5,5,5)},
        yticker = {'ticks': np.linspace(-5,5,5)},
        zticker = {'ticks': np.linspace(-2,2,5),
                   'labels': [''] + [str(int(item)) for item in np.linspace(-2,2,5)[1:]]},
        fontsize = 12,
        digits = 1,
        grid_opacity = 0.5,
        show_grid=True
    )
    assert isinstance(model.axes, VTKAxes)

    # test export to file
    tmpfile = os.path.join(*tmp_path.joinpath('scene').parts)
    exported_file = pane.export_scene(filename=tmpfile)
    assert exported_file.endswith('.synch')

    # test import from file
    # (TODO test if the scene imported is identical to the one exported)
    imported_scene = VTK.import_scene(filename=exported_file)
    assert isinstance(imported_scene, VTKRenderWindowSynchronized)

    # Cleanup
    pane._cleanup(model)
    assert pane._contexts == {}
    assert pane._models == {}