bokeh.models.annotations.Title

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

3 Examples 7

0 View Source File : cli.py
License : MIT License
Project Creator : IQTLabs

def visualize(
    fasta,
    width,
    palette,
    color,
    hide,
    bar,
    title,
    separate,
    cols,
    link_x,
    link_y,
    output,
    offline,
    method,
    dimensions,
    skip,
    mode,
    legend_loc,
    output_backend,
    downsample,
):
    # check filetype
    if fasta is None:
        raise ValueError("Must provide FASTA file.")

    # handle selecting the palette
    palette = small_palettes[palette]

    # handle setting the dimensions automatically if not specified
    if not dimensions:
        dimensions = (750, 500)

    if (
        len([record for _f in fasta for record in Fasta(_f, read_long_names=True)])
        > len(palette)
        and mode != "file"
    ):
        if len(fasta) > 1 and mode == "auto":
            if not skip:
                print(
                    "Visualizing each file in separate color. To override, provide mode selection."
                )
            mode = "file"
        else:
            print("Visualizing each sequence in black.")
            color = False
    elif mode == "auto":
        mode = "seq"

    # get all the sequences
    seqs = []
    color_counter = 0
    warned = False
    for i, _f in enumerate(fasta):
        for j, seq in enumerate(
            Fasta(_f, sequence_always_upper=True, read_long_names=True)
        ):
            seqs.append(
                Box(
                    color=palette[color_counter + 1 if color_counter > 2 else 3][
                        color_counter
                    ]
                    if color
                    else "black",
                    name=_f if mode == "file" else seq.name,
                    raw_seq=str(seq),
                )
            )

            # check the length of the seq
            if len(seq) > 10000 and not skip and not warned and downsample == 1:
                click.confirm(
                    "You are plotting a long sequence ({} bp). This may be very slow, although downsampling might help. "
                    "Do you want to continue?".format(len(seq)),
                    abort=True,
                )
                warned = True

            if mode == "seq":
                color_counter += 1
        if mode == "file":
            color_counter += 1

    # warn if plotting a large number of seqs
    if len(seqs) > 500 and not skip:
        click.confirm(
            "You are plotting a large number of sequences ({}). This may be very slow, although downsampling might help. "
            "Do you want to continue?".format(len(seqs)),
            abort=True,
        )

    # warn if using a bad method
    if (
        max([len(seq.raw_seq) for seq in seqs]) > 25
        and method in ["qi", "randic"]
        and not skip
    ):
        click.confirm(
            "This method is not well suited to a sequence of this length. "
            "Do you want to continue?",
            abort=True,
        )

    axis_labels = {
        "squiggle": {"x": "position (BP)", "y": None},
        "gates": {"x": "C-G axis", "y": "A-T axis"},
        "yau": {"x": None, "y": None},
        "yau-bp": {"x": "position (BP)", "y": None},
        "randic": {"x": "position (BP)", "y": "nucleotide"},
        "qi": {"x": "position (BP)", "y": "dinucleotide"},
    }

    # the number of figures to draw is either the number of sequences or files (or 1)
    if separate:
        if mode == "seq":
            fig_count = len(seqs)
        elif mode == "file":
            fig_count = len(fasta)
    else:
        fig_count = 1

    fig = []
    for i in range(fig_count):

        # link the axes, if requested
        if i > 0 and link_x:
            x_range = fig[i - 1].x_range
        else:
            x_range = None
        if i > 0 and link_y:
            y_range = fig[i - 1].y_range
        else:
            y_range = None

        # the y axes for randic and qi are bases
        if method == "randic":
            y_range = ["A", "T", "G", "C"]
        elif method == "qi":
            y_range = [
                "AA",
                "AC",
                "AG",
                "AT",
                "CA",
                "CC",
                "CG",
                "CT",
                "GA",
                "GC",
                "GG",
                "GT",
                "TA",
                "TC",
                "TG",
                "TT",
            ]

        fig.append(
            figure(
                x_axis_label=axis_labels[method]["x"],
                y_axis_label=axis_labels[method]["y"],
                title=title,
                x_range=x_range,
                y_range=y_range,
                plot_width=dimensions[0],
                plot_height=dimensions[1],
                output_backend=output_backend,
            )
        )

    # show a progress bar if processing multiple files
    if len(seqs) > 1 and bar:
        _seqs = tqdm(seqs, unit=" seqs", leave=False)
    else:
        _seqs = seqs

    for i, seq in enumerate(_seqs):
        # perform the actual transformation
        transformed = transform(seq.raw_seq, method=method)
        if downsample > 1:
            transformed = (transformed[0][::downsample], transformed[1][::downsample])

        # figure (no pun intended) which figure to plot the data on
        if separate:
            if mode == "seq":
                _fig = fig[i]
            elif mode == "file":
                _fig = fig[fasta.index(seq.name)]

            # add a title to the plot
            _fig.title = annotations.Title()
            if mode == "seq":
                _fig.title.text = seq.name
            elif mode == "file":
                _fig.title.text = click.format_filename(seq.name, shorten=True)
        else:
            _fig = fig[0]
            _fig.title = annotations.Title()

            # if only plotting on one figure, set up the title
            if title:
                _fig.title.text = title
            elif len(seqs) > 1 and not title and len(fasta) == 1:
                _fig.title.text = click.format_filename(fasta[0], shorten=True)
            elif len(seqs) == 1:
                # if just plotting one sequence, title it with the name of the sequence
                _fig.title.text = seq.name

        # randic and qi method's have categorical y axes
        if method == "randic":
            y = list(seq.raw_seq)
        elif method == "qi":
            y = [seq.raw_seq[i : i + 2] for i in range(len(seq.raw_seq))]
            y = [str(i) for i in y if len(i) == 2]
        else:
            y = transformed[1]

        # figure out whether to add a legend
        if (separate or not color or mode == "file" or len(seqs) == 1) and not hide:
            legend = None
        else:
            legend = click.format_filename(seq.name, shorten=True)

        # optimization for comparing large FASTA files without hiding
        try:
            if mode == "file" and seqs[i + 1].color != seq.color and not separate:
                legend = click.format_filename(seq.name, shorten=True)
        except IndexError:
            if mode == "file" and not separate:
                legend = click.format_filename(seq.name, shorten=True)

        # do the actual plotting

        # set up the legend
        if legend is not None:
            _fig.line(
                x=transformed[0],
                y=y,
                line_width=width,
                legend_label=legend,
                color=seq.color,
            )
            _fig.legend.location = legend_loc
            if hide:
                _fig.legend.click_policy = "hide"
        else:
            _fig.line(x=transformed[0], y=y, line_width=width, color=seq.color)

    # clean up the tqdm bar
    try:
        _seqs.close()
    except AttributeError:
        pass

    # lay out the figure
    if separate:
        plot = gridplot(
            fig,
            ncols=math.ceil(len(fig) ** 0.5) if cols == 0 else cols,
            toolbar_options=dict(logo=None),
        )  # note that 0 denotes the automatic default
    else:
        plot = fig[0]

    if output is not None and output.endswith(".html"):
        output_file(
            output, title="Squiggle Visualization" if title is not None else title
        )
        save(plot, resources=INLINE if offline else None)
    else:
        show(plot)


if __name__ == "__main__":

0 View Source File : test_annotations.py
License : MIT License
Project Creator : rthorst

def test_Title():
    title = Title()
    assert title.level == 'annotation'
    assert title.text is None
    assert title.vertical_align == 'bottom'
    assert title.align == 'left'
    assert title.offset == 0
    assert title.text_font == 'helvetica'
    assert title.text_font_size == {'value': '10pt'}
    assert title.text_font_style == 'bold'
    assert title.text_color == '#444444'
    assert title.text_alpha == 1.0
    check_fill_properties(title, "background_", None, 1.0)
    check_line_properties(title, "border_", None, 1.0, 1.0)
    check_properties_existence(title, [
        "visible",
        "level",
        "text",
        "vertical_align",
        "align",
        "offset",
        "text_font",
        "text_font_size",
        "text_font_style",
        "text_color",
        "text_alpha",
        "render_mode"],
        prefix('border_', LINE),
        prefix('background_', FILL))


def test_Whisker():

0 View Source File : render.py
License : MIT License
Project Creator : sfu-db

def render_crossfilter(
    itmdt: Intermediate, plot_width: int, plot_height: int, cfg: Config
) -> column:
    """
    Render crossfilter scatter plot with a regression line.
    """

    # pylint: disable=too-many-locals, too-many-function-args

    if cfg.interactions.cat_enable:
        all_cols = itmdt["all_cols"]
    else:
        all_cols = itmdt["num_cols"]
    scatter_df = itmdt["scatter_source"]
    # all other plots except for scatter plot, used for cat-cat and cat-num interactions.
    other_plots = itmdt["other_plots"]
    if scatter_df.empty:
        scatter_df["__x__"] = [None] * len(itmdt["scatter_source"])
        scatter_df["__y__"] = [None] * len(itmdt["scatter_source"])
    else:
        scatter_df["__x__"] = scatter_df[scatter_df.columns[0]]
        scatter_df["__y__"] = scatter_df[scatter_df.columns[0]]
    source_scatter = ColumnDataSource(scatter_df)
    source_xy_value = ColumnDataSource({"x": [scatter_df.columns[0]], "y": [scatter_df.columns[0]]})
    var_list = list(all_cols)

    xcol = source_xy_value.data["x"][0]
    ycol = source_xy_value.data["y"][0]

    tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]
    scatter_fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )
    scatter = scatter_fig.scatter("__x__", "__y__", source=source_scatter)

    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    scatter_fig.add_tools(hover)

    fig_all_in_one = column(scatter_fig, sizing_mode="stretch_width")

    x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
    y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)

    x_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                fig_all_in_one=fig_all_in_one,
                scatter_plot=scatter_fig,
                x_axis=scatter_fig.xaxis[0],
                other_plots=other_plots,
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;
        xyValueData['x'][0] = currentSelect;
        xy_value.change.emit();

        const children = []
        let ycol = xyValueData['y'][0];
        let col = currentSelect + '_' + ycol
        if (col in other_plots) {
            children.push(other_plots[col])
        }
        else {
            scatterData['__x__'] = scatterData[currentSelect];
            x_axis.axis_label = currentSelect;
            scatter.change.emit();
            children.push(scatter_plot)
        }
        fig_all_in_one.children = children;        
        """,
        ),
    )
    y_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                fig_all_in_one=fig_all_in_one,
                scatter_plot=scatter_fig,
                y_axis=scatter_fig.yaxis[0],
                other_plots=other_plots,
            ),
            code="""
        let ycol = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;
        xyValueData['y'][0] = ycol;
        xy_value.change.emit();

        const children = []
        let xcol = xyValueData['x'][0];
        let col = xcol + '_' + ycol;
        if (col in other_plots) {
            children.push(other_plots[col])
        }
        else {
            scatterData['__y__'] = scatterData[ycol];
            y_axis.axis_label = ycol;
            scatter.change.emit();
            children.push(scatter_plot)
        }
        fig_all_in_one.children = children;        
        """,
        ),
    )

    interaction_fig = column(
        row(x_select, y_select, align="center"), fig_all_in_one, sizing_mode="stretch_width"
    )
    return interaction_fig


# ######### Interactions for report #########
# def render_crossfilter(
#     itmdt: Intermediate, plot_width: int, plot_height: int
# ) -> column:
#     """
#     Render crossfilter scatter plot with a regression line.
#     """

#     # pylint: disable=too-many-locals, too-many-function-args
#     source_scatter = ColumnDataSource(itmdt["data"])
#     source_coeffs = ColumnDataSource(itmdt["coeffs"])
#     source_xy_value = ColumnDataSource(
#         {"x": [itmdt["data"].columns[0]], "y": [itmdt["data"].columns[0]]}
#     )
#     var_list = list(itmdt["data"].columns)[0:-2]

#     xcol = source_xy_value.data["x"][0]
#     ycol = source_xy_value.data["y"][0]

#     tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]

#     fig = Figure(
#         plot_width=plot_width,
#         plot_height=plot_height,
#         toolbar_location=None,
#         title=Title(text="Scatter Plot & Regression Line", align="center"),
#         tools=[],
#         x_axis_label=xcol,
#         y_axis_label=ycol,
#     )
#     scatter = fig.scatter("__x__", "__y__", source=source_scatter)
#     fig.line("__x__", "__y__", source=source_coeffs, line_width=3)

#     # Not adding the tooltips before because we only want to apply tooltip to the scatter
#     hover = HoverTool(tooltips=tooltips, renderers=[scatter])
#     fig.add_tools(hover)

#     x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
#     y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)

#     x_select.js_on_change(
#         "value",
#         CustomJS(
#             args=dict(
#                 scatter=source_scatter,
#                 coeffs=source_coeffs,
#                 xy_value=source_xy_value,
#                 x_axis=fig.xaxis[0],
#             ),
#             code="""
#         let currentSelect = this.value;
#         let xyValueData = xy_value.data;
#         let scatterData = scatter.data;
#         let coeffsData = coeffs.data;

#         xyValueData['x'][0] = currentSelect;
#         scatterData['__x__'] = scatterData[currentSelect];
#         coeffsData['__x__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}x`];
#         coeffsData['__y__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}y`];

#         x_axis.axis_label = currentSelect;
#         scatter.change.emit();
#         coeffs.change.emit();
#         xy_value.change.emit();
#         """,
#         ),
#     )
#     y_select.js_on_change(
#         "value",
#         CustomJS(
#             args=dict(
#                 scatter=source_scatter,
#                 coeffs=source_coeffs,
#                 xy_value=source_xy_value,
#                 y_axis=fig.yaxis[0],
#             ),
#             code="""
#         let currentSelect = this.value;
#         let xyValueData = xy_value.data;
#         let scatterData = scatter.data;
#         let coeffsData = coeffs.data;

#         xyValueData['y'][0] = currentSelect;
#         scatterData['__y__'] = scatterData[currentSelect];
#         coeffsData['__x__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}x`];
#         coeffsData['__y__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}y`];

#         y_axis.axis_label = currentSelect;
#         scatter.change.emit();
#         coeffs.change.emit();
#         xy_value.change.emit();
#         """,
#         ),
#     )

#     fig = column(
#         row(x_select, y_select, align="center"), fig, sizing_mode="stretch_width"
#     )
#     return fig