Пример #1
0
def create_transactor_figure(G):
    plot = Plot(plot_width=800,
                plot_height=600,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Transactor Visualization"

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool(), PanTool())

    graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=4, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=4,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=3)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=3)

    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = EdgesAndLinkedNodes()

    plot.renderers.append(graph_renderer)

    return plot
Пример #2
0
def saveimg(smile, pltnm):
    atorvastatin = Chem.MolFromSmiles(smile)
    mh = Chem.AddHs(atorvastatin)
    rdDistGeom.EmbedMolecule(mh)
    _, res = rdEHTTools.RunMol(mh)
    static_chgs = res.GetAtomicCharges()[:atorvastatin.GetNumAtoms()]
    d = Draw.MolDraw2DCairo(400, 400)
    SimilarityMaps.GetSimilarityMapFromWeights(atorvastatin,
                                               list(static_chgs),
                                               draw2d=d)
    d.FinishDrawing()
    thing = show_png(d.GetDrawingText())
    name = "http://localhost:5006/fol/static/" + pltnm + ".png"
    thing.save(
        "C:\\Users\\patil.py\\Documents\\11F-Drive\\PFastWebLocalApp\\FlavorTool\\fol\\static\\"
        + pltnm + ".png")

    p = figure(x_range=(0, 1),
               y_range=(0, 1),
               toolbar_location=None,
               plot_width=200,
               plot_height=200)
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.visible = False
    thing = WheelZoomTool()
    p.add_tools(thing)
    p.toolbar.active_scroll = thing

    p.image_url(url=[name], x=0, y=1, w=1, h=1)
    return p
Пример #3
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)
Пример #4
0
def ridgeplot(courses_obj):
    # first format 'courses_obj' into 'probly' DataFrame format
    # courses_obj: [{'course_name': 'Calculus...', ...}, ...]
    grades = [[100*y[2]/y[3] for y in x['assignments']] for x in courses_obj]
    # turn this list of lists into a complete NumPy array
    length = len(sorted(grades, key=len, reverse=True)[0])
    grades = np.array([xi+[None]*(length-len(xi)) for xi in grades], dtype='float')
    columns = [x['course_name'] for x in courses_obj]
    grades = grades.transpose()
    probly = pd.DataFrame(grades, columns=columns)


    cats = list(reversed(probly.keys()))


    palette = [cc.rainbow[i*15] for i in range(17)]

    x = np.linspace(-20,110, 500)

    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=cats, plot_width=900, plot_height = 300, x_range=(-5, 120))#, toolbar_location=None)

    for i, cat in enumerate(reversed(cats)):
        adjusted = probly[cat].replace([np.inf, -np.inf], np.nan).dropna(how="all")
        if adjusted.size == 1 or pd.unique(adjusted).size == 1: # this means we can't compute
            continue
        pdf = gaussian_kde(adjusted)
        #p = figure(plot_width=400, plot_height=400)
        #p.line(x, pdf(x))
        y = ridge(cat, pdf(x), scale=2)
        #p.line(x, y, color='black')
        #show(p)
        source.add(y, cat)
        p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]

    ticks = list(np.array([np.array([0,3,7])+i*10 for i in range(10)]).flatten()) + [100]
    p.xaxis.ticker = FixedTicker(ticks=ticks)
    p.xaxis.formatter = PrintfTickFormatter(format="%d")
    p.xaxis.axis_label = "Your Grade Distribution"

    p.yaxis.axis_label = "Your Courses"

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "Grey"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.12

    return p
Пример #5
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
Пример #6
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
Пример #7
0
def workloadplot(courses_obj, is_ridge=True):
    # we just need to first get a list of lists of dicts
    # each sublist is a separate course
    # within each sublist you're gonna have a bunch of datetimes
    # for each datetime, you want to repeat it depending on the category
    datetimes = [[[xi[5]]*repeat(xi[1].lower()) for xi in x['assignments']] for x in courses_obj]
    datetimes = [list(itertools.chain.from_iterable(x)) for x in datetimes]
    datetimes = pd.DataFrame(datetimes, index=[x['course_name'] for x in courses_obj]).transpose()
    datetimes = datetimes.apply(pd.to_datetime) # convert to datetime
    datetimes = pd.DataFrame([datetimes[x].dt.week for x in datetimes])

    counts = pd.DataFrame([datetimes[x].value_counts() for x in datetimes]).transpose()
    #counts = 
    # use something like a[0].combine(pd.Series([0 for x in range(50)]), lambda x1, x2: x1 if type(x1)==type(pd.to_datetime('8/8/2018')) else pd.to_datetime('1/1/2018' ))

    assert(datetimes.shape[1] == len(courses_obj))

    # for each course, need a list where each element is the number of assignments
    # due that week (by index)
    first_date = time.mktime(datetimes.apply(min).min().timetuple())
    last_date = time.mktime(datetimes.apply(max).max().timetuple())

    x = np.arange(first_date, last_date+DIVISION, TWO_WEEKS)
    x_ = np.linspace(0,101,2)

    source = ColumnDataSource(data=dict(x_=x_))

    cats = list(datetimes.keys())



    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]
    p.xaxis.axis_label = "Your Workload Over Time"

    p.yaxis.axis_label = "Your Courses"

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "Grey"

    #ticks = ['Beginning', 'End']
    #p.xaxis.ticker = FixedTicker(ticks=ticks)

    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.8
    #p.y_range.group_padding = 3

    return p
Пример #8
0
def gradesplot(course_obj):
    assignment_array = course_obj['assignments']
    assignment_array.reverse()
    all_categories = get_categories(assignment_array)
    # get a list of lists
    # so each list within has all of the assignments belonging to that category/group
    data = []
    for category in all_categories:
        category_data = []
        for assignment in assignment_array:
            if assignment[1] == category:
                category_data.append(assignment)
        data.append(category_data)
    p = figure(x_axis_type="datetime", plot_width=1000, plot_height=300, y_range=(50,120))
    p.title.text = "Grades over time"

    colors = Spectral[len(all_categories)] if len(all_categories) >= 3 else Spectral[3][:len(all_categories)]
    
    assert(len(data) == len(all_categories) == len(colors))

    for datum, category, color in zip(data, all_categories, colors):
        df = pd.DataFrame(datum)
        df = df.rename({0:'name',1:'grouping', 2:'score', 3:'possible',4:'assigned',5:'due'}, axis='columns')

        df['due'] = pd.to_datetime(df['due'])
        source = ColumnDataSource(data=dict(
                x=df['due'],
                y=100*df['score']/df['possible'],
                category=df['grouping'],
                name=df['name']
            ))
        p.line('x', 'y', line_width=2, color=color, source=source, legend=category, tags=[category])
        p.circle('x', 'y', color=color, legend=category, source=source, tags=[category])

    p.ygrid.grid_line_alpha = 0.75
    p.ygrid.grid_line_color = "Black"
    p.legend.location = "bottom_left"
    p.legend.click_policy="hide"
    p.legend.label_text_font_size = '8pt'
    p.legend.spacing = -6

    p.toolbar.logo = None
    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = """
        <style>
            .bk-tooltip>div:not(:first-child) {display:none;}
        </style>
        <span style="font-size: 12px;">@name</span>
        <span style="font-size: 10px;"> (@category) <br>
        Grade: @y%</span>
    """

    return p
Пример #9
0
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1100,
                     height=400):
    """Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=list(data[x_name]))
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.05)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=.8,
                 fill_color="#ffdf00")
    plot.add_glyph(source, glyph)
    plot.add_tools(WheelZoomTool())
    plot.add_tools(BoxZoomTool())
    plot.add_tools(ZoomOutTool())

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Weight"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Grouping"
    plot.xaxis.major_label_orientation = 1
    return plot
Пример #10
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)
Пример #11
0
def create_figure(G, ntx):
    plot = Plot(plot_width=800,
                plot_height=600,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    #plot.title.text = "BTC Block Visualization"

    citation = Label(x=0, y=-20, x_units='screen', y_units='screen',
                text='This block contains '+str(ntx)+\
                 ' transactions between '+str(len(G.nodes()))+\
                 ' addresses. The most active address transacted with '+str(max(list(dict(G.degree()).values())))+\
                 ' addresses.',
                render_mode='css',
                border_line_color='red', border_line_alpha=1.0,
                background_fill_color='white', background_fill_alpha=1.0)

    #citation = Label(x=40, y=0, x_units='screen', y_units='screen',
    #             text='There were '+str(ntx)+' transactions total. The most active transactor was involved in '+str(max(list(dict(G.degree()).values())))+' transactions.',
    #             render_mode='css',
    #             border_line_color='black', border_line_alpha=1.0,
    #             background_fill_color='white', background_fill_alpha=1.0)

    plot.add_layout(citation)

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool(), PanTool())

    graph_renderer = from_networkx(G,
                                   nx.circular_layout,
                                   scale=1,
                                   center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=4, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=4,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=3)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=3)

    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = EdgesAndLinkedNodes()

    plot.renderers.append(graph_renderer)

    return plot
Пример #12
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)
Пример #13
0
    def plot_pulses2(self, km=False):

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        from bokeh.resources import CDN
        from bokeh.embed import components
        from bokeh.mpl import to_bokeh
        from bokeh.models.tools import WheelZoomTool, ResetTool, PanTool, HoverTool, SaveTool

        lines = self.get_lines()

        N = len(lines)
        npoints = self.total_units / self.km2unit if km else self.total_units
        fig = plt.figure(figsize=(12, 2 + N * 0.5))
        ax = fig.add_subplot(111)
        labels = ['IPP']

        for i, line in enumerate(lines):
            labels.append(line.get_name(channel=True))
            l = ax.plot((0, npoints), (N - i - 1, N - i - 1))
            points = [(tup[0], tup[1] - tup[0])
                      for tup in line.pulses_as_points(km=km) if tup != (0, 0)]
            ax.broken_barh(points, (N - i - 1, 0.5),
                           edgecolor=l[0].get_color(),
                           facecolor='none')

        n = 0
        f = ((self.ntx + 50) / 100) * 5 if (
            (self.ntx + 50) / 100) * 10 > 0 else 2
        for x in np.arange(0, npoints,
                           self.ipp if km else self.ipp * self.km2unit):
            if n % f == 0:
                ax.text(x, N, '%s' % n, size=10)
            n += 1

        labels.reverse()
        ax.set_yticks(range(len(labels)))
        ax.set_yticklabels(labels)
        ax.set_xlabel = 'Units'
        plot = to_bokeh(fig, use_pandas=False)
        plot.tools = [
            PanTool(dimensions=['width']),
            WheelZoomTool(dimensions=['width']),
            ResetTool(),
            SaveTool()
        ]
        plot.toolbar_location = "above"

        return components(plot, CDN)
Пример #14
0
def plot_layoult(title, grid1, save_figs=False, show_figs=True, grid2=None):

    if title is None:
        title='NOME DA FIGURA NAO FORNECIDO'
        
    xwheel_zoom = WheelZoomTool(dimensions="width")
    pan_tool = PanTool()
    hover = HoverTool()
    crosshair = CrosshairTool()

    toolbar = Toolbar(
        tools=[xwheel_zoom, pan_tool, hover, crosshair],
        active_inspect=[crosshair],
        # active_drag =                         # here you can assign the defaults
        # active_scroll =                       # wheel_zoom sometimes is not working if it is set here
        # active_tap
    )

    toolbar_box = ToolbarBox(toolbar=toolbar, toolbar_location="above")

    if grid2 is None:
        layout_2 = layout(children=[[
#                toolbar_box, 
                grid1
                ]], 
#                          sizing_mode="stretch_both",
#                          plot_width=400, plot_height=800,
                          )
    else:
        layout_2 = layout(children=[[
#                toolbar_box, 
                [[grid1], 
                [grid2]]
                ]],
#            sizing_mode="stretch_both",
#            plot_width=3000, plot_height=1000,
            )

    
    
    
    if save_figs is True:
        output_file(title + ".html")
        if show_figs is True:
            show(layout_2)
        else:
            save(layout_2)
    else:
        show(layout_2)
Пример #15
0
    def addplot(self, curve, *args):
        TOOLTIPS = [
        ("(curve)", "($name)"),
        ("(value)", "($x)")]
        logIndex=len(self.plotlist)
        r = lambda: random.randint(0,255)
        colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        if self.unitDict[curve] in ('ohmm', 'OHMM'):
            self.figDict["fig{0}".format(logIndex)]=figure(x_axis_type="log", x_axis_location='above')
        else:
            self.figDict["fig{0}".format(logIndex)] = figure(tooltips=TOOLTIPS, x_axis_location='above')
        # Define 1st LHS y-axis
        self.figDict["fig{0}".format(logIndex)].yaxis.axis_label = str(self.curvename[0])+' (' + str(self.unitDict[self.curvename[0]])+ ')'
        self.figDict["fig{0}".format(logIndex)].y_range = Range1d(start=max(self.df[self.curvename[0]]), end=min(self.df[self.curvename[0]]),  bounds=(None,None))

        # Define x-axis
        self.figDict["fig{0}".format(logIndex)].xaxis.axis_label = str(curve) + ' ('+ str(self.unitDict[curve])+')'
        self.figDict["fig{0}".format(logIndex)].x_range = Range1d(start=min(self.df[curve]), end=max(self.df[curve]))
        #fig.xaxis.ticker=SingleIntervalTicker(interval=30)
        self.figDict["fig{0}".format(logIndex)].xaxis.axis_label_text_color = colr
        # Define x-axis curve
        self.figDict["fig{0}".format(logIndex)].line(
            y = self.df[self.curvename[0]],
            x = self.df[curve],
            name = str(curve),
            color = colr
            )
        for curves in args:
            colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r())
            #add more x-axis
            self.figDict["fig{0}".format(logIndex)].extra_x_ranges [str(curves)] = Range1d(start=min(self.df[curves]), end=max(self.df[curves]))
            self.figDict["fig{0}".format(logIndex)].add_layout(LinearAxis( x_range_name=curves, 
                                      axis_label=str(curves) + ' ('+ str(self.unitDict[curves])+')', axis_label_text_color = colr), 'above')

            # Define other x-axis curve
            self.figDict["fig{0}".format(logIndex)].line(
                y = self.df[self.curvename[0]],
                x = self.df[curves],
                name = curves,
                x_range_name = str(curves),
                color = colr
            )
        self.plotlist.append(self.figDict["fig{0}".format(logIndex)])
        self.figDict["fig{0}".format(logIndex)].tools=[WheelZoomTool(),PanTool(),ResetTool()]
        self.figDict["fig{0}".format(logIndex)].add_tools(HoverTool(tooltips=TOOLTIPS))
        
        return self.figDict["fig{0}".format(logIndex)]
Пример #16
0
    def newplot(self, data, log, unit, *args):
        curve= data[log]
        TOOLTIPS = [
        ("(curve)", "($name)"),
        ("(value)", "($x)")]
        logIndex=len(self.plotlist)
        r = lambda: random.randint(0,255)
        colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        self.figDict["fig{0}".format(logIndex)] = figure(tooltips=TOOLTIPS, x_axis_location='above')
        # Define 1st LHS y-axis
        self.figDict["fig{0}".format(logIndex)].yaxis.axis_label = str(self.curvename[0])+' (' + str(self.unitDict[self.curvename[0]])+ ')'
        self.figDict["fig{0}".format(logIndex)].y_range = Range1d(start=max(curve.index), end=min(curve.index),  bounds=(None,None))
        
        # Define x-axis
        self.figDict["fig{0}".format(logIndex)].xaxis.axis_label = str(log) + ' ('+ str(unit)+')'
        self.figDict["fig{0}".format(logIndex)].x_range = Range1d(start=min(curve), end=max(curve))
        #fig.xaxis.ticker=SingleIntervalTicker(interval=30)
        self.figDict["fig{0}".format(logIndex)].xaxis.axis_label_text_color = colr
        # Define x-axis curve
        self.figDict["fig{0}".format(logIndex)].line(
            y = curve.index,
            x = curve,
            name = str(log),
            color = colr
            )
        for curved in args:
            curves=data[curved]
            colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r())
            #add more x-axis
            self.figDict["fig{0}".format(logIndex)].extra_x_ranges [str(curved)] = Range1d(start=min(curves), end=max(curves))
            self.figDict["fig{0}".format(logIndex)].add_layout(LinearAxis( x_range_name=curved, 
                                      axis_label=str(curved) + ' ('+ str(unit)+')', axis_label_text_color = colr), 'above')

            # Define other x-axis curve
            self.figDict["fig{0}".format(logIndex)].line(
                y = curves.index,
                x = curves,
                name = curved,
                x_range_name = str(curved),
                color = colr
            )
        self.plotlist.append(self.figDict["fig{0}".format(logIndex)])
        self.figDict["fig{0}".format(logIndex)].tools=[WheelZoomTool(),PanTool(),ResetTool()]
        self.figDict["fig{0}".format(logIndex)].add_tools(HoverTool(tooltips=TOOLTIPS))
        
        return self.figDict["fig{0}".format(logIndex)]
Пример #17
0
    def plot_perf(
        data: pd.DataFrame,
        mod: DirectReinforcementModel,
        tail: int = config["chartTail"],
        modelName: str = f"{config['modelName']} v{config['modelVersion']}",
    ) -> str:  # returns HTML str
        data = data.tail(tail)
        data = DataVisualiser.add_positions_to_data(mod, data)
        data = DataVisualiser.add_performance_to_data(mod, data)
        p1 = figure(
            x_axis_type="datetime",
            title="Cumulative Returns by Strategy",
            plot_width=800,
            plot_height=500,
        )
        p1.grid.grid_line_alpha = 0.3
        p1.xaxis.axis_label = "Date"
        p1.yaxis.axis_label = "Cumulative Returns"

        p1.toolbar.logo = None
        p1.tools = [
            PanTool(),
            # SaveTool(),
            WheelZoomTool(),
            ResetTool(),
            CrosshairTool(),
        ]

        p1.line(  # pylint: disable=too-many-function-args
            datet(data.closeTimeIso),
            data.modelReturnsCumSum,
            color="#33A02C",
            legend_label=modelName,
        )
        p1.line(  # pylint: disable=too-many-function-args
            datet(data.closeTimeIso),
            data.buyHoldReturns,
            color="#FB9A99",
            legend_label="HODL",
        )

        return file_html(p1, CDN), data
Пример #18
0
def show_image(ds):
    shape = ds['R'].shape
    aspect = shape[1] / shape[0]

    wheel_zoom = WheelZoomTool(zoom_on_axis=False)

    image = (hv.RGB(ds, ['X', 'Y'], ['R', 'G', 'B'])).opts(
        'RGB',
        default_tools=['pan', wheel_zoom, 'tap', 'reset'],
        active_tools=['tap', 'wheel_zoom'],
        xaxis=None,
        yaxis=None,
        aspect=aspect,
        responsive=True,
        hooks=[remove_white_borders],
    ).opts(toolbar='above')

    tap = hv.streams.Tap(source=image, x=shape[1], y=shape[0])
    tap.param.watch(tap_update, ['x', 'y'])
    return image
Пример #19
0
def render_from_fb_combined():
    print('rendering from facebook_combined.txt')
    df = pd.read_csv('facebook_combined.txt', sep=" ", header=None)
    G = nx.from_pandas_edgelist(df.head(1000), 0, 1)
    print(nx.info(G))

    plot = Plot(background_fill_color="white",
                sizing_mode="stretch_both",
                x_range=Range1d(-0.5, 0.5), y_range=Range1d(-0.5, 0.5))

    graph_renderer = from_networkx(
        G, nx.spring_layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(
        size=15, fill_color=Spectral4[0])
    graph_renderer.edge_renderer.glyph = MultiLine(
        line_alpha=0.8, line_width=1)

    plot.add_tools(WheelZoomTool())
    plot.add_tools(ResetTool())
    plot.add_tools(PanTool())
    plot.add_tools(HoverTool(
        tooltips=[("user", "datracka"), ("url", "https://twitter.com/datracka")]))
    plot.add_tools(PointDrawTool(
        renderers=[], empty_value='black'))

    plot.axis.axis_line_width = 0
    plot.grid.grid_line_width = 0
    plot.xaxis.major_tick_line_color = None  # turn off x-axis major ticks
    plot.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks
    plot.yaxis.major_tick_line_color = None  # turn off y-axis major ticks
    plot.yaxis.minor_tick_line_color = None  # turn off y-axis minor ticks
    plot.xaxis.major_label_text_color = None  # Remove label x axis
    plot.yaxis.major_label_text_color = None  # Remove label x axis
    plot.border_fill_color = None
    plot.outline_line_color = None

    plot.renderers.append(graph_renderer)

    return plot
Пример #20
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)
     ]
Пример #21
0
	def visualize(self):
		# add axes titles
		'''
		# Seaborn viz
		ax = sns.scatterplot(x = 0, y = 1, hue = 'clus_label', data = self.pca_frame)
		plt.title('Example Plot')
		plt.xlabel('PCA1')
		plt.ylabel('PCA2')
		plt.show()
		'''
		list_x = list(self.pca_frame[0].values)
		list_y = list(self.pca_frame[1].values)
		names = self.lookup.set_index(self.index_col)
		names = names.reindex(index = self.pca_frame.index)
		names.reset_index(inplace = True)
		# desc = list(self.pca_frame.index.values)
		desc = list(names[self.name_col].values)
		labels = list(self.pca_frame['clus_label'].values)

		source = ColumnDataSource(data=dict(x=list_x, y=list_y, desc=desc, color=labels))
		hover = HoverTool(tooltips=[
			# ("index", "$index"),
			# ("(PCA1, PCA2)", "(@x, @y)"),
			(self.index_col, '@desc'),
		])
		zoom = BoxZoomTool()
		pan = PanTool()
		wheel = WheelZoomTool()
		mapper = LinearColorMapper(palette=plasma(256), low=min(labels), high=max(labels))
		# mapper = CategoricalColorMapper(palette=plasma(256), low=min(labels), high=max(labels))

		p = figure(plot_width=1000, plot_height=600, tools=[hover, zoom, pan, wheel], title="Clustering Test:  " + self.index_col)
		p.circle('x', 'y', size=10, source=source, color=transform('color', mapper)) # fill_color arg is okay but looks worse

		output_file('cluster_viz_' + self.index_col + '.html')
		show(p)
Пример #22
0
class GeoPlot(ElementPlot):
    """
    Plotting baseclass for geographic plots with a cartopy projection.
    """

    default_tools = param.List(
        default=[
            'save', 'pan',
            WheelZoomTool(**({} if bokeh_version < '0.12.16' else {
                'zoom_on_axis': False
            })),
            BoxZoomTool(match_aspect=True), 'reset'
        ],
        doc="A list of plugin tools to use on the plot.")

    show_grid = param.Boolean(default=False,
                              doc="""
        Whether to show gridlines on the plot.""")

    # Project operation to apply to the element
    _project_operation = None

    def __init__(self, element, **params):
        super(GeoPlot, self).__init__(element, **params)
        self.geographic = is_geographic(self.hmap.last)

    def _axis_properties(self,
                         axis,
                         key,
                         plot,
                         dimension=None,
                         ax_mapping={
                             'x': 0,
                             'y': 1
                         }):
        axis_props = super(GeoPlot,
                           self)._axis_properties(axis, key, plot, dimension,
                                                  ax_mapping)
        if self.geographic:
            dimension = 'lon' if axis == 'x' else 'lat'
            axis_props['ticker'] = MercatorTicker(dimension=dimension)
            axis_props['formatter'] = MercatorTickFormatter(
                dimension=dimension)
        return axis_props

    def _postprocess_hover(self, renderer, source):
        super(GeoPlot, self)._postprocess_hover(renderer, source)
        hover = self.handles.get('hover')
        try:
            from bokeh.models import CustomJSHover
        except:
            CustomJSHover = None
        if (not self.geographic or None in (hover, CustomJSHover)
                or isinstance(hover.tooltips, basestring)):
            return
        element = self.current_frame
        xdim, ydim = [dimension_sanitizer(kd.name) for kd in element.kdims]
        code = """
        var projections = require("core/util/projections");
        var x = special_vars.data_x
        var y = special_vars.data_y
        var coords = projections.wgs84_mercator.inverse([x, y])
        return "" + (coords[%d]).toFixed(4)
        """
        formatters = {
            xdim: CustomJSHover(formatter=code % 0),
            ydim: CustomJSHover(formatter=code % 1),
        }
        tooltips = []
        for name, formatter in hover.tooltips:
            if formatter in ('@{%s}' % xdim, '@{%s}' % ydim):
                formatter += '{custom}'
            tooltips.append((name, formatter))
        hover.tooltips = tooltips
        hover.formatters = formatters

    def get_extents(self, element, ranges):
        """
        Subclasses the get_extents method using the GeoAxes
        set_extent method to project the extents to the
        Elements coordinate reference system.
        """
        extents = super(GeoPlot, self).get_extents(element, ranges)
        if not getattr(element, 'crs', None) or not self.geographic:
            return extents
        elif any(e is None or not np.isfinite(e) for e in extents):
            extents = None
        else:
            try:
                extents = project_extents(extents, element.crs, DEFAULT_PROJ)
            except:
                extents = None
        return (np.NaN, ) * 4 if not extents else extents

    def get_data(self, element, ranges, style):
        if self._project_operation and self.geographic and element.crs != DEFAULT_PROJ:
            element = self._project_operation(element)
        return super(GeoPlot, self).get_data(element, ranges, style)
Пример #23
0
        def update_plots(new):

            print("Starting update")

            nonlocal Estimators

            if not isinstance(Estimators, (type(np.array), list)):
                Estimators = np.array(Estimators)

            estimator_names = np.array(list(estimator_select.value))
            ix = np.isin(Estimator_Names, estimator_names)
            estimator_indices = [int(i) for i in np.where(ix)[0].flatten()]

            estimators = np.array(Estimators)[estimator_indices]

            variable1 = drop1.value
            variable2 = drop2.value
            y = drop3.value

            #Things to update:
            # image background i.e. image source √
            # observation source √
            #Color mapper values√
            #hover tool values √
            #Figure ranges √
            #Model score text things √

            #Lets calculate all the image and observation data first

            plots = [None for i in range(len(estimators))]
            image_sources = [None for i in range(len(estimators))]
            observation_sources = [None for i in range(len(estimators))]
            hover_tools = [None for i in range(len(estimators))]
            model_score_sources = [None for i in range(len(estimators))]
            glyphs0 = [None for i in range(len(estimators))]
            color_bars = [None for i in range(len(estimators))]
            p_circles = [None for i in range(len(estimators))]
            p_images = [None for i in range(len(estimators))]

            #Iterate over the estimators
            for idx, estimator in enumerate(estimators):
                #Find the title for each plot
                estimator_name = str(estimator()).split('(')[0]

                #Extract the needed data
                full_mat = X[[variable1, variable2, y]].dropna(how="any",
                                                               axis=0)

                #Define a class bijection for class colour mapping
                unique_classes, y_bijection = np.unique(full_mat[y],
                                                        return_inverse=True)
                full_mat['y_bijection'] = y_bijection

                #Rescale the X Data so that the data fits nicely on the axis/predictions are reliable
                full_mat[variable1 + "_s"] = StandardScaler().fit_transform(
                    full_mat[variable1].values.reshape((-1, 1)))
                full_mat[variable2 + "_s"] = StandardScaler().fit_transform(
                    full_mat[variable2].values.reshape((-1, 1)))

                #Define the Step size in the mesh
                delta = Delta

                #Separate the data into arrays so it is easy to work with
                X1 = full_mat[variable1 + "_s"].values
                X2 = full_mat[variable2 + "_s"].values
                Y = full_mat["y_bijection"].values

                #Define the mesh-grid co-ordiantes over which to colour in
                x1_min, x1_max = X1.min() - 0.5, X1.max() + 0.5
                x2_min, x2_max = X2.min() - 0.5, X2.max() + 0.5

                #Create the meshgrid itself
                x1, x2 = np.arange(x1_min, x1_max,
                                   delta), np.arange(x2_min, x2_max, delta)
                x1x1, x2x2 = np.meshgrid(x1, x2)

                #Create the train test split
                X_train, X_test, y_train, y_test = train_test_split(
                    full_mat[[variable1 + "_s", variable2 + "_s"]],
                    Y,
                    test_size=Test_Size,
                    random_state=Random_State)
                #Fit and predict/score the model
                model = estimator().fit(X=X_train, y=y_train)
                # train_preds = model.predict(X_train)
                # test_preds = model.predict(X_test)
                model_score = model.score(X_test, y_test)
                model_score_text = "Model score: %.2f" % model_score

                if hasattr(model, "decision_function"):
                    Z = model.decision_function(np.c_[x1x1.ravel(),
                                                      x2x2.ravel()])

                elif hasattr(model, "predict_proba"):
                    Z = model.predict_proba(np.c_[x1x1.ravel(), x2x2.ravel()])

                else:
                    print(
                        "This Estimator doesn't have a decision_function attribute and can't predict probabilities"
                    )

                Z = np.argmax(Z, axis=1)
                Z_uniques = np.unique(Z)

                unique_predictions = unique_classes[Z_uniques]

                Z = Z.reshape(x1x1.shape)

                #Add in the probabilities and predicitions for the tooltips
                full_mat["probability"] = np.amax(model.predict_proba(
                    full_mat[[variable1 + "_s", variable2 + "_s"]]),
                                                  axis=1)

                bijected_predictions = model.predict(
                    full_mat[[variable1 + "_s", variable2 + "_s"]])
                full_mat["prediction"] = unique_classes[bijected_predictions]

                #Add an associated color to the predictions
                number_of_colors = len(np.unique(y_bijection))

                #Create the hover tool to be updated
                hover = HoverTool(tooltips=[(
                    variable1, "@" +
                    variable1), (variable2, "@" +
                                 variable2), ("Probability", "@probability"),
                                            ("Prediction",
                                             "@prediction"), ("Actual",
                                                              "@" + y)])

                #Create the axes for all the plots
                plots[idx] = figure(x_axis_label=variable1,
                                    y_axis_label=variable2,
                                    title=estimator_name,
                                    x_range=(x1x1.min(), x1x1.max()),
                                    y_range=(x2x2.min(), x2x2.max()),
                                    plot_height=600,
                                    plot_width=600)

                #Create all the image sources
                image_data = dict()
                image_data['x'] = np.array([x1x1.min()])
                image_data["y"] = np.array([x2x2.min()])
                image_data['dw'] = np.array([x1x1.max() - x1x1.min()])
                image_data['dh'] = np.array([x2x2.max() - x2x2.min()])
                image_data['boundaries'] = [Z]

                image_sources[idx] = ColumnDataSource(image_data)

                #Create all the updatable images (boundaries)
                p_images[idx] = plots[idx].image(image='boundaries',
                                                 x='x',
                                                 y='y',
                                                 dw='dw',
                                                 dh='dh',
                                                 palette="RdBu11",
                                                 source=image_sources[idx])

                #Create the sources to update the observation points
                observation_sources[idx] = ColumnDataSource(data=full_mat)

                #Create all the updatable points
                low = full_mat["y_bijection"].min()
                high = full_mat["y_bijection"].max()
                cbar_mapper = LinearColorMapper(palette=RdBu[number_of_colors],
                                                high=high,
                                                low=low)

                p_circles[idx] = plots[idx].circle(
                    x=variable1 + "_s",
                    y=variable2 + "_s",
                    color=dict(field='y_bijection', transform=cbar_mapper),
                    source=observation_sources[idx],
                    line_color="black")

                #Create the hovertool for each plot
                hover_tools[idx] = hover

                #Add the hover tools to each plot
                plots[idx].add_tools(hover_tools[idx])

                #Create all the text sources (model scores) for the plots
                model_score_sources[idx] = ColumnDataSource(
                    data=dict(x=[x1x1.min() + 0.3],
                              y=[x2x2.min() + 0.3],
                              text=[model_score_text]))

                #Add the model scores to all the plots
                score_as_text = Text(x="x", y="y", text="text")
                glyphs0[idx] = plots[idx].add_glyph(model_score_sources[idx],
                                                    score_as_text)

                #Add a colorbar
                color_bars[idx] = ColorBar(
                    color_mapper=cbar_mapper,
                    ticker=BasicTicker(desired_num_ticks=number_of_colors),
                    label_standoff=12,
                    location=(0, 0),
                    bar_line_color="black")

                plots[idx].add_layout(color_bars[idx], "right")
                plots[idx].add_tools(LassoSelectTool(), WheelZoomTool())

                # configure so that no drag tools are active
                plots[idx].toolbar.tools = plots[idx].toolbar.tools[1:]
                plots[idx].toolbar.tools[0], plots[idx].toolbar.tools[
                    -2] = plots[idx].toolbar.tools[-2], plots[
                        idx].toolbar.tools[0]

            layout = gridplot([
                widgetbox(drop1, drop2, drop3, estimator_select, update_drop)
            ], [row(plot) for plot in plots])
            return layout

            #Finished the callback
            print("Ending Update")
            push_notebook(handle=handle0)
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
Пример #25
0
ppgLineMarkers = mainViewer.circle(x=[], y=[], color='navy', alpha=0.5, visible=False)
qosMarkers = mainViewer.circle(x=[], y=[], color='red', y_range_name='qosRange')
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,
Пример #26
0
class GeoPlot(ProjectionPlot, ElementPlot):
    """
    Plotting baseclass for geographic plots with a cartopy projection.
    """

    default_tools = param.List(
        default=[
            'save', 'pan',
            WheelZoomTool(**({} if bokeh_version < '0.12.16' else {
                'zoom_on_axis': False
            })),
            BoxZoomTool(match_aspect=True), 'reset'
        ],
        doc="A list of plugin tools to use on the plot.")

    fixed_bounds = param.Boolean(default=True,
                                 doc="""
        Whether to prevent zooming beyond the projections defined bounds.""")

    global_extent = param.Boolean(default=False,
                                  doc="""
        Whether the plot should display the whole globe.""")

    infer_projection = param.Boolean(default=False,
                                     doc="""
        Whether the projection should be inferred from the element crs.""")

    show_grid = param.Boolean(default=False,
                              doc="""
        Whether to show gridlines on the plot.""")

    show_bounds = param.Boolean(default=False,
                                doc="""
        Whether to show gridlines on the plot.""")

    projection = param.Parameter(default=GOOGLE_MERCATOR,
                                 doc="""
        Allows supplying a custom projection to transform the axis
        coordinates during display. Defaults to GOOGLE_MERCATOR.""")

    # Project operation to apply to the element
    _project_operation = None

    _hover_code = """
        var projections = require("core/util/projections");
        var x = special_vars.data_x
        var y = special_vars.data_y
        var coords = projections.wgs84_mercator.inverse([x, y])
        return "" + (coords[%d]).toFixed(4)
    """

    def __init__(self, element, **params):
        super(GeoPlot, self).__init__(element, **params)
        self.geographic = is_geographic(self.hmap.last)
        if self.geographic and not isinstance(self.projection,
                                              (PlateCarree, Mercator)):
            self.xaxis = None
            self.yaxis = None
            self.show_frame = False
            show_bounds = self._traverse_options(element,
                                                 'plot', ['show_bounds'],
                                                 defaults=False)
            self.show_bounds = not any(not sb
                                       for sb in show_bounds['show_bounds'])
            if self.show_grid:
                param.main.warning(
                    'Grid lines do not reflect {0}; to do so '
                    'multiply the current element by gv.feature.grid() '
                    'and disable the show_grid option.'.format(
                        self.projection))

    def _axis_properties(self,
                         axis,
                         key,
                         plot,
                         dimension=None,
                         ax_mapping={
                             'x': 0,
                             'y': 1
                         }):
        axis_props = super(GeoPlot,
                           self)._axis_properties(axis, key, plot, dimension,
                                                  ax_mapping)
        proj = self.projection
        if self.geographic and proj is GOOGLE_MERCATOR:
            dimension = 'lon' if axis == 'x' else 'lat'
            axis_props['ticker'] = MercatorTicker(dimension=dimension)
            axis_props['formatter'] = MercatorTickFormatter(
                dimension=dimension)
        return axis_props

    def _update_ranges(self, element, ranges):
        super(GeoPlot, self)._update_ranges(element, ranges)
        if not self.geographic:
            return
        if self.fixed_bounds:
            self.handles['x_range'].bounds = self.projection.x_limits
            self.handles['y_range'].bounds = self.projection.y_limits
        if self.projection is GOOGLE_MERCATOR:
            # Avoid zooming in beyond tile and axis resolution (causing JS errors)
            options = self._traverse_options(element,
                                             'plot', ['default_span'],
                                             defaults=False)
            min_interval = options['default_span'][0] if options.get(
                'default_span') else 5
            for r in ('x_range', 'y_range'):
                ax_range = self.handles[r]
                start, end = ax_range.start, ax_range.end
                if (end - start) < min_interval:
                    mid = (start + end) / 2.
                    ax_range.start = mid - min_interval / 2.
                    ax_range.start = mid + min_interval / 2.
                ax_range.min_interval = min_interval

    def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):
        opts = {} if isinstance(self, HvOverlayPlot) else {'source': source}
        fig = super(GeoPlot, self).initialize_plot(ranges, plot, plots, **opts)
        if self.geographic and self.show_bounds and not self.overlaid:
            from . import GeoShapePlot
            shape = Shape(self.projection.boundary,
                          crs=self.projection).options(fill_alpha=0)
            shapeplot = GeoShapePlot(shape,
                                     projection=self.projection,
                                     overlaid=True,
                                     renderer=self.renderer)
            shapeplot.geographic = False
            shapeplot.initialize_plot(plot=fig)
        return fig

    def _postprocess_hover(self, renderer, source):
        super(GeoPlot, self)._postprocess_hover(renderer, source)
        hover = self.handles.get('hover')
        try:
            from bokeh.models import CustomJSHover
        except:
            CustomJSHover = None
        if (not self.geographic or None in (hover, CustomJSHover)
                or isinstance(hover.tooltips, basestring)
                or self.projection is not GOOGLE_MERCATOR
                or hover.tooltips is None):
            return
        element = self.current_frame
        xdim, ydim = [dimension_sanitizer(kd.name) for kd in element.kdims]
        formatters, tooltips = {}, []
        xhover = CustomJSHover(code=self._hover_code % 0)
        yhover = CustomJSHover(code=self._hover_code % 1)
        for name, formatter in hover.tooltips:
            customjs = None
            if formatter in ('@{%s}' % xdim, '$x'):
                dim = xdim
                customjs = xhover
            elif formatter in ('@{%s}' % ydim, '$y'):
                dim = ydim
                customjs = yhover
            if customjs:
                key = formatter if formatter in ('$x', '$y') else dim
                formatters[key] = customjs
                formatter += '{custom}'
            tooltips.append((name, formatter))
        hover.tooltips = tooltips
        hover.formatters = formatters

    def get_data(self, element, ranges, style):
        proj = self.projection
        if self._project_operation and self.geographic:
            element = self._project_operation(element, projection=proj)
        return super(GeoPlot, self).get_data(element, ranges, style)
Пример #27
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)
Пример #28
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)
Пример #29
0
mean.add_layout(span)
# =============================================================================
multi_plot = Plot(plot_width=800,
                  plot_height=400,
                  background_fill_color='silver')
multi_glyph = MultiLine(xs='waves', ys='ys', line_width=2, line_color='label')
multi_plot.add_glyph(spectra_visible_multi, multi_glyph)
xaxis, yaxis = LinearAxis(), LinearAxis()
multi_plot.add_layout(xaxis, 'below')
multi_plot.xaxis.axis_label = 'Wavelength (nm)'
multi_plot.add_layout(yaxis, 'left')
multi_plot.yaxis.axis_label = 'Intensity (CPS)'
multi_plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
multi_plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
multi_plot.add_tools(BoxZoomTool())
multi_plot.add_tools(WheelZoomTool())
multi_plot.add_tools(ResetTool())
multi_plot.add_tools(SaveTool())
multi_plot.add_layout(span)
# =============================================================================
# ~~  Clustering figures
# ~  labeled_materials_image: map image of predicted material labels
# ~  elbow inertia vs n_materials plot
# ~  varBar bar plot of pca explained variances
# =============================================================================
labeled_materials_image, label_mapper = basicMap(labeled_materials, 400,
                                                 'image')
# elbow = figure(x_axis_label='Number of Materials', y_axis_label='Learning Inertia',
#                plot_width=400, plot_height=200, toolbar_location=None)
# elbow.line('num_clusters', 'inertia', source=elbow_plot)
varBar = figure(plot_width=400, plot_height=200, toolbar_location=None)
Пример #30
0
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