bokeh.io.save

Here are the examples of the python api bokeh.io.save taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11 Examples 7

3 Source : utils.py
with MIT License
from allenbai01

    def save(self, title='Training Results'):
        if len(self.figures) > 0:
            if os.path.isfile(self.plot_path):
                os.remove(self.plot_path)
            output_file(self.plot_path, title=title)
            plot = column(*self.figures)
            save(plot)
            self.figures = []
        self.results.to_csv(self.path, index=False, index_label=False)

    def load(self, path=None):

3 Source : bokeh.py
with BSD 3-Clause "New" or "Revised" License
from holzschu

    def __init__(self, model, driver, output_file_url, has_no_console_errors):
        self._driver = driver
        self._model = model
        self._has_no_console_errors = has_no_console_errors

        save(self._model)

        self._driver.get(output_file_url)

        self.init_results()

    @property

3 Source : tests.py
with MIT License
from karlicoss

def save_plot(plot, name: str):
    base = Path('test-outputs')
    path = base / Path(name)
    path.parent.mkdir(exist_ok=True, parents=True)
    suf = path.suffix
    if suf == '.html':
        from bokeh.io import output_file, save
        output_file(str(path), title='hello', mode='inline', root_dir=None)
        save(plot)
    elif suf == '.png':
        # todo sigh.. seems that png export is way too slow
        from bokeh.io import export_png
        export_png(plot, filename=str(path))
    else:
        raise RuntimeError(name, suf)


def make_test(plot_factory):

3 Source : __main__.py
with MIT License
from karlicoss

def render_tab(*, tab: Tab, filename: Path):
    res = tab.plotter()

    from bokeh.io import save, output_file, curdoc
    output_file(filename, title=tab.name, mode='inline', root_dir=None)
    curdoc().theme = theme
    # TODO a bit weird that it needs two function calls to save..
    save(res)


def run(to: Path, tab_name: Optional[str]=None, debug: bool=False) -> Iterable[Exception]:

0 Source : quantify_profiles.py
with GNU Affero General Public License v3.0
from DennisSchmitz

def draw_stacked_bars(df, perc, sample="", parts=[], outfile="", colours=COLOURS):
    """
    Takes a file of quantified read annotations by a pipeline (e.g. PZN)
    and draws a stacked bar chart using Bokeh, creating an interactive
    HTML file.
    
    Input:
     - A Pandas dataframe with all the required data
     - The column name of Sample IDs (as string)
     - The column names for the numbers ("parts", as list)
     - The title of the figure (as string)
     - The name of the output file (as string)
     - The colours to be used for the bars (as list of strings - hexcodes)
    Output:
     - Interactive (Bokeh) stacked bar chart that visualises
      the composition of each sample in your experiment
    """
    # Set a comfortable length depending on the number of samples to show:
    if len(df[sample]) > 40:
        width = len(df[sample]) * 20
    # Have the graph grow horizontally to accomodate large numbers of samples
    elif len(df[sample]) > 25:
        width = len(df[sample]) * 33
    else:
        # With a minimum of 800 to display the legend
        width = 800

    nr_fig = figure(
        x_range=df[sample],
        plot_height=800,
        plot_width=width,
        title="Composition of samples (read-based)",
        toolbar_location=None,
        tools="hover, pan",
        tooltips="@%s $name: @$name" % sample,
    )

    nr_fig.vbar_stack(
        parts,
        x=sample,
        width=0.9,
        color=colours,
        source=df,
        legend=[value(x) for x in parts],
    )

    nr_fig.y_range.start = 0
    nr_fig.x_range.range_padding = 0.1
    nr_fig.xgrid.grid_line_color = None
    nr_fig.axis.minor_tick_line_color = None
    nr_fig.outline_line_color = None
    nr_fig.legend.location = "top_left"
    nr_fig.legend.orientation = "horizontal"
    nr_fig.xaxis.major_label_orientation = 1

    nr_panel = Panel(child=nr_fig, title="Absolute number of reads")

    perc_fig = figure(
        x_range=perc[sample],
        plot_height=800,
        plot_width=width,
        title="Composition of samples (percentages)",
        toolbar_location=None,
        tools="hover, pan",
        tooltips="@%s $name: @$name" % sample,
    )

    perc_fig.vbar_stack(
        parts,
        x=sample,
        width=0.9,
        color=colours,
        source=perc,
        legend=[value(x) for x in parts],
    )

    perc_fig.y_range.start = 0
    perc_fig.x_range.range_padding = 0.1
    perc_fig.xgrid.grid_line_color = None
    perc_fig.axis.minor_tick_line_color = None
    perc_fig.outline_line_color = None
    perc_fig.legend.location = "top_left"
    perc_fig.legend.orientation = "horizontal"
    perc_fig.xaxis.major_label_orientation = 1

    perc_panel = Panel(child=perc_fig, title="Percentage of reads")

    tabs = Tabs(tabs=[nr_panel, perc_panel])

    output_file(outfile)
    save(tabs)

    return None


def main():

0 Source : log.py
with Apache License 2.0
from Drajan

    def save(self, title=None):
        """save the json file.
        Parameters
        ----------
        title: string
            title of the HTML file
        """
        title = title or self.title
        if len(self.figures) > 0:
            if os.path.isfile(self.plot_path):
                os.remove(self.plot_path)
            if self.first_save:
                self.first_save = False
                logging.info('Plot file saved at: {}'.format(
                    os.path.abspath(self.plot_path)))

            output_file(self.plot_path, title=title)
            plot = column(
                Div(text='  <  h1 align="center">{} < /h1>'.format(title)), *self.figures)
            save(plot)
            self.clear()

        if self.data_format == 'json':
            self.results.to_json(self.data_path, orient='records', lines=True)
        else:
            self.results.to_csv(self.data_path, index=False, index_label=False)

    def load(self, path=None):

0 Source : visual_midi.py
with MIT License
from dubreuia

    def save(self, pm: PrettyMIDI, filepath: str):
        """
        Saves the pretty midi object as a plot file (html) in the provided file. If
        the live reload option is activated, the opened page will periodically
        refresh.

          :param pm: the PrettyMIDI instance to plot
          :param filepath: the file path to save the resulting plot to
          :return: the bokeh plot layout
        """
        plot = self.plot(pm)
        if self._live_reload:
            html = file_html(plot, CDN)
            html = html.replace("  <  /head>", """
               < script type="text/javascript">
                var liveReloadInterval = window.setInterval(function(){
                  location.reload();
                }, 2000);
               < /script>
               < /head>""")
            with open(filepath, 'w') as file:
                file.write(html)
        else:
            output_file(filepath)
            save(plot)
        return plot

    def show(self, pm: PrettyMIDI, filepath: str):

0 Source : mw_plot_bokeh.py
with MIT License
from henrysky

    def savefig(self, file='MWPlot.html'):
        output_file(file)
        save(self.bokeh_fig)
        
class MWSkyMapBokeh(MWSkyMapMaster):

0 Source : mw_plot_bokeh.py
with MIT License
from henrysky

    def savefig(self, file='MWSkyMap.html'):
        output_file(file)
        save(self.bokeh_fig)

0 Source : visualize.py
with Apache License 2.0
from IQTLabs

def visualize(
    k_mers,
    target_freqs,
    optimized_freqs,
    original_freqs=None,
    title="Freqgen Optimization Results",
    plot_height=400,
    plot_width=1200,
    show=True,
    filepath="freqgen.html",
    codons=False,
):
    """Creates a visualization of the results of a Freqgen optimization.

    Note:
        Currently, this function does not support the visualization of codon
        optimization *and* *k*-mer optimization simultaneously.

    Args:
        k_mers (list): A list of the *k*-mers to use as the labels for the *x*-axis.
        target_freqs (list): A list of the target frequencies in the same order as the `k_mers` argument.
        optimized_freqs (list): A list of the resultant frequencies in the same order as the `k_mers` argument.
        original_freqs (list, optional): A list of the original frequencies in the same order as the `k_mers` argument.
        title (str, optional): A title to use for the graph. Defaults to "Freqgen Optimization Results".
        plot_height (int, optional): The height for the graph. Defaults to 400.
        plot_width (int, optional): The width for the graph. Defaults to 1200.
        show (bool, optional): Whether to show the plot or simply return it. Defaults to True.
        filepath (str, optional): The output filepath. Defaults to "freqgen.html".
        codons (bool, optional): Whether codons are included in the input vectors. If they are, the *x*-axis legend will updated accordingly.

    Note:
        Codons must be denoted with a ``*`` in the ``k_mers`` argument. For example, the codon GAG should be passed as ``GAG*``

    Returns:
        bokeh.plotting.figure.Figure: A Bokeh figure containing the bar graph.
    """

    # validate that all the codons that should be there are there
    if codons and len([k_mer for k_mer in k_mers if k_mer.endswith("*")]) != 64:
        raise ValueError("You appear to be passing an incomplete list of codons.")

    codons_only = False
    if all([k_mer.endswith("*") for k_mer in k_mers]) and codons:
        k_mers = [k_mer[:-1] for k_mer in k_mers]
        codons_only = True

    output_file(filepath)

    categories = ["Original", "Target", "Optimized"]

    data = {"k_mers": k_mers, "Target": target_freqs, "Optimized": optimized_freqs}

    # adjust spacing depending on if there's three bars or two
    if not isinstance(original_freqs, type(None)):
        offset = 0.25
        data["Original"] = original_freqs
    else:
        offset = 0.15

    # identify the greatest y value for setting bounds
    y_max = max((max(target_freqs), max(optimized_freqs)))
    if not isinstance(original_freqs, type(None)):
        y_max = max((max(original_freqs), y_max))

    source = ColumnDataSource(data=data)

    p = figure(
        x_range=k_mers,
        plot_height=plot_height,
        plot_width=plot_width,
        title=title,
        y_range=(0, 1.2 * y_max),
    )

    if not isinstance(original_freqs, type(None)):
        p.vbar(
            x=dodge("k_mers", -0.25, range=p.x_range),
            top="Original",
            width=0.2,
            source=source,
            color=Set2_3[0],
            legend=value("Original"),
        )

    p.vbar(
        x=dodge(
            "k_mers",
            0.0 if not isinstance(original_freqs, type(None)) else -offset,
            range=p.x_range,
        ),
        top="Target",
        width=0.2,
        source=source,
        color=Set2_3[1],
        legend=value("Target"),
    )

    p.vbar(
        x=dodge("k_mers", offset, range=p.x_range),
        top="Optimized",
        width=0.2,
        source=source,
        color=Set2_3[2],
        legend=value("Optimized"),
    )

    p.x_range.range_padding = 0.05
    p.xgrid.grid_line_color = None
    p.legend.location = "top_right"
    p.legend.orientation = "horizontal"
    p.legend.click_policy = "hide"

    # decide the x-axis label
    if codons_only:
        p.xaxis.axis_label = "codon"
    elif codons:
        p.xaxis.axis_label = "k-mer (* denotes codon)"
    else:
        p.xaxis.axis_label = "k-mer"

    if len(k_mers) >= 32:
        p.xaxis.major_label_orientation = math.pi / 2

    p.yaxis.axis_label = "frequency"
    if show:
        _show(p)
    else:
        save(p, filename=filepath)
    return p

0 Source : timeseries_plots.py
with Apache License 2.0
from OpenMDAO

def _bokeh_timeseries_plots(varnames, time_units, var_units, phase_names, phases_node_path,
                            last_solution_case, last_simulation_case, plot_dir_path, num_cols=2,
                            bg_fill_color='#282828', grid_line_color='#666666', open_browser=False):
    from bokeh.io import output_notebook, output_file, save, show
    from bokeh.layouts import gridplot, column, row, grid, layout
    from bokeh.models import Legend, LegendItem
    from bokeh.plotting import figure
    import bokeh.palettes as bp

    if dymos_options['notebook_mode']:
        output_notebook()
    else:
        output_file(os.path.join(plot_dir_path, 'plots.html'))

    # Prune the edges from the color map
    cmap = bp.turbo(len(phase_names) + 2)[1:-1]
    figures = []
    colors = {}
    sol_plots = {}
    sim_plots = {}

    # Get the minimum and maximum times in any phase, so when we plot a variable that only exists
    # in a few phases, it is plotted against the entire time range.
    min_time = 1.0E21
    max_time = -1.0E21

    for iphase, phase_name in enumerate(phase_names):
        if phases_node_path:
            time_name = f'{phases_node_path}.{phase_name}.timeseries.time'
        else:
            time_name = f'{phase_name}.timeseries.time'
        min_time = min(min_time, np.min(last_solution_case.outputs[time_name]))
        max_time = max(max_time, np.max(last_solution_case.outputs[time_name]))
        colors[phase_name] = cmap[iphase]

    for ivar, var_name in enumerate(varnames):
        # Get the labels
        time_label = f'time ({time_units[var_name]})'
        var_label = f'{var_name} ({var_units[var_name]})'
        title = f'timeseries.{var_name}'

        # add labels, title, and legend
        padding = 0.05 * (max_time - min_time)
        fig = figure(title=title, background_fill_color=bg_fill_color,
                     x_range=(min_time - padding, max_time + padding), plot_width=180,
                     plot_height=180)
        fig.xaxis.axis_label = time_label
        fig.yaxis.axis_label = var_label
        fig.xgrid.grid_line_color = grid_line_color
        fig.ygrid.grid_line_color = grid_line_color

        # Plot each phase
        for iphase, phase_name in enumerate(phase_names):
            sol_color = cmap[iphase]
            sim_color = cmap[iphase]

            if phases_node_path:
                var_name_full = f'{phases_node_path}.{phase_name}.timeseries.{var_name}'
                time_name = f'{phases_node_path}.{phase_name}.timeseries.time'
            else:
                var_name_full = f'{phase_name}.timeseries.{var_name}'
                time_name = f'{phase_name}.timeseries.time'

            # Get values
            if var_name_full not in last_solution_case.outputs:
                continue

            var_val = last_solution_case.outputs[var_name_full]
            time_val = last_solution_case.outputs[time_name]

            for idxs, i in np.ndenumerate(np.zeros(var_val.shape[1:])):
                var_val_i = var_val[:, idxs].ravel()
                sol_plots[phase_name] = fig.circle(time_val.ravel(), var_val_i, size=5,
                                                   color=sol_color, name='sol:' + phase_name)

            # get simulation values, if plotting simulation
            if last_simulation_case:
                # if the phases_node_path is empty, need to pre-pend names with "sim_traj."
                #   as that is pre-pended in Trajectory.simulate code
                sim_prefix = '' if phases_node_path else 'sim_traj.'
                var_val_simulate = last_simulation_case.outputs[sim_prefix + var_name_full]
                time_val_simulate = last_simulation_case.outputs[sim_prefix + time_name]
                for idxs, i in np.ndenumerate(np.zeros(var_val_simulate.shape[1:])):
                    var_val_i = var_val_simulate[:, idxs].ravel()
                    sim_plots[phase_name] = fig.line(time_val_simulate.ravel(), var_val_i,
                                                     line_dash='solid', line_width=0.5, color=sim_color,
                                                     name='sim:' + phase_name)
        figures.append(fig)

    # Implement a single legend for all figures using the example here:
    # https://stackoverflow.com/a/56825812/754536

    # ## Use a dummy figure for the LEGEND
    dum_fig = figure(outline_line_alpha=0, toolbar_location=None,
                     background_fill_color=bg_fill_color, plot_width=250, max_width=250)

    # set the components of the figure invisible
    for fig_component in [dum_fig.grid, dum_fig.ygrid, dum_fig.xaxis, dum_fig.yaxis]:
        fig_component.visible = False

    # The glyphs referred by the legend need to be present in the figure that holds the legend,
    # so we must add them to the figure renderers.
    sol_legend_items = [(phase_name + ' solution', [dum_fig.circle([0], [0],
                                                                   size=5,
                                                                   color=colors[phase_name],
                                                                   tags=['sol:' + phase_name])]) for phase_name in phase_names]
    sim_legend_items = [(phase_name + ' simulation', [dum_fig.line([0], [0],
                                                                   line_dash='solid',
                                                                   line_width=0.5,
                                                                   color=colors[phase_name],
                                                                   tags=['sim:' + phase_name])]) for phase_name in phase_names]
    legend_items = [j for i in zip(sol_legend_items, sim_legend_items) for j in i]

    # # set the figure range outside of the range of all glyphs
    dum_fig.x_range.end = 1005
    dum_fig.x_range.start = 1000

    legend = Legend(click_policy='hide', location='top_left', border_line_alpha=0, items=legend_items,
                    background_fill_alpha=0.0, label_text_color='white', label_width=120, spacing=10)

    dum_fig.add_layout(legend, place='center')

    gd = gridplot(figures, ncols=num_cols, sizing_mode='scale_both')

    plots = gridplot([[gd, column(dum_fig, sizing_mode='stretch_height')]],
                     toolbar_location=None,
                     sizing_mode='scale_both')

    if dymos_options['notebook_mode'] or open_browser:
        show(plots)
    else:
        save(plots)


def timeseries_plots(solution_recorder_filename, simulation_record_file=None, plot_dir="plots"):