def test_band(output_file_url, selenium, screenshot):

    x_range = Range1d(0, 10)
    y_range = Range1d(0, 10)

    # Have to specify x/y range as labels aren't included in the plot area solver
    plot = Plot(plot_height=HEIGHT,
                plot_width=WIDTH,
                x_range=x_range,
                y_range=y_range,
                toolbar_location=None)

    source = ColumnDataSource(data=dict(
        x1=[1, 3, 5, 7, 9],
        lower1=[1, 2, 1, 2, 1],
        upper1=[2, 3, 2, 3, 2],
        x2=[200, 250, 350, 450, 550],
        lower2=[400, 300, 400, 300, 400],
        upper2=[500, 400, 500, 400, 500],
    ))

    band1 = Band(base='x1',
                 lower='lower1',
                 upper='upper1',
                 line_width=3,
                 line_color='red',
                 line_dash='dashed',
                 source=source)
    band2 = Band(base='x2',
                 lower='lower2',
                 upper='upper2',
                 base_units='screen',
                 lower_units='screen',
                 upper_units='screen',
                 dimension='width',
                 line_width=3,
                 fill_color='blue',
                 line_color='green',
                 source=source)

    plot.add_layout(band1)
    plot.add_layout(band2)

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)

    # Take screenshot
    screenshot.assert_is_valid()
    def plot(self, figure):
        source = self.asColumnDataSource()
        figure.title.text = self.title

        for party in self.parties:
            color = self.party_to_color[party]
            figure.circle('Date', party, source=source, size=4, color=color, alpha=0.1)
            figure.line('Date', party + '_mean', source=source, color=color)

            band = Band(
                base='Date',
                lower=party + '_low',
                upper=party + '_up',
                source=source,
                level='underlay',
                fill_alpha=0.2,
                line_width=1,
                fill_color=color)
            figure.add_layout(band)

            if self.results:
                election_result = Span(
                    location=self.results[party],
                    dimension='width',
                    line_color=color,
                    line_width=2)
                figure.add_layout(election_result)

        self._plot_next_election(figure)
        self._plot_today(figure)

        return figure
Example #3
0
def plot_data(data, ticker):
    p = bk.figure(x_axis_type='datetime')
    p.xaxis.axis_label = 'Date'
    p.yaxis.axis_label = 'Price'
    p.line(data['Date'],
           data['Open'],
           legend=ticker + ' Open',
           line_color="green")
    p.line(data['Date'], data['Close'], legend=ticker + ' Close')
    p.line(data['Date'],
           data['High'],
           legend=ticker + ' High',
           line_color='red')
    p.line(data['Date'],
           data['Low'],
           legend=ticker + ' Low',
           line_color='orange')
    source = ColumnDataSource({
        'base': data['Date'],
        'lower': data['Low'],
        'upper': data['High']
    })
    band = Band(base='base',
                lower='lower',
                upper='upper',
                source=source,
                level='underlay',
                fill_alpha=1.0,
                line_width=1,
                line_color='black')
    p.add_layout(band)
    return p
Example #4
0
    def init(self, doc):
        # Source must only be modified through a stream
        self.source = ColumnDataSource(data=self.data)
        self.colors[0] = 'cyan'
        #self.source = ColumnDataSource(data=self.data[self.scale])

        # Enable theming
        theme = Theme(
            os.path.dirname(os.path.abspath(__file__)) + '/theme.yaml')
        doc.theme = theme
        self.doc = doc

        fig = figure(plot_width=600,
                     plot_height=400,
                     tools='xpan,xwheel_zoom, xbox_zoom, reset, save',
                     title=self.title,
                     x_axis_label=self.XAXIS,
                     y_axis_label=self.ylabel)

        # Initialize plots
        for i, key in enumerate(self.keys):
            fig.line(source=self.source,
                     x=self.x,
                     y=key,
                     color=self.colors[i],
                     line_width=LINE_WIDTH,
                     legend_label=key)

            band = Band(source=self.source,
                        base=self.x,
                        lower=key + 'lower',
                        upper=key + 'upper',
                        level='underlay',
                        line_color=self.colors[i],
                        line_width=1,
                        line_alpha=0.2,
                        fill_color=self.colors[i],
                        fill_alpha=0.2)
            fig.add_layout(band)

        def switch_scale(attr, old, new):
            """Callback for RadioButtonGroup to switch tick scale
            and refresh document
            Args:
                attr: variable to be changed, in this case 'active'
                old: old index of active button
                new: new index of active button
            """
            self.scale = self.scales[new]
            self.source.data = self.data[self.scale]

        self.timescales = RadioButtonGroup(
            labels=[str(scale) for scale in self.scales],
            active=self.scales.index(self.scale))
        self.timescales.on_change('active', switch_scale)

        self.structure = layout([[self.timescales], [fig]])
        self.doc.add_root(self.structure)

        self.fig = fig
Example #5
0
def test_Band() -> None:
    band = Band()
    assert band.level == 'annotation'
    assert band.lower == field("lower")
    assert band.lower_units == 'data'
    assert band.upper == field("upper")
    assert band.upper_units == 'data'
    assert band.base == field("base")
    assert band.dimension == 'height'
    assert isinstance(band.source, ColumnDataSource)
    assert band.x_range_name == 'default'
    assert band.y_range_name == 'default'
    check_line_properties(band, "", "#cccccc", 1.0, 0.3)
    check_fill_properties(band, "", "#fff9ba", 0.4)
    check_properties_existence(
        band, ANNOTATION + [
            "lower",
            "lower_units",
            "upper",
            "upper_units",
            "base",
            "base_units",
            "dimension",
            "source",
        ], LINE, FILL)
def plot_classification(point, ideal_function):
    """
    plots the classification function and a point on top. It also displays the tolerance
    :param point: a dict with "x" and "y"
    :param ideal_function: a classification object
    """
    if ideal_function is not None:
        classification_function_dataframe = ideal_function.dataframe

        point_str = "({},{})".format(point["x"], round(point["y"], 2))
        title = "point {} with classification: {}".format(point_str, ideal_function.name)

        p = figure(title=title, x_axis_label='x', y_axis_label='y')

        # draw the ideal function
        p.line(classification_function_dataframe["x"], classification_function_dataframe["y"],
                legend_label="Classification function", line_width=2, line_color='black')

        # procedure to show the tolerance within the graph
        criterion = ideal_function.tolerance
        classification_function_dataframe['upper'] = classification_function_dataframe['y'] + criterion
        classification_function_dataframe['lower'] = classification_function_dataframe['y'] - criterion

        source = ColumnDataSource(classification_function_dataframe.reset_index())

        band = Band(base='x', lower='lower', upper='upper', source=source, level='underlay',
            fill_alpha=0.3, line_width=1, line_color='green', fill_color="green")

        p.add_layout(band)

        # draw the point
        p.scatter([point["x"]], [round(point["y"], 4)], fill_color="red", legend_label="Test point", size=8)

        return p
Example #7
0
    def update(self):
        if self.test_done and not self.analysed:
            self.btn.label = 'Test Complete'
            np.savetxt('test.txt', np.column_stack((self.x, self.y)))
            x = np.array(self.x)
            y = np.array(self.y)
            results = analyse_data(x, y, 7, 3)
            tmeans, fmeans, e_fmeans, msg, _critical_load, load_asymptote, predicted_force = results
            self.results_div.text = msg

            fill_src = ColumnDataSource(dict(x=tmeans, upper=predicted_force,
                                             lower=load_asymptote*np.ones_like(tmeans)))
            self.fig.add_layout(
                Band(base='x', lower='lower', upper='upper', source=fill_src, fill_alpha=0.7)
            )
            self.fig.circle(tmeans, fmeans, color='red', size=5, line_alpha=0)

            esource = ColumnDataSource(dict(x=tmeans, upper=fmeans+e_fmeans, lower=fmeans-e_fmeans))
            self.fig.add_layout(
                Whisker(source=esource, base='x', upper='upper', lower='lower', level='overlay')
            )
            self.analysed = True
        else:
            if self.tindeq is not None:
                self.btn.label = 'Start Test'
            self.state.update(self)
            self.source.stream({'x': self.xnew, 'y': self.ynew})
            nlaps = self.duration // 10
            self.laps.text = f"Rep {1 + nlaps - self.reps}/{nlaps}"
            self.reset()
def plot(env: str, var: str  = 'duration', n_steps:List = None, ncols:int = 3, win:int = 20, standalone:bool = False):
    """
        env: which enviroment to plot for
        var: which variable to plot against the episodes
        n_steps: list of n steps to plot for
        ncols: numbe rof columns in the output
        win: size of the smoothing avg window
        standalone: to plto also standalone
    """
    df = load_csv(env)
    # df = pd.read_csv('data/CartPole-v0.csv', dialect='unix')
    cnf = {True: {'legend': 'Semi-gradient', 'color': '#66C2A5'},
           False: {'legend': 'Full-gradient', 'color': '#FC8D62'}}

    varnames = {'G': 'Return',
                'duration': 'Length of episode'}

    if n_steps is None:
        n_steps = sorted(df.n_step.unique())
    figs = []
    for n_step in n_steps:
        step_df = df[df.n_step == n_step]
        fig = figure(title=f'{varnames.get(var, var)} using {n_step}-step TD', active_scroll='wheel_zoom')
        for semi in (True, False):
            # _df = step_df[df.semi_gradient == semi]
            # fig.circle(_df.episode, _df[var], legend=cnf[semi]['legend'], line_color=cnf[semi]['color'])
            mean_df = step_df[df.semi_gradient == semi].groupby(['episode']).agg({var: ['mean', 'std', 'min', 'max']})

            # Smooth the curves
            mean_df = mean_df.rolling(win, min_periods=1).mean()
            mean_df = mean_df.fillna(0)

            # Plot the mean line
            fig.line(mean_df.index, mean_df[var]['mean'], legend=cnf[semi]['legend'], line_color=cnf[semi]['color'], line_width=2)

            # Plot the std band
            mean_df['upper'] = mean_df[var]['mean'] + mean_df[var]['std'] / 2
            mean_df['lower'] = mean_df[var]['mean'] - mean_df[var]['std'] / 2
            # mean_df['upper'] = mean_df[var]['max']
            # mean_df['lower'] = mean_df[var]['min']
            source = ColumnDataSource(mean_df)
            band = Band(base='episode', lower='lower_', upper='upper_', source=source, level='underlay',
                        fill_alpha=.1, line_width=0, fill_color=cnf[semi]['color'])
            fig.add_layout(band)
        figs.append(fig)

    grid = gridplot(figs, ncols=ncols, sizing_mode='stretch_both', toolbar_location='below')

    html_components = '\n'.join(components(grid))
    path = os.path.join(os.getcwd(), 'docs/_includes', f'{env}_{var}.html')
    print(f'Save plot to {path}')
    with open(path, 'w') as fp:
        fp.write(html_components)

    if standalone:
        html_standalone = file_html(grid, CDN, f"{env}_{var}")
        path = os.path.join(os.getcwd(), 'docs/_includes', f'{env}_{var}_standalone.html')
        with open(path, 'w') as fp:
            fp.write(html_standalone)
Example #9
0
    def update(self, data_dict):
        for plot, fig in zip(self.plots, self.figures):

            try:
                try:
                    key, idx = fig.title.text.split('-')
                    data = data_dict[key][int(idx)]
                except ValueError:
                    data = data_dict[fig.title.text]
            except KeyError:
                if self.i == 0:
                    pass
                else:
                    continue

            new_data = dict()
            if self.i == 0:

                if fig.title.text == 'samples':
                    fig.xaxis.axis_label = 'phi'
                    fig.yaxis.axis_label = 'phi_dot'
                    new_data['x'], new_data['y'], *_ = [data[0], data[1]]

                elif fig.title.text == 'model_ranges':

                    new_data = {'lower': [1.0], 'upper': [1.0], 'x': [self.i], 'y': [1.0]}
                    plot.data_source.data.update(new_data)

                    self.band = Band(base='x', lower='lower', upper='upper', source=plot.data_source, level='underlay',
                                     fill_alpha=1.0, line_width=1, line_color='black')
                    fig.add_layout(self.band)
                    fig.xaxis.axis_label = 'iteration'
                else:
                    fig.xaxis.axis_label = 'iteration'

                    new_data['x'] = [self.i]
                    new_data['y'] = [data]


            else:
                if fig.title.text == 'samples':
                    new_data['x'] = plot.data_source.data['x'] + data[0]
                    new_data['y'] = plot.data_source.data['y'] + data[1]
                elif fig.title.text == 'model_ranges':
                    new_data['x'] = plot.data_source.data['x'] + [self.i]
                    new_data['y'] = plot.data_source.data['y'] + [data['y']]
                    new_data['lower'] = plot.data_source.data['lower'] + [data['lower']]
                    new_data['upper'] = plot.data_source.data['upper'] + [data['upper']]
                    fig.y_range = Range1d(np.min(plot.data_source.data['lower']), 2)
                else:
                    new_data['x'] = plot.data_source.data['x'] + [self.i]
                    new_data['y'] = plot.data_source.data['y'] + [data]


            plot.data_source.data.update(new_data)
        self.i += 1

        push_notebook(handle=self.plot_handle)
Example #10
0
def test_Whisker_and_Band_accept_negative_values() -> None:
    whisker = Whisker(base=-1., lower=-1.5, upper=-0.5)
    assert whisker.base == -1.
    assert whisker.lower == -1.5
    assert whisker.upper == -0.5
    band = Band(base=-1., lower=-1.5, upper=-0.5)
    assert band.base == -1.
    assert band.lower == -1.5
    assert band.upper == -0.5
Example #11
0
def create_plot(source, x, y, depth, sat_position, title):
    depth_is_positive = depth.startswith("+")
    depth_coordinate = depth[1]
    plot = figure(
        plot_height=400,
        plot_width=400,
        title=title,
        match_aspect=True,
        aspect_scale=1,
        tools="",
        x_range=[-constants.PLOTS_RANGE, constants.PLOTS_RANGE],
        y_range=[-constants.PLOTS_RANGE, constants.PLOTS_RANGE],
        background_fill_color=colors["background"],
        border_fill_color=colors["elements-background"],
        outline_line_alpha=0,
    )
    plot.title.text_color = colors["text-dimmed"]
    plot.grid.visible = False
    plot.axis.visible = False
    plot.line(
        x,
        y,
        source=source,
        line_width=3,
        line_dash="dashed",
        line_color=colors["orbit"],
    )
    plot.circle(
        x,
        y,
        source=source,
        view=generate_view(source, depth_coordinate, depth_is_positive),
        size=5,
        color=colors["orbit"],
    )
    plot.circle(
        x,
        y,
        source=sat_position,
        color=colors["satellite"],
        size=10,
    )
    plot.add_layout(
        Band(
            base="x",
            lower="lower",
            upper="upper",
            source=earth,
            level="underlay",
            fill_alpha=0.5,
            line_width=1,
            line_color=colors["earth"],
            fill_color=colors["earth"],
        )
    )
    return plot
Example #12
0
def add_band(f, x, ylo, yhi, source, color, alpha=0.3, y_range_name='default'):
    band = Band(base=x,
                lower=ylo,
                upper=yhi,
                source=ColumnDataSource(source),
                fill_color=color,
                fill_alpha=alpha,
                line_width=1,
                line_color=color,
                y_range_name=y_range_name)
    f.add_layout(band)
 def add_band(self, x_column, source, max_values_column, min_values_column):
     # add a 'confidence interval' or band to the figure
     max_min_interval = Band(base=x_column,
                             lower=max_values_column,
                             upper=min_values_column,
                             source=ColumnDataSource(source),
                             level='underlay',
                             fill_alpha=1.0,
                             line_width=1,
                             line_color='black')
     self.p.add_layout(max_min_interval)
Example #14
0
def SFH_plot(DB, SDB, gid):
    rshift = DB.query('id == {}'.format(gid)).zgrism.values[0]
    t50 = DB.query('id == {}'.format(gid)).t_50.values[0]
    t50_err = DB.query('id == {}'.format(gid)).t_50_hdr.values[0]
    
    t50_l = t50_err[0]
    t50_h = t50_err[1]
    
    x = np.linspace(t50_l, t50_h, 100)
    top = interp1d(SDB.LBT,SDB['{}_84'.format(gid)])(x)
    bottom = interp1d(SDB.LBT,SDB['{}_16'.format(gid)])(x)
    

    df = pd.DataFrame({'x':x, 'top':top, 'bottom':bottom})
    source = ColumnDataSource(df)
    
    LBT = SDB.LBT
    SFH = SDB['{}'.format(gid)]
    LBT = LBT[SFH**2 > 0]
    SFH = SFH[SFH**2 > 0]
    
    zs = [z_at_value(cosmo.lookback_time,(U*u.Gyr + cosmo.lookback_time(rshift)),
                     zmax=1E6) for U in LBT]

    src_sfh = ColumnDataSource(data = {'LBT':LBT,'SFH':SFH, 'z':zs })
    
    sfh = figure(plot_width = 900, plot_height = 350, x_axis_label ='Lookback Time (Gyr)',
               y_axis_label = 'SFR (M/yr)')
    for i in range(90):
        sfh.line(SDB.LBT.values, SDB['{}_x_{}'.format(gid, i)].values, color = '#532436', alpha=.075)

    r1 = sfh.line(source = src_sfh, x = 'LBT', y='SFH', color = '#C1253C', line_width = 2)
    sfh.line(SDB.LBT,SDB['{}_16'.format(gid)], color ='black', line_width = 2)
    sfh.line(SDB.LBT,SDB['{}_84'.format(gid)], color ='black', line_width = 2)
    sfh.line([t50, t50], [interp1d(SDB.LBT,SDB['{}_16'.format(gid)])(t50), 
             interp1d(SDB.LBT,SDB['{}_84'.format(gid)])(t50)],line_width=2.4, color = 'black')
    sfh.line([t50, t50], [interp1d(SDB.LBT,SDB['{}_16'.format(gid)])(t50), 
             interp1d(SDB.LBT,SDB['{}_84'.format(gid)])(t50)],line_width=2, color = '#ED2D39')

    band = Band(base='x', lower='top', upper='bottom', source=source, level='underlay',
                fill_color = '#4E7577', fill_alpha=0.7, line_width=1, line_color='black')
    sfh.add_layout(band)
    sfh.add_tools(HoverTool(tooltips = [('Lookback time', '@LBT'), 
                                        ('SFH', '@SFH'), ('z', '@z')], renderers = [r1]))
    sfh.xaxis.axis_label_text_font_size = "20pt"
    sfh.yaxis.axis_label_text_font_size = "20pt"
    sfh.xaxis.major_label_text_font_size = "15pt"
    sfh.yaxis.major_label_text_font_size = "15pt"
    
    return sfh
def plot_pr_curve(pr_curve, auprc, model_name=None, file_name=None):
    if model_name is None:
        model_name = ""
    else:
        model_name += ": "

    p = figure(
        plot_width=600,
        plot_height=400,
        title=f"{model_name}Precision - Recall Curve",
        x_axis_label="Recall",
        y_axis_label="Precision",
    )

    source = dict(zip(["recall", "precision", "thr"], pr_curve))
    source["lower_band"] = np.repeat(0.0, source["recall"].shape[0])
    source = ColumnDataSource(source)

    _ = p.line(
        x="recall",
        y="precision",
        color="coral",
        line_width=1.0,
        legend_label=f"AUPRC: {auprc:.2%}",
        source=source,
    )
    band = Band(
        base="recall",
        lower="lower_band",
        upper="precision",
        level="underlay",
        fill_color="coral",
        fill_alpha=0.2,
        source=source,
    )
    p.add_layout(band)

    p.xgrid.grid_line_color = None
    p.xaxis.formatter = NumeralTickFormatter(format="0%")
    p.yaxis.formatter = NumeralTickFormatter(format="0%")
    p.legend.label_text_font_size = "8pt"
    p.legend.location = "top_right"
    p.title.align = "center"
    p.title.text_font_size = "12pt"

    show(p)

    if file_name is not None:
        p.output_backend = "svg"
        _ = export_svgs(p, filename=file_name)
def add_band(x, y, minimum, maximum, plot, alpha, color='lightsteelblue'):
    dftemp = pd.DataFrame(data=dict(x=x, y=y[0])).sort_values(by="x")
    dftemp['upper'] = minimum
    dftemp['lower'] = maximum
    source = ColumnDataSource(dftemp.reset_index())

    band = Band(base='x',
                lower='lower',
                upper='upper',
                source=source,
                level='underlay',
                fill_alpha=alpha,
                line_width=0.3,
                line_color='black',
                fill_color=color,
                line_dash='dashed')
    plot.add_layout(band)
Example #17
0
def create_stock_plot(ti, d1, d2):
    #getting stock data from ticker input
    data = q.get_table(
        'WIKI/PRICES',
        paginate=True,
        ticker=ti,
        date={
            'gte': d2,
            'lte': d1
        },
        qopts={"columns": ["ticker", "date", "close", "low", "high"]})
    #creating dictionary database to plot
    df = pd.DataFrame(data=dict(
        x=data.date, y=data.close, low=data.low, high=data.high)).sort_values(
            by="x")
    source = ColumnDataSource(df.reset_index())

    t1 = "Closing Cost with High/Low Reach Band for Stock: %s" % (ti)
    t2 = "From %s to %s" % (d2, d1)
    #creating figure
    p = figure(title=t1,
               plot_width=700,
               plot_height=500,
               x_axis_type="datetime")
    p.y_range = Range1d(data.low[data.low.idxmin()] - 2,
                        data.high[data.high.idxmax()] + 2)
    p.xaxis.axis_label = 'Days'
    p.yaxis.axis_label = 'Value in USD'

    p.line('x', 'y', color='firebrick', source=source, line_width=2)

    band = Band(base='x',
                lower='low',
                upper='high',
                level='underlay',
                source=source,
                fill_alpha=0.5,
                line_width=1,
                line_color='black',
                fill_color='grey')

    p.add_layout(band)
    p.add_layout(Title(text=t2, align="center"), "below")

    return p
Example #18
0
    def init(self, doc):
        #Source must only be modified through a stream
        self.source = ColumnDataSource(data=self.data)

        #Enable theming
        theme = Theme('forge/blade/core/market/theme.yaml')
        doc.theme = theme
        self.doc = doc

        fig = figure(
           plot_width=600,
           plot_height=400,
           tools='pan,xwheel_zoom,box_zoom,save,reset',
           title='Neural MMO: Market Data',
           x_axis_label=self.x,
           y_axis_label=self.ylabel)

        #Initialize plots
        for i, key in enumerate(self.keys):
            fig.line(
                source=self.source,
                x=self.x,
                y=key,
                color=self.colors[i],
                line_width=LINE_WIDTH,
                legend_label=key)

            band = Band(
               source=self.source,
               base=self.x,
               lower=key+'lower',
               upper=key+'upper',
               level='underlay',
               line_color=self.colors[i],
               line_width=1,
               line_alpha=0.2,
               fill_color=self.colors[i],
               fill_alpha=0.2)
            fig.add_layout(band) 

        #Set root
        self.doc.add_root(fig)
        self.fig = fig
Example #19
0
def make_control_chart(dictionary, id):
    source = AjaxDataSource(data_url=request.url_root + 'control-chart/' + id +
                            "/",
                            polling_interval=1000,
                            mode='replace')
    source.data = dictionary

    keys = [
        key for key in dictionary
        if not (key.endswith("_lower") or (key.endswith("_upper")))
    ]
    figures = []
    for key in keys:
        if key == "time_stamp": continue
        plot = figure(plot_height=300,
                      sizing_mode='scale_width',
                      x_axis_type="datetime")
        band = Band(
            base="time_stamp",
            lower=key + '_lower',
            upper=key + '_upper',
            source=source,
            level='underlay',
            fill_alpha=0.4,
            line_width=1,
            fill_color='#55FF88',
            line_color='red',
            line_dash='dashed',
        )
        plot.add_layout(band)
        plot.line('time_stamp', key, source=source, line_width=4)
        plot.circle('time_stamp',
                    key,
                    source=source,
                    line_width=4,
                    color="red")

        figures.append(plot)

    script, div = components(column(figures))

    return script, div
    def st_plot_wind_pressure(self):
        """
        Plot wind pressure along the sign face.
        The value may change for 45 degrees and a large aspect ratio.
        """
        #Set up plot
        plot = Plot()

        #Graph of Drag Factors along sign
        x = np.linspace(0, self.sign_w, num=50)
        if self.wind.loadcase is Cases.FAT:
            y = [
                0.5 * 1.2 * self.wind.V_sit_beta.value**2 * self.C_dyn / 1000 *
                self.C_fig for ix in x
            ]
        else:
            y = [
                0.5 * 1.2 * self.wind.V_sit_beta.value**2 *
                self.C_dyn * self.K_p / 1000 * self.C_pn_func(
                    self.sign_w, self.sign_h, self.wind.Wind_mult.height, ix)
                for ix in x
            ]
        source = ColumnDataSource(dict(x=x, y=y))
        drag_factor = Line(x='x', y='y', line_color="#f46d43", line_width=3)
        plot.add_glyph(source, drag_factor)

        #Fille area under line
        fill_under = Band(base='x',
                          upper='y',
                          source=source,
                          level='underlay',
                          fill_color='#55FF88')
        plot.add_layout(fill_under)

        #Plot setup
        plot.add_layout(LinearAxis(), 'below')
        plot.add_layout(LinearAxis(), 'left')
        plot.xaxis.axis_label = "Distance along sign (m)"
        plot.yaxis.axis_label = "Wind Pressure (kPa)"
        plot.y_range = Range1d(0, max(y) * 1.3)

        return plot
    def draw_prediction_band(region, conf_level, **kwargs):
        plot_params = {'line_alpha': 0, 'fill_alpha': 0.4}

        plot_params.update(kwargs)

        L, x0, k, L_std, x0_std, k_std = params_CDS.data[region]
        xs = np.arange(lines_CDS.data['date'].size)
        offset = get_offset_from_start_date(region)
        bands_CDS.data[f'{region}_lower'], bands_CDS.data[
            f'{region}_upper'] = (logistic_function(
                xs, L - L_std * z_star(conf_level), x0 + offset, k),
                                  logistic_function(
                                      xs, L + L_std * z_star(conf_level),
                                      x0 + offset, k))

        bands[region] = Band(base='date',
                             lower=f'{region}_lower',
                             upper=f'{region}_upper',
                             source=bands_CDS,
                             level='underlay',
                             **plot_params)
        plot.add_layout(bands[region])
Example #22
0
def plot_hr_profile(df_ts, x='s', y='BPM'):
    p = figure(
        width=450,
        height=325,
        title=f'Workout heart rate profile',
        x_axis_label='Time (seconds)',
        y_axis_label='BPM',
        toolbar_location="above",
        tools='box_zoom,undo,redo,reset',
        tooltips=[
            ('Time', '@Time'),
            ('BPM', '@BPM'),
        ]
    )

    cds = ColumnDataSource(df_ts)
    p.line(x, y, source=cds, color="black", alpha=0)

    band = Band(base='s', upper=y, source=cds, level='underlay',
                fill_alpha=0.90, fill_color='#ab383a') #e73360
    p.add_layout(band)
    return p, cds
Example #23
0
def plot_cs_prof(alg, instr, filename):
    def update_triangle(source):
        return CustomJS(args=dict(source=source, xr=p.x_range),
                        code="""
        var data = source.data;
        var x = data["size"]
        var range = data["range"]
        var cond = range[0] / (xr.end - xr.start)
        if (Math.abs(cond - 1) > 0.001)
            for (var i = 0; i < x.length; i++) {
                x[i] = x[i] * cond;
                range[i] = xr.end - xr.start
            }
        source.change.emit();
        """)

    timeframe = instr.timeframe
    close_df = pd.DataFrame(columns=[
        'time', 'close_price', 'open_price_oncl', 'close_side', 'last_indic',
        'profit'
    ])
    open_df = pd.DataFrame(columns=[
        'time', 'open_price', 'close_price_onop', 'open_side', 'first_indic',
        'profit'
    ])

    for pos in alg.positions:
        pos_trades = pos.trades
        for j in range(len(pos_trades)):
            if pos.closed:
                if j < len(pos_trades) - 1:
                    close_df = close_df.append(
                        pd.DataFrame([[
                            pos_trades[j].close_time,
                            pos_trades[j].close_price,
                            pos_trades[j].open_price, pos_trades[j].side, 0, 0
                        ]],
                                     columns=[
                                         'time', 'close_price',
                                         'open_price_oncl', 'close_side',
                                         'last_indic', 'profit'
                                     ]))
                elif pos_trades[j].close_time > 0:
                    close_df = close_df.append(
                        pd.DataFrame([[
                            pos_trades[j].close_time,
                            pos_trades[j].close_price,
                            pos_trades[j].open_price, pos_trades[j].side, 1,
                            pos.profit
                        ]],
                                     columns=[
                                         'time', 'close_price',
                                         'open_price_oncl', 'close_side',
                                         'last_indic', 'profit'
                                     ]))
            if j > 0:
                open_df = open_df.append(
                    pd.DataFrame([[
                        pos_trades[j].open_time, pos_trades[j].open_price,
                        pos_trades[j].close_price, pos_trades[j].side, 0,
                        pos.profit
                    ]],
                                 columns=[
                                     'time', 'open_price', 'close_price_onop',
                                     'open_side', 'first_indic', 'profit'
                                 ]))
            else:
                open_df = open_df.append(pd.DataFrame([[
                    pos_trades[j].open_time, pos_trades[j].open_price,
                    pos_trades[j].close_price, pos_trades[j].side, 1,
                    pos.profit
                ]],
                                                      columns=[
                                                          'time', 'open_price',
                                                          'close_price_onop',
                                                          'open_side',
                                                          'first_indic',
                                                          'profit'
                                                      ]),
                                         ignore_index=True)

    df = pd.DataFrame(instr.candles)

    opendf_len = len(open_df)
    closedf_len = len(close_df)

    df['size'] = 12.0
    close_df['size'] = 12.0
    open_df['size'] = 12.0
    df["date"] = pd.to_datetime(df["time"].astype(str),
                                format='%Y%m%d%H%M%S%f')
    timedelta = df['date'][len(df) -
                           1] - df['date'][len(df) -
                                           1].floor(str(timeframe) + 'T')

    df = df.drop(['time'], axis=1)

    close_df["date"] = pd.to_datetime(close_df["time"].astype(str),
                                      format='%Y%m%d%H%M%S%f')
    close_df = close_df.drop(['time'], axis=1)
    open_df["date"] = pd.to_datetime(open_df["time"].astype(str),
                                     format='%Y%m%d%H%M%S%f')
    open_df = open_df.drop(['time'], axis=1)
    df = df.sort_values(by=['date'])
    close_df = close_df.sort_values(by=['date'])
    open_df = open_df.sort_values(by=['date'])

    df = df.reset_index()
    df['index'] = df.index
    close_df = close_df.reset_index()
    open_df = open_df.reset_index()
    df['index'] = df['index'].astype(np.float64)
    close_df['index'] = df['index'].astype(np.float64)
    open_df['index'] = df['index'].astype(np.float64)

    close_df = reindex_by_df(close_df, df, timeframe)
    open_df = reindex_by_df(open_df, df, timeframe)
    w = (0.5)

    output_file(filename, title="Graphs")
    TOOLS = "pan,wheel_zoom,reset,save"

    inc = df['close'] > df['open']
    dec = ~inc

    ind_close = close_df["last_indic"] == 1
    ind_close_subseq = close_df["last_indic"] == 0
    ind_close_pos = close_df['close_side'] == -1

    ind_open_subseq = open_df["first_indic"] == 0
    ind_open = open_df["first_indic"] == 1
    ind_open_pos = open_df['open_side'] == -1

    max_range = (df['high'] - df['low']).max()

    range_constant = 31 if len(df) - 31 > 0 else len(df)
    min_low_range = df['low'][:range_constant].min()

    max_high_range = df['high'][:range_constant].max()
    p = figure(title="Candlestick chart with timeframe = " + str(timeframe) +
               " munutes",
               x_axis_type="linear",
               tools=TOOLS,
               plot_width=1000,
               toolbar_location="left",
               x_range=(-1.5, 30),
               y_range=(min_low_range - max_range / 2,
                        max_high_range + max_range / 2))

    df['range'] = p.x_range.end - p.x_range.start
    close_df['range'] = p.x_range.end - p.x_range.start
    open_df['range'] = p.x_range.end - p.x_range.start
    p.segment(df['index'], df['high'], df['index'], df['low'], color="black")
    min_diff = np.fabs(df['close'] - df['open'])
    min_diff = min_diff[min_diff > 0].min()
    prec = "0"
    for i in range(0, 16):
        if min_diff * 10**i >= 1:
            prec = prec * i
            break

    df['close_eq'] = df['close'] + min_diff
    df.loc[df['close'] + min_diff > df['high'],
           'close_eq'] = df['close'] - min_diff
    ind_eq = df['close'] == df['open']
    df['index'] = df.index
    mysource1 = ColumnDataSource(df[inc])
    mysource2 = ColumnDataSource(df[dec])
    mysource3 = ColumnDataSource(df[ind_eq])
    bars_1 = p.vbar(source=mysource1,
                    x="index",
                    width=w,
                    bottom="open",
                    top="close",
                    fill_color="honeydew",
                    line_color="black",
                    line_width=1)
    bars_2 = p.vbar(source=mysource2,
                    x="index",
                    width=w,
                    bottom="close",
                    top="open",
                    fill_color="deepskyblue",
                    line_color="black",
                    line_width=1)
    bars_3 = p.vbar(source=mysource3,
                    x="index",
                    width=w,
                    bottom="close_eq",
                    top="open",
                    fill_color="white",
                    line_color="black",
                    line_width=1,
                    fill_alpha=0.0)
    hover = HoverTool(renderers=[bars_1, bars_2, bars_3],
                      tooltips=[('high', '@high{0.' + str(prec) + '}'),
                                ('low', '@low{0.' + str(prec) + '}'),
                                ('open', '@open{0.' + str(prec) + '}'),
                                ('close', '@close{0.' + str(prec) + '}'),
                                ('volume', '@vol{0.0}'),
                                ('date', "@date{%Y-%m-%d %H:%M:%S}")],
                      formatters={"date": "datetime"})
    p.add_tools(hover)
    p.xaxis.major_label_overrides = {
        i: date.strftime('%Y-%m-%d %H:%M:%S')
        for i, date in enumerate(df["date"])
    }
    if (opendf_len > 0):
        open_df['time'] = open_df['date'].dt.floor(str(timeframe) +
                                                   'T') + timedelta
        source1 = ColumnDataSource(open_df[ind_open
                                           & (open_df['open_side'] == 1)])
        source2 = ColumnDataSource(open_df[ind_open
                                           & (open_df['open_side'] == -1)])
        source5 = ColumnDataSource(open_df[ind_open_subseq
                                           & (open_df['open_side'] == 1)])
        source6 = ColumnDataSource(open_df[ind_open_subseq
                                           & (open_df['open_side'] == -1)])
        tr_1 = p.triangle(x="index",
                          y="open_price",
                          size="size",
                          fill_alpha=0.7,
                          source=source1,
                          fill_color="green")
        inv_tr_1 = p.inverted_triangle(x="index",
                                       y="open_price",
                                       size="size",
                                       fill_alpha=0.7,
                                       source=source2,
                                       fill_color="green")
        tr_3 = p.triangle(x="index",
                          y="open_price",
                          size="size",
                          fill_alpha=0.7,
                          source=source5,
                          fill_color="purple")
        inv_tr_3 = p.inverted_triangle(x="index",
                                       y="open_price",
                                       size="size",
                                       fill_alpha=0.7,
                                       source=source6,
                                       fill_color="purple")

        p.x_range.js_on_change('start', update_triangle(source1))
        p.x_range.js_on_change('start', update_triangle(source2))
        p.x_range.js_on_change('start', update_triangle(source5))
        p.x_range.js_on_change('start', update_triangle(source6))

        hover1 = HoverTool(renderers=[tr_1, inv_tr_1, tr_3, inv_tr_3],
                           tooltips=[
                               ('open_price',
                                '@open_price{0.' + str(prec) + '}'),
                               ('close_price_onop',
                                '@close_price_onop{0.' + str(prec) + '}'),
                               ('date', "@date{%Y-%m-%d %H:%M:%S}")
                           ],
                           formatters={"date": "datetime"})
        p.add_tools(hover1)

    if (closedf_len > 0):
        close_df['time'] = close_df['date'].dt.floor(str(timeframe) +
                                                     'T') + timedelta

        source3 = ColumnDataSource(close_df[ind_close
                                            & (close_df['close_side'] == 1)])
        source4 = ColumnDataSource(close_df[ind_close
                                            & (close_df['close_side'] == -1)])
        source7 = ColumnDataSource(close_df[ind_close_subseq
                                            & (close_df['close_side'] == 1)])
        source8 = ColumnDataSource(close_df[ind_close_subseq
                                            & (close_df['close_side'] == -1)])

        tr_2 = p.inverted_triangle(x="index",
                                   y="close_price",
                                   size="size",
                                   fill_alpha=0.7,
                                   source=source3,
                                   fill_color="yellow")
        inv_tr_2 = p.triangle(x="index",
                              y="close_price",
                              size="size",
                              fill_alpha=0.7,
                              source=source4,
                              fill_color="yellow")
        tr_4 = p.inverted_triangle(x="index",
                                   y="close_price",
                                   size="size",
                                   fill_alpha=0.7,
                                   source=source7,
                                   fill_color="brown")
        inv_tr_4 = p.triangle(x="index",
                              y="close_price",
                              size="size",
                              fill_alpha=0.7,
                              source=source8,
                              fill_color="brown")

        p.x_range.js_on_change('start', update_triangle(source3))
        p.x_range.js_on_change('start', update_triangle(source4))
        p.x_range.js_on_change('start', update_triangle(source7))
        p.x_range.js_on_change('start', update_triangle(source8))

        hover2 = HoverTool(renderers=[tr_2, inv_tr_2, tr_4, inv_tr_4],
                           tooltips=[('close_price',
                                      '@close_price{0.' + str(prec) + '}'),
                                     ('open_price_oncl',
                                      '@open_price_oncl{0.' + str(prec) + '}'),
                                     ('date', "@date{%Y-%m-%d %H:%M:%S}")],
                           formatters={"date": "datetime"})
        p.add_tools(hover2)

    p.yaxis.axis_label = 'Price'
    p.xaxis.major_label_orientation = 3.14 / 4
    p.grid.grid_line_alpha = 0.5
    point_attributes = ['x', 'y', 'sx', 'sy']
    wheel_attributes = point_attributes + ['delta']

    close_df = close_df[close_df['last_indic'] == 1]
    close_df.loc[np.isnan(close_df['profit']), 'profit'] = 0.0
    prof = close_df['profit'].iloc[-1]
    if (open_df['date'].iloc[-1] > close_df['date'].iloc[-1]):
        prof = open_df['profit'].iloc[-1]

    first_el = df.iloc[0]
    first_el = first_el.to_frame().T
    first_el['profit'] = 0.0
    last_el = df.iloc[-1]
    last_el = last_el.to_frame().T
    last_el['profit'] = prof
    last_el['date'] = last_el['date'] + dt.timedelta(minutes=timeframe)

    close_df = close_df.append(first_el, sort=True)
    close_df = close_df.append(last_el, sort=True)

    close_df = close_df.sort_values(by=['date'])
    close_df = close_df.reset_index()
    close_df['cumsum'] = close_df['profit'].cumsum(skipna=True)
    close_df['pos'] = 0.0

    close_df['pos'] = close_df.loc[close_df['cumsum'] > 0, 'cumsum']
    close_df.loc[np.isnan(close_df['pos']), 'pos'] = 0
    close_df['neg'] = 0.0
    close_df['neg'] = close_df.loc[close_df['cumsum'] < 0, 'cumsum']
    close_df.loc[np.isnan(close_df['neg']), 'neg'] = 0.0
    close_df['zeros'] = 0.0
    plot_prof = figure(
        title="Profit plot",
        x_axis_type="datetime",
        tools=TOOLS,
        plot_width=1000,
        toolbar_location="left",
        x_range=(df["date"].min(), close_df["date"].max()),
        y_range=(close_df['cumsum'].min() -
                 (close_df['cumsum'].max() - close_df['cumsum'].min()) * 0.1,
                 close_df['cumsum'].max() +
                 (close_df['cumsum'].max() - close_df['cumsum'].min()) * 0.1))

    date_mid = pd.DataFrame()
    close_df['date'] = (pd.DatetimeIndex(close_df['date']).astype(np.int64))

    curloc = np.sign(
        close_df['cumsum'].shift().fillna(0) * close_df['cumsum']) < 0

    date_mid['date'] = close_df['date'].shift(
    )[curloc] + close_df['cumsum'].shift()[curloc] * (
        close_df['date'][curloc] - close_df['date'].shift())[curloc] / (
            close_df['cumsum'].shift()[curloc] - close_df['cumsum'])[curloc]
    date_mid = date_mid[np.isfinite(date_mid['date'])]
    date_mid['date'] = pd.to_datetime(date_mid['date'])
    close_df['date'] = pd.to_datetime(close_df['date'])

    date_mid['cumsum'] = 0.0
    date_mid['pos'] = 0.0
    date_mid['neg'] = 0.0
    date_mid['zeros'] = 0.0

    close_df = close_df.drop(['level_0', 'index'], axis=1)
    close_d_no_mids = close_df
    close_df = pd.concat([close_df, date_mid], sort=True)
    close_df = close_df.sort_values(by=['date'])
    close_df = close_df.reset_index()
    close_d_no_mids = close_d_no_mids.sort_values(by=['date'])
    close_d_no_mids = close_d_no_mids.reset_index()
    close_d_no_mids = close_d_no_mids.drop(['index'], axis=1)
    close_df = close_df.drop(['index'], axis=1)

    source_no_mids = ColumnDataSource(close_d_no_mids)
    source = ColumnDataSource(close_df)

    band = Band(base='date',
                lower='zeros',
                upper='pos',
                source=source,
                fill_alpha=0.75,
                fill_color="green")
    plot_prof.add_layout(band)
    plot_prof.yaxis.axis_label = 'Profit'
    band = Band(base='date',
                lower='zeros',
                upper='neg',
                source=source,
                fill_alpha=0.75,
                fill_color="red")
    plot_prof.add_layout(band)
    profit_line = plot_prof.line(x='date',
                                 y='cumsum',
                                 source=source_no_mids,
                                 line_width=2)
    hover3 = HoverTool(renderers=[profit_line],
                       tooltips=[('date', '@date{%Y-%m-%d %H:%M:%S}'),
                                 ('profit', '@cumsum{0.' + str(prec) + '}')],
                       formatters={"date": "datetime"})
    plot_prof.add_tools(hover3)

    candlestick_y_axis = p.select(dict(type=Axis, layout="left"))[0]
    candlestick_y_axis.formatter.use_scientific = False
    prof_y_axis = plot_prof.select(dict(type=Axis, layout="left"))[0]
    prof_y_axis.formatter.use_scientific = False
    save(column(p, plot_prof), filename)
Example #24
0
    def forestplot(self, credible_interval, quartiles, linewidth, markersize,
                   ax, rope):
        """Draw forestplot for each plotter.

        Parameters
        ----------
        credible_interval : float
            How wide each line should be
        quartiles : bool
            Whether to mark quartiles
        linewidth : float
            Width of forestplot line
        markersize : float
            Size of marker in center of forestplot line
        ax : Axes
            Axes to draw on
        """
        if rope is None or isinstance(rope, dict):
            pass
        elif len(rope) == 2:
            cds = ColumnDataSource({
                "x":
                rope,
                "lower": [-2 * self.y_max(), -2 * self.y_max()],
                "upper": [self.y_max() * 2, self.y_max() * 2],
            })

            band = Band(
                base="x",
                lower="lower",
                upper="upper",
                fill_color=[
                    color for _, color in zip(
                        range(4),
                        cycle(plt.rcParams["axes.prop_cycle"].by_key()
                              ["color"]))
                ][2],
                line_alpha=0.5,
                source=cds,
            )

            ax.renderers.append(band)
        else:
            raise ValueError("Argument `rope` must be None, a dictionary like"
                             '{"var_name": {"rope": (lo, hi)}}, or an '
                             "iterable of length 2")
        # Quantiles to be calculated
        endpoint = 100 * (1 - credible_interval) / 2
        if quartiles:
            qlist = [endpoint, 25, 50, 75, 100 - endpoint]
        else:
            qlist = [endpoint, 50, 100 - endpoint]

        for plotter in self.plotters.values():
            for y, rope_var, values, color in plotter.treeplot(
                    qlist, credible_interval):
                if isinstance(rope, dict):
                    self.display_multiple_ropes(rope, ax, y, linewidth,
                                                rope_var)

                mid = len(values) // 2
                param_iter = zip(
                    np.linspace(2 * linewidth, linewidth, mid,
                                endpoint=True)[-1::-1], range(mid))
                for width, j in param_iter:
                    ax.line([values[j], values[-(j + 1)]], [y, y],
                            line_width=width,
                            line_color=color)
                ax.circle(
                    x=values[mid],
                    y=y,
                    size=markersize * 0.75,
                    fill_color=color,
                )
        _title = Title()
        _title.text = "{:.1%} Credible Interval".format(credible_interval)
        ax.title = _title

        return ax
Example #25
0
    def _bokeh_component_plot(self,
                              component: str,
                              plot_options: dict,
                              data_color: str = "darkblue",
                              core_axis=None):
        """ Define a plot for an individual component. """
        times, obs, err = (self.__dict__[component].times,
                           self.__dict__[component].observations,
                           self.__dict__[component].errors)
        source = ColumnDataSource(
            dict(times=times,
                 obs=obs,
                 err=err,
                 lower=obs - err,
                 upper=obs + err))

        if not core_axis:
            p = figure(title=component,
                       x_range=[times[0], times[-1]],
                       **plot_options)
        else:
            p = figure(title=component,
                       x_range=core_axis.x_range,
                       **plot_options)
        p.background_fill_color = "lightgrey"
        p.yaxis.axis_label = f"{component} (mm)"
        p.xaxis.axis_label = "Time stamp (UTC)"
        p.min_border_bottom = 0
        p.min_border_top = 0
        p_scatter = p.scatter(x="times",
                              y="obs",
                              source=source,
                              line_color=None,
                              color=data_color)
        p_band = Band(base="times",
                      lower="lower",
                      upper="upper",
                      source=source,
                      level="underlay",
                      fill_alpha=1.0,
                      line_width=1,
                      line_color=data_color)
        p.add_layout(p_band)

        datetick_formatter = DatetimeTickFormatter(
            days=["%Y/%m/%d"],
            months=["%Y/%m/%d"],
            hours=["%Y/%m/%dT%H:%M:%S"],
            minutes=["%Y/%m/%dT%H:%M:%S"],
            seconds=["%H:%M:%S"],
            hourmin=["%Y/%m/%dT%H:%M:%S"],
            minsec=["%H:%M:%S"])
        p.xaxis.formatter = datetick_formatter

        # Add picker
        picks = ColumnDataSource({"x": [], "y": [], 'color': []})
        renderer = p.scatter(x='x',
                             y='y',
                             source=picks,
                             color='color',
                             size=10)
        renderer_up = p.ray(x='x',
                            y='y',
                            source=picks,
                            color='color',
                            angle=90,
                            angle_units="deg",
                            length=0)
        renderer_down = p.ray(x='x',
                              y='y',
                              source=picks,
                              color='color',
                              angle=270,
                              angle_units="deg",
                              length=0)
        draw_tool = PointDrawTool(
            renderers=[renderer, renderer_up, renderer_down],
            empty_value="red",
            num_objects=2)
        p.add_tools(draw_tool)
        p.toolbar.active_tap = draw_tool

        tabledatetimeformatter = DateFormatter(format="%Y/%m/%d")
        columns = [
            TableColumn(field="x",
                        title="Date",
                        formatter=tabledatetimeformatter),
            TableColumn(field="y",
                        title="Offset (mm)",
                        formatter=NumberFormatter(format="0.00"))
        ]
        table = DataTable(source=picks,
                          columns=columns,
                          editable=True,
                          width=300)
        return p, table
Example #26
0
            y_range=y_range,
            toolbar_location=None)

source = ColumnDataSource(data=dict(
    x1=[1, 3, 5, 7, 9],
    lower1=[1, 2, 1, 2, 1],
    upper1=[2, 3, 2, 3, 2],
    x2=[200, 250, 350, 450, 550],
    lower2=[400, 300, 400, 300, 400],
    upper2=[500, 400, 500, 400, 500],
))

band1 = Band(base='x1',
             lower='lower1',
             upper='upper1',
             line_width=3,
             line_color='red',
             line_dash='dashed',
             source=source)
band2 = Band(base='x2',
             lower='lower2',
             upper='upper2',
             base_units='screen',
             lower_units='screen',
             upper_units='screen',
             dimension='width',
             line_width=3,
             fill_color='blue',
             line_color='green',
             source=source)
def bokeh_scatter(data, fig_dir, factor_name, threshold=0.05):
    plot_data = dict(
        x=data.index.tolist(),
        pval_adj=data['p.adjusted'].tolist(),
        neg_log10_pval_adj=data['neg_log_padj'].tolist(),
        R2=data['R2'].tolist(),
        upper=[data['neg_log_padj'].max() * 1.2] * len(data),
        lower=[-np.log10(threshold)] * len(data),
        n1=data['n1'].tolist(),
        n2=data['n2'].tolist(),
    )
    plots = []

    factors = pd.MultiIndex.get_level_values(data.index, 1).unique()
    palette = Category10[10] + Dark2[8] + Accent[8]
    index_cmap = factor_cmap('x',
                             palette=palette,
                             factors=sorted(factors),
                             start=1,
                             end=2)

    tooltips = [('R2', '@R2'), ('adjusted p-value', '@pval_adj'),
                ('#samples in {} 1'.format(factor_name), '@n1'),
                ('#samples in {} 2'.format(factor_name), '@n2')]

    titles = {
        'neg_log10_pval_adj': 'Permanova test: -log10[adjusted p-value]',
        'R2': 'Permanova test: R2 score'
    }

    for metric, title in titles.items():
        p = figure(title=title,
                   x_range=FactorRange(*plot_data['x']),
                   tooltips=tooltips)
        p.vbar(x='x',
               top=metric,
               width=0.9,
               source=plot_data,
               line_color="white",
               fill_color=index_cmap)

        if metric == 'neg_log10_pval_adj':
            p.line(
                list(range(len(data) + len(factors))),
                [-np.log10(threshold)] * (len(data) + len(factors)),
                line_color='grey',
                line_dash='dashed',
                line_width=1,
                line_alpha=0.5,
                legend_label="{:.0%} significance threshold".format(threshold))

            band = Band(base='x',
                        lower='lower',
                        upper='upper',
                        level='underlay',
                        source=ColumnDataSource(plot_data),
                        line_dash='dashed',
                        fill_alpha=0.5,
                        line_width=1,
                        line_color='black')
            p.add_layout(band)
            p.legend.background_fill_alpha = 0.0

        p.xaxis.major_label_orientation = "vertical"
        p.xaxis.axis_label_text_font_size = "10pt"
        plots.append(p)

    grid = gridplot(plots, ncols=1, plot_width=1500, plot_height=500)
    output_file(f"{fig_dir}/permanova_results_{factor_name}.html")
    save(grid)
Example #28
0
    def add_border(self, plot, projection="ortho", pts=1000):
        if projection == "ortho":
            xe = np.linspace(-1, 1, pts)
            ye = np.sqrt(1 - xe**2)
            res = self.npix_o
        else:
            xe = np.linspace(-2, 2, pts)
            ye = 0.5 * np.sqrt(4 - xe**2)
            res = self.npix_m
        d = 1 - 2 * np.sqrt(2) / res

        # Fill above
        source = ColumnDataSource(
            data=dict(x=d * xe, lower=d * ye, upper=np.ones_like(xe)))
        band = Band(
            base="x",
            lower="lower",
            upper="upper",
            level="overlay",
            fill_alpha=1,
            fill_color="white",
            line_width=0,
            source=source,
        )
        plot.add_layout(band)

        # Fill below
        source = ColumnDataSource(
            data=dict(x=d * xe, lower=-np.ones_like(xe), upper=-d * ye))
        band = Band(
            base="x",
            lower="lower",
            upper="upper",
            level="overlay",
            fill_alpha=1,
            fill_color="white",
            line_width=0,
            source=source,
        )
        plot.add_layout(band)

        # Fill right
        if projection == "ortho":
            source = ColumnDataSource(data=dict(
                x=[1 + 1.1 * (d - 1), 1.1],
                lower=[-1.0, -1.0],
                upper=[1.0, 1.0],
            ))
        else:
            source = ColumnDataSource(data=dict(
                x=[2 * (1 + 1.1 * (d - 1)), 2.1],
                lower=[-1.0, -1.0],
                upper=[1.0, 1.0],
            ))
        band = Band(
            base="x",
            lower="lower",
            upper="upper",
            level="overlay",
            fill_alpha=1.0,
            fill_color="white",
            line_width=0,
            source=source,
        )
        plot.add_layout(band)

        # Fill left
        if projection == "ortho":
            source = ColumnDataSource(data=dict(
                x=[-1.1, -(1 + 1.1 * (d - 1))],
                lower=[-1.0, -1.0],
                upper=[1.0, 1.0],
            ))
        else:
            source = ColumnDataSource(data=dict(
                x=[-2.1, -2 * (1 + 1.1 * (d - 1))],
                lower=[-1.0, -1.0],
                upper=[1.0, 1.0],
            ))
        band = Band(
            base="x",
            lower="lower",
            upper="upper",
            level="overlay",
            fill_alpha=1.0,
            fill_color="white",
            line_width=0,
            source=source,
        )
        plot.add_layout(band)

        # Plot contour
        plot.line(d * xe, d * ye, line_width=2, color="black", alpha=1)
        plot.line(d * xe, -d * ye, line_width=2, color="black", alpha=1)
Example #29
0
p_sx =  figure(plot_width=600, plot_height=450,
               tools='pan,wheel_zoom, box_zoom, box_select, crosshair, undo,redo,save,reset,help',
               tooltips=TOOLTIPS,
               title="Significanse Curve", x_axis_type='datetime',
               background_fill_color = "#282C44",
               background_fill_alpha = 1)       #p = <class 'bokeh.plotting.figure.Figure'>
p_sx.yaxis.minor_tick_in = 5


renderer_line = p_sx.line(  x='start_datetime_dt', y='sx_value', source=source_sx,
                            line_width=2, color='#08F7FE',
                            line_alpha=0.7,
                            selection_alpha=1,
                            nonselection_alpha=1,
)
band = Band(base='start_datetime_dt', lower=0, upper='sx_value', source=source_sx, level='underlay',
            fill_color='#08F7FE', fill_alpha=0.1, line_width=0, line_color='black')
p_sx.add_layout(band)
#*******************************************************************
renderer_circle = p_sx.circle(x='start_datetime_dt', y='sx_value',
                              source=source_sx, size = 7,
                              fill_color='#08F7FE', fill_alpha=0.3,
                              line_color='#08F7FE', line_width=2)

selected_circle = Circle(fill_alpha = 1, fill_color='#FE53BB')
nonselected_circle = Circle(fill_alpha=0.2, fill_color='#08F7FE', line_color="blue")
renderer_circle.selection_glyph = selected_circle
renderer_circle.nonselection_glyph = nonselected_circle
select_overlay = p_sx.select_one(BoxSelectTool).overlay
select_overlay.fill_color = "firebrick"
select_overlay.line_color = None
# ***********************************************:
Example #30
0
               tools='',
               background_fill_color="#fafafa",
               toolbar_location=None,
               y_axis_location="right",
               margin=(5, 5, 5, 5))
iqr_p.line(x='date',
           y='med',
           color='#53b497',
           legend_label='Median correl.',
           line_width=2,
           source=band_source)
band = Band(base='date',
            lower='q1',
            upper='q3',
            source=band_source,
            level='underlay',
            fill_color='#53b497',
            fill_alpha=0.2,
            line_width=1,
            line_color='#53b497',
            line_alpha=0.4)
iqr_p.add_layout(band)
iqr_p.xaxis.visible = False
iqr_p.legend.location = "top_left"
iqr_p.legend.border_line_width = 0
iqr_p.legend.border_line_color = None
iqr_p.legend.background_fill_color = None
iqr_p.legend.background_fill_alpha = 0.0
iqr_p.yaxis.minor_tick_line_color = None
iqr_p.grid.grid_line_alpha = 0.3
iqr_p.legend.label_text_font_size = '8pt'