예제 #1
0
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()
        reset = ResetTool()
        self.lasso_select = LassoSelectTool(
            renderers=self.circles,          # default = all available renderers
            select_every_mousemove=False,    # to enhance performance
        )

        self.lasso_select.overlay.line_alpha=0.9
        self.lasso_select.overlay.line_color="black"
        self.lasso_select.overlay.fill_alpha=0.2
        self.lasso_select.overlay.fill_color="grey"

        hover = self._get_hover_tool()
        self.tools = (
            pan, box_zoom, self.lasso_select, box_select,
            crosshair, save, reset, tap, wheel_zoom
        )
        self.plot.add_tools(*self.tools)
예제 #2
0
def create_viewer(title,
                  y_range,
                  toolbar_location=None,
                  toolbar_sticky=False,
                  tools="",
                  plot_width=annotatorSettings.viewerWidth,
                  plot_height=annotatorSettings.defaultViewerHeights,
                  x_axis_type='datetime',
                  add_tools=True):

    viewer = figure(
        title=title,
        tools=tools,
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=toolbar_location,
        # toolbar_sticky=False,
        x_axis_type=x_axis_type,
        y_range=y_range,
    )

    viewer.xaxis.formatter = DatetimeTickFormatter(
        years=["%F %T"],
        months=["%F %T"],
        days=["%F %T"],
        hours=["%F %T"],
        hourmin=["%F %T"],
        minutes=["%F %T"],
        minsec=["%F %T"],
        seconds=["%F %T"],
        milliseconds=["%F %T.%3N"],
    )

    # Create tools to add to ekgViewer.
    wheel_zoom = WheelZoomTool()
    tap_tool = TapTool()
    resizeTool = ResizeTool()
    box_select = BoxSelectTool(dimensions="width")
    hover = HoverTool(
        point_policy='snap_to_data',
        line_policy='nearest',
        tooltips=[
            ("index", "$index"),
            ("Time", "@x{%F %T.%3N %Z}"),
            ("Value", "@y"),
            # ("Time", '@time'),
        ],
        formatters={"x": "datetime"},
    )

    if add_tools:
        viewer.add_tools(hover, box_select, tap_tool, resizeTool)
        viewer.toolbar.active_drag = box_select
        viewer.toolbar.active_scroll = wheel_zoom
        viewer.toolbar.active_tap = tap_tool

    return viewer
예제 #3
0
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()

        lasso_select = LassoSelectTool(
            select_every_mousemove=False,  # enhance performance
        )

        code = """
            var projections = require("core/util/projections");
            var x = special_vars.x
            var y = special_vars.y
            var coords = projections.wgs84_mercator.inverse([x, y])
            return coords[%d].toFixed(2)
        """

        tooltips = '''
            <style>
                .bk-tooltip>div:not(:nth-child(-n+5)) {{
                    display:none;
                }}

                .bk-tooltip>div {{
                    background-color: #dff0d8;
                    padding: 5px;
                }}
            </style>

            <b>STATION: </b> @{STNNBR} <br />
            <b>LON: </b> @X_WMTS{custom} <br />
            <b>LAT: </b> @Y_WMTS{custom} <br />
        '''

        hover = HoverTool(toggleable=True,
                          mode='mouse',
                          tooltips=tooltips,
                          renderers=[self.env.wmts_map_scatter],
                          formatters={
                              'X_WMTS': CustomJSHover(code=code % 0),
                              'Y_WMTS': CustomJSHover(code=code % 1),
                          })

        tools = (pan, box_zoom, lasso_select, hover, crosshair, tap,
                 wheel_zoom)
        self.env.wmts_map.add_tools(*tools)

        # set defaults
        self.env.wmts_map.toolbar.active_drag = pan
        self.env.wmts_map.toolbar.active_inspect = [crosshair, hover]
        self.env.wmts_map.toolbar.active_scroll = wheel_zoom
        self.env.wmts_map.toolbar.active_tap = None
예제 #4
0
    def makedoc(doc):
        source = ColumnDataSource(dataframe)
        image_holder = ColumnDataSource({
            'image': [],
            'x': [],
            'y': [],
            'dx': [],
            'dy': []
        })
        tools = [
            ResetTool(),
            PanTool(),
            WheelZoomTool(),
            TapTool(),
            BoxSelectTool(),
            PolySelectTool(),
            UndoTool(),
            RedoTool()
        ]
        pca = figure(title='PCA',
                     x_range=[minx - 0.05 * rangex, maxx + 0.05 * rangex],
                     y_range=[miny - 0.05 * rangey, maxy + 0.05 * rangey],
                     sizing_mode='scale_both',
                     tools=tools)
        glyphs = pca.circle(source=source, x='x', y='y')

        sel = figure(title='Selected image',
                     x_range=[0, 1],
                     y_range=[0, 1],
                     sizing_mode='scale_both')
        image_canvas = sel.image_rgba('image',
                                      'x',
                                      'y',
                                      'dx',
                                      'dy',
                                      source=image_holder)

        def load_selected(attr, old, new):
            print('new index: ', new.indices)
            if len(new.indices) == 1:  # could be empty selection
                update_image_canvas_single(new.indices[0],
                                           data=dataframe,
                                           source=image_holder)
            elif len(new.indices) > 1:
                update_image_canvas_multi(new.indices,
                                          data=dataframe,
                                          source=image_holder)

        glyphs.data_source.on_change('selected', load_selected)

        fig = row([pca, sel], sizing_mode='stretch_both')
        doc.title = 'Bokeh microscopium app'
        doc.add_root(fig)
예제 #5
0
 def __create_tools(cls, **hoverkwargs):
     return [
         TapTool(),
         BoxSelectTool(dimensions='width'),
         BoxSelectTool(dimensions='height'),
         BoxSelectTool(),
         WheelZoomTool(),
         BoxZoomTool(),
         ResetTool(),
         SaveTool(),
         HoverTool(tooltips=[('workflow', '@Workflow'),
                             ('activity', '@Activity'),
                             ('result', '@Result'),
                             ('duration', '@DurationStr'),
                             ('started', '@StartedOnTimestampStr'),
                             ('ended', '@EndedOnTimeStampStr')],
                   formatters={
                       'started': 'printf',
                       'ended': 'printf'
                   },
                   show_arrow=True,
                   **hoverkwargs)
     ]
예제 #6
0
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()
        reset = ResetTool()     # TODO: add only to one plot, maybe with n_plot

        self.lasso_select = LassoSelectTool(
            renderers=self.circles,                  # default all available renderers
            select_every_mousemove=False,            # enhance performance
        )

        tooltips = '''
            <style>
                .bk-tooltip>div:not(:nth-child(-n+5)) {{
                    display:none;
                }}

                /* .bk-tooltip-custom + .bk-tooltip-custom {{
                    display: none;  sometimes everything is hidden with this
                }} */

                .bk-tooltip>div {{
                    background-color: #dff0d8;
                    padding: 5px;
                }}
            </style>

            <b>INDEX: </b> @INDEX <br>
            <b>{x}: </b> @{x} <br>
            <b>{x}_FLAG_W: </b> @{x}_FLAG_W <br>
            <b>{y}: </b> @{y} <br>
            <b>{y}_FLAG_W: </b> @{y}_FLAG_W <br>
        '''.format(x=self.x, y=self.y)

        hover = HoverTool(                  # TODO: try to make this toggleable
            renderers=self.circles,
            toggleable=True,
            mode='mouse',
            tooltips=tooltips,
        )

        tools = (
            pan, box_zoom, self.lasso_select, box_select,
            crosshair, save, reset, tap, wheel_zoom
        )
        self.plot.add_tools(*tools)
def make_region_plot(src, src_gene, src_tss, src_rna, fixed_yaxis=None):
    '''
    Construct pileup plot based on src
    '''

    # output_file(html_output)

    # flatten list of lists in count column of src, find max value of absolute expression
    frag_count_range = max(
        map(abs, [x for count in src.data['count'] for x in count]))
    if len(src_rna.data['y_plus']) > 0:
        rna_count_range = max(max(src_rna.data['y_plus']),
                              max(abs(src_rna.data['y_minus'])))
    else:
        rna_count_range = 0

    count_range = max(frag_count_range, rna_count_range)

    if fixed_yaxis:
        ymin = -1 * (fixed_yaxis)
        ymax = fixed_yaxis
    else:
        ymin = -(count_range + 1)
        ymax = count_range + 1

    # draw blank figure of correct size with tools
    p = figure(y_range=(ymin, ymax),
               plot_width=900,
               plot_height=700,
               tools=[
                   BoxSelectTool(),
                   BoxZoomTool(),
                   PanTool(),
                   WheelZoomTool(),
                   SaveTool(),
                   ResetTool()
               ],
               toolbar_location='above')

    legends = []

    # format axis and colors
    p.xaxis.axis_label = 'position'
    p.xaxis.major_label_orientation = pi / 4
    p.xaxis[0].formatter.use_scientific = False
    # p.xaxis[0].ticker=FixedTicker(ticks=range(start, end, 100))
    p.yaxis.axis_label = 'log normalized activity'

    patches = p.patches(source=src,
                        xs='position',
                        ys='count',
                        fill_color='color',
                        line_color=None,
                        alpha=0.50)
    legends.append(
        LegendItem(label='promoter activity (plus strand)',
                   renderers=[patches],
                   index=0))
    legends.append(
        LegendItem(label='promoter activity (minus strand)',
                   renderers=[patches],
                   index=1))

    # draw RNA lines
    if len(src_rna.data['x_minus']) > 0:
        plus_line = p.line(x='x_plus',
                           y='y_plus',
                           line_color='#528ecb',
                           line_width=2,
                           source=src_rna)
        legends.append(
            LegendItem(label='RNA-seq (plus strand)',
                       renderers=[plus_line],
                       index=0))
        minus_line = p.line(x='x_minus',
                            y='y_minus',
                            line_color='#ef8137',
                            line_width=2,
                            source=src_rna)
        legends.append(
            LegendItem(label='RNA-seq (minus strand)',
                       renderers=[minus_line],
                       index=1))

    # add second y-axis for TSS strength
    max_tss = max(map(abs, src_tss.data['y0']))
    p.extra_y_ranges = {
        'tss': Range1d(start=-(max_tss * 4), end=(max_tss * 4))
    }
    p.add_layout(LinearAxis(y_range_name='tss', axis_label='TSS expression'),
                 'right')

    # draw vertical rectangle
    p.quad(top='top',
           bottom='bottom',
           left='left',
           right='right',
           color='color',
           source=src_tss,
           y_range_name='tss')
    # draw horizontal line for arrow
    p.segment(x0='x0',
              y0='y0',
              x1='x1',
              y1='y1',
              color='color',
              source=src_tss,
              line_width=4,
              y_range_name='tss')
    # center of triangle is endpoint of segment
    tri = p.triangle(x='x1',
                     y='y1',
                     size=9,
                     angle='angle',
                     angle_units='deg',
                     color='color',
                     source=src_tss,
                     y_range_name='tss')
    legends.append(LegendItem(label='inactive TSS', renderers=[tri], index=9))
    legends.append(LegendItem(label='active TSS', renderers=[tri], index=0))

    # plot genes
    p.rect(x='gene_center',
           y='gene_center_y',
           width='gene_width',
           color='gene_color',
           height=10,
           height_units='screen',
           source=src_gene)
    p.triangle(x='tri_x',
               y=0,
               size=20,
               angle='angle',
               angle_units='deg',
               fill_color='gene_color',
               line_color=None,
               source=src_gene)
    p.text(x='gene_center',
           y='gene_center_y',
           text='gene_name',
           text_color='black',
           text_align='center',
           text_baseline='middle',
           text_font_size='10pt',
           source=src_gene)

    p.add_layout(Legend(items=legends), 'below')

    return p
예제 #8
0
annotation = mainViewer.line(x=[], y=[], color='navy', visible=True, line_width=3)

ppgDataSource = ppgLine.data_source
ppgLineMarkersDataSource = ppgLineMarkers.data_source
qosDataSource = qosMarkers.data_source
annotatedDataSource = annotation.data_source

#### Describe how selected data are handled. ####
selected_circle = Circle(fill_color='navy', visible=True)
nonselected_circle = Circle(fill_color='navy', visible=False)
ppgLineMarkers.selection_glyph = selected_circle
ppgLineMarkers.nonselection_glyph = nonselected_circle

wheel_zoom = WheelZoomTool()
tap_tool = TapTool()
box_select = BoxSelectTool(dimensions="width")
hover = HoverTool(
    point_policy='snap_to_data',
    line_policy='nearest',
    tooltips=[
        ("index", "$index"),
        ("Value", "@y"),
        # ("desc", "@desc"),
        ("Time", '@time'),
        ("Note", "@notes"),
    ],
    renderers=[
        qosMarkers,
        ppgLineMarkers,
    ]
)
예제 #9
0
    def __init__(self, dataset, parameters):

        self.dataset = dataset

        # Set up the controls
        self.specials = Selector(
            name="Specials",
            kind="specials",
            css_classes=["specials"],
            entries={
                "Color-magnitude diagram": "cmd",
                "Period vs. radius": "pr",
                "Period vs. transit duration": "pdt",
            },
            default="Color-magnitude diagram",
        )
        self.data = Selector(
            name="Datasets",
            kind="datasets",
            css_classes=["data"],
            entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"},
            default="Confirmed Planets",
        )
        self.xaxis = Selector(
            name="Build-Your-Own",
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="ra",
            title="X Axis",
        )
        self.yaxis = Selector(
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="dec",
            title="Y Axis",
        )
        self.size = Selector(
            name="Sides",
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Size",
            none_allowed=True,
        )
        self.color = Selector(
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Color",
            none_allowed=True,
        )

        # Set up the plot
        self.source = ColumnDataSource(
            data=dict(x=[], y=[], size=[], color=[])
        )
        self.plot = figure(
            plot_height=600,
            plot_width=700,
            title="",
            tooltips=[("TIC ID", "@ticid")],
            sizing_mode="scale_both",
        )
        self.plot.circle(
            x="x",
            y="y",
            source=self.source,
            size="size",
            color=linear_cmap(
                field_name="color", palette=Viridis256, low=0, high=1
            ),
            line_color=None,
        )
        self.plot.add_tools(
            BoxSelectTool(),
            BoxZoomTool(),
            LassoSelectTool(),
            PanTool(),
            PolySelectTool(),
            TapTool(),
            WheelZoomTool(),
            WheelPanTool(),
            ZoomInTool(),
            ZoomOutTool(),
            HoverTool(),
            CrosshairTool(),
            ResetTool(),
        )

        # Register the callback
        for control in [
            self.specials,
            self.data,
            self.xaxis,
            self.yaxis,
            self.size,
            self.color,
        ]:
            control.widget.on_change("value", self.callback)

        # Load and display the data
        self.callback(None, None, None)
예제 #10
0
파일: plotting.py 프로젝트: ratt-ru/ragavi
def create_bk_fig(x=None, xlab=None, x_min=None, x_max=None,
                  ylab=None, fh=None, fw=None,
                  title=None, pw=None, ph=None, x_axis_type="linear",
                  y_axis_type="linear", x_name=None, y_name=None, **kwargs):
    """ Generates a bokeh figure

    Parameters
    ----------
    x :obj:`DataArray`
        Contains x-axis data
    xlab : :obj:`str`
        X-axis label
    x_min : :obj:`float`
        Min x value
    x_max : :obj:`float`
        Max x value
    ylab : :obj:`str`
        Y-axis label
    fh: :obj:`int`
        True height of figure without legends, axes titles etc
    fw: :obj:`int`
        True width of figure without legends, axes etc
    title: :obj:`str`
        Title of plot
    pw: :obj:`int`
        Plot width including legends, axes etc
    ph: :obj:`int`
        Plot height including legends, axes etc
    x_axis_type: :obj:`str`
        Type of x-axis can be linear, log, or datetime
    y_axis_type: :obj:`str`
        Can be linear, log or datetime
    x_name: :obj:`str`
        Name of the column used for the x-axis. Mostly used to form tooltips
    y_name: :obj:`str`
        Name of the column used for the y-axis. Also used for tooltips
    add_grid: :obj:`bool`
        Whether or not to add grid
    add_title: :obj:`bool`
        Whether or not to add title to plot
    add_xaxis: :obj:`bool`
        Whether or not to add x-axis and tick marks
    add_yaxis: :obj:`bool`
        Add y-axis or not
    fix_plotsize: :obj:`bool`
        Enforce certain dimensions on plot. This is useful for ensuring a plot
        is not obscure by axes and other things. If activated, plot's
        dimensions will not be responsive. It utilises fw and fh.

    Returns
    -------
    p : :obj:`Plot`
        A bokeh Plot object

    """

    add_grid = kwargs.pop("add_grid", False)
    add_title = kwargs.pop("add_title", True)
    add_xaxis = kwargs.pop("add_xaxis", False)
    add_yaxis = kwargs.pop("add_yaxis", False)
    fix_plotsize = kwargs.pop("fix_plotsize", True)
    # addition plot specs
    pl_specs = kwargs.pop("pl_specs", {})
    # additional axis specs
    ax_specs = kwargs.pop("ax_specs", {})
    # ticker specs
    ti_specs = kwargs.pop("ti_specs", {})

    plot_specs = dict(background="white", border_fill_alpha=0.1,
                      border_fill_color="white", min_border=3,
                      name="plot", outline_line_dash="solid",
                      outline_line_width=2, outline_line_color="#017afe",
                      outline_line_alpha=0.4, output_backend="canvas",
                      sizing_mode="stretch_width", title_location="above",
                      toolbar_location="above")
    plot_specs.update(pl_specs)

    axis_specs = dict(minor_tick_line_alpha=0, axis_label_text_align="center",
                      axis_label_text_font="monospace",
                      axis_label_text_font_size="10px",
                      axis_label_text_font_style="normal",
                      major_label_orientation="horizontal")
    axis_specs.update(ax_specs)

    tick_specs = dict(desired_num_ticks=5)
    tick_specs.update(ti_specs)

    # Define frame width and height
    # This is the actual size of the plot without the titles et al
    if fix_plotsize and not(fh or fw):
        fw = int(0.98 * pw)
        fh = int(0.93 * ph)

    # define the axes ranges
    x_range = DataRange1d(name="p_x_range", only_visible=True)

    y_range = DataRange1d(name="p_y_range", only_visible=True)

    if x_min is not None and x_max is not None and x_name.lower() in ["channel", "frequency"]:
        x_range = Range1d(name="p_x_range", start=x_min, end=x_max)
        y_range.only_visible = False

    # define items to add on the plot
    p_htool = HoverTool(tooltips=[(x_name, "$x"),
                                  (y_name, "$y")],
                        name="p_htool", point_policy="snap_to_data")

    if x_name.lower() == "time":
        p_htool.tooltips[0] = (x_name, "$x{%d-%m-%Y %H:%M}")
        p_htool.formatters = {"$x": "datetime"}

    p_toolbar = Toolbar(name="p_toolbar",
                        tools=[p_htool, BoxSelectTool(), BoxZoomTool(),
                               # EditTool(), # BoxEditTool(), # RangeTool(),
                               LassoSelectTool(), PanTool(), ResetTool(),
                               SaveTool(), UndoTool(), WheelZoomTool()])
    p_ticker = BasicTicker(name="p_ticker", **tick_specs)

    # select the axis scales for x and y
    if x_axis_type == "linear":
        x_scale = LinearScale(name="p_x_scale")
        # define the axes and tickers
        p_x_axis = LinearAxis(axis_label=xlab, name="p_x_axis",
                              ticker=p_ticker, **axis_specs)
    elif x_axis_type == "datetime":
        x_scale = LinearScale(name="p_x_scale")
        # define the axes and tickers
        p_x_axis = DatetimeAxis(axis_label=xlab, name="p_x_axis",
                                ticker=p_ticker, **axis_specs)
    elif x_axis_type == "log":
        x_scale = LogScale(name="p_x_scale")
        p_x_axis = LogAxis(axis_label=xlab, name="p_x_axis",
                           ticker=p_ticker, **axis_specs)

    if y_axis_type == "linear":
        y_scale = LinearScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = LinearAxis(axis_label=ylab, name="p_y_axis",
                              ticker=p_ticker, **axis_specs)
    elif x_axis_type == "datetime":
        y_scale = LinearScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = DatetimeAxis(axis_label=xlab, name="p_y_axis",
                                ticker=p_ticker, **axis_specs)
    elif y_axis_type == "log":
        y_scale = LogScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = LogAxis(axis_label=ylab, name="p_y_axis",
                           ticker=p_ticker, **axis_specs)

    # Create the plot object
    p = Plot(plot_width=pw, plot_height=ph, frame_height=fh, frame_width=fw,
             toolbar=p_toolbar, x_range=x_range, x_scale=x_scale,
             y_range=y_range, y_scale=y_scale, **plot_specs)

    if add_title:
        p_title = Title(align="center", name="p_title", text=title,
                        text_font_size="24px",
                        text_font="monospace", text_font_style="bold",)
        p.add_layout(p_title, "above")

    if add_xaxis:
        p.add_layout(p_x_axis, "below")

    if add_yaxis:
        p.add_layout(p_y_axis, "left")

    if add_grid:
        p_x_grid = Grid(dimension=0, ticker=p_ticker)
        p_y_grid = Grid(dimension=1, ticker=p_ticker)
        p.add_layout(p_x_grid)
        p.add_layout(p_y_grid)

    return p
예제 #11
0
def plot():

    # Read data as if uploaded file is now used, Data set 1
    data1 = read_csv('app/static/uploads/Data1.csv', sep=',', skipinitialspace=1)

    xdata1 = data1.values[:,1]    # Extract Data
    ydata1 = data1.values[:,2]
    colour1 = ['black']*len(xdata1)

    # Read data as if uploaded file is now used, Data set 2
    data2 = read_csv('app/static/uploads/Data2.csv', sep=',', skipinitialspace=1)

    xdata2 = data2.values[:,1]
    ydata2 = data2.values[:,2]
    colour2 = ['green']*len(xdata2)

    # Read data as if uploaded file is now used, Data set 3
    data3 = read_csv('app/static/uploads/Data3.csv', sep=',', skipinitialspace=1)

    xdata3 = data3.values[:,1]
    ydata3 = data3.values[:,2]
    colour3 = ['red']*len(xdata3)

    # Prepare Data3
    # xdata3 = linspace(0, 100, 10)
    # ydata3 = sin(10*xdata3)

    # Data_pandas = DataFrame({'Time': xdata3,
    #                        'Value': ydata3})

    # Data_pandas.to_csv('app/static/uploads/Data3.csv')


    # Assign read data to ColumnDataSource objects
    sourceData1 = ColumnDataSource(data=dict(x=xdata1, y=ydata1, color=colour1))
    sourceData2 = ColumnDataSource(data=dict(x=xdata2, y=ydata2, color=colour2))
    sourceData3 = ColumnDataSource(data=dict(x=xdata3, y=ydata3, color=colour3))

    my_plot = figure(tools=[BoxSelectTool(dimensions=['width'], select_every_mousemove=True), PanTool(), ResetTool(), WheelZoomTool(), BoxZoomTool()],
                     title='Time series data',
                     x_range=(xdata1.min(), xdata1.max()),
                     y_range=(ydata1.min(), ydata1.max()),
                     width=1200)      # Create figure object; DEBUG: select_every_mousemove=False

    my_plot.extra_y_ranges = {# 'Data1': Range1d(start=ydata1.min(), end=ydata1.max()),
                              'Data2': Range1d(start=ydata2.min(), end=ydata2.max()),
                              'Data3': Range1d(start=ydata3.min(), end=ydata3.max())}

    my_plot.circle(x='x', y='y', color='color', source=sourceData1,
                   size=8, alpha=0.8, legend='Data 1')  # Add circle elements (glyphs) to the figure

    my_plot.circle(x='x', y='y', color='color', source=sourceData2,
                   size=5, alpha=0.8, y_range_name='Data2', legend='Data 2')

    my_plot.circle(x='x', y='y', color='color', source=sourceData3,
                   size=8, alpha=0.5, y_range_name='Data3', legend='Data 3')
    my_plot.line(x='x', y='y', color='red', source= sourceData3,
                 alpha=0.5, y_range_name='Data3', legend='Data 3')


    sourceFit = ColumnDataSource(data=dict(xfit=[], yfit=[]))
    my_plot.circle(x='xfit', y='yfit', source=sourceFit, color='orange', alpha=0.3)

    # my_plot.add_layout(LinearAxis(y_range_name='Data1', axis_line_color=colour1[0]), 'left')
    my_plot.add_layout(LinearAxis(y_range_name='Data2', axis_line_color=colour2[0], axis_line_width=3), 'left')
    my_plot.add_layout(LinearAxis(y_range_name='Data3', axis_line_color=colour3[0], axis_line_width=3), 'left')


    # sourceAnnotate = ColumnDataSource(data=dict(text=['Foo', 'Bah'], x=[50, 50], y=[0.5, 0], x_offset=[0,0], y_offset=[0,0], text_font_size=['15pt', '15pt'],

    #                                            text_color=['orange', 'orange']))
    # my_plot.text(source=sourceAnnotate, text='text', x='x', y='y', x_offset='x_offset', y_offset='y_offset', text_font_size='text_font_size', text_color='text_color')

    sourceData1.callback = CustomJS(args=dict(sourceFit=sourceFit), code=("""FirstOrderEyeball(cb_obj, sourceFit)"""))

    # sourceData.callback = CustomJS(args=dict(sourceFit=sourceFit, sourceAnnotate=sourceAnnotate), code=("""FirstOrderEyeball(cb_obj, sourceFit, sourceAnnotate)"""))

    script, div = components(my_plot)  # Break figure up into component HTML to be added to template
    return render_template("int_scatter.html", myScript=script, myDiv=div)
예제 #12
0
source = ColumnDataSource(data=dict(
    x=timepts, au=au, p1=p1, raw_lp_decim_p1=p1, p2=p2, raw_lp_decim_p2=p2))

# Create the tools for the toolbar
ts_cnt = np.arange(3)
cross = [CrosshairTool() for n in ts_cnt]
hover = [
    HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p1'), ('raw', '@raw_lp_decim_p1')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p2'), ('raw', '@raw_lp_decim_p2')])
]
xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt]
xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt]
xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt]
xtsel = [TapTool() for n in ts_cnt]
xpan = [PanTool(dimensions=['width']) for n in ts_cnt]
save = [SaveTool() for n in ts_cnt]
reset = [ResetTool() for n in ts_cnt]
tools = [[
    cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n],
    save[n], reset[n]
] for n in ts_cnt]

data_update_in_progress = False

play_all_button = Button(label='Play', button_type='success', width=60)
play_all_button.on_click(play_all)
play_all_sox_button = Button(label='Play sox', button_type='success', width=60)
play_all_sox_button.on_click(play_all_sox)
    ('ma-slow', '@ma_slow{0.2f}'),
    ('ma-fast', '@ma_fast{0.2f}'),
    ('time', '@time{%F %T}')
]

box_zoom = BoxZoomTool()
pan_tool = PanTool(dimensions='width')
wheel_zoom = WheelZoomTool()
reset_tool = ResetTool()
crosshair = CrosshairTool()
save = SaveTool()
hover_tool = HoverTool(
    tooltips=tooltips_top,
    formatters={'@time': 'datetime'}
)
box_selection = BoxSelectTool()

tools_top = [
    box_zoom,
    pan_tool,
    wheel_zoom,
    reset_tool,
    crosshair,
    save,
    hover_tool,
    box_selection
]

p1 = figure(plot_width=PLOT_WIDTH,
            plot_height=340,
            tools=tools_top,
예제 #14
0
# create widgets
expt_select = Select(title='Experiment:', options=expts, value=expts[0])
refresh = Button(label='Update')
div = Div(width=1000)

# hover tools
hover = HoverTool(tooltips=[('variable', '@variable'),
                            ('start', '@time_start{%F}'),
                            ('end', '@time_end{%F}'), ('run', '@run'),
                            ('file', '@ncfile')],
                  formatters={
                      'time_start': 'datetime',
                      'time_end': 'datetime'
                  })
tap = TapTool()
box_select = BoxSelectTool()
tools = [hover, box_select, tap, 'pan', 'box_zoom', 'wheel_zoom', 'reset']

df = get_data(expt_select.value)
freqs = df.frequency.unique()
cmap = factor_cmap('frequency',
                   palette=bokeh.palettes.Category10[10],
                   factors=freqs)
cds = ColumnDataSource(df, callback=print_selected(div))

p = figure(y_range=df.variable.unique(),
           x_range=(df.iloc[0].time_start, df.iloc[-1].time_end),
           title=expt_select.value,
           tools=tools)
cmap = factor_cmap('frequency',
                   palette=bokeh.palettes.Category10[10],
예제 #15
0
from bokeh.models.tools import BoxSelectTool
from bokeh.plotting import figure, show

# prepare some data
x = [1, 2, 3, 4, 5]
y = [1, 4, 2, 4, 5]

# create a new plot, with no tools
p = figure(tools="", width=400, height=400)

# Adding a tool, with custom tooltip
p.add_tools(BoxSelectTool(description="My tool"))

# add a line renderer with legend and line thickness
p.line(x, y, legend_label="Temp.", line_width=2)

# show the results
show(p)
예제 #16
0
from bokeh.models.tools import BoxSelectTool
from bokeh.plotting import figure, show

# prepare some data
x = [1, 2, 3, 4, 5]
y = [1, 4, 2, 4, 5]

# create a new figure with no tools
p = figure(tools="", width=400, height=400)

# Adding a tool with custom icon
p.add_tools(BoxSelectTool(icon="xpan"))

# add a line renderer with legend and line thickness
p.line(x, y, legend_label="Temp.", line_width=2)

# show the results
show(p)