Ejemplo n.º 1
0
def save_plot_to_file(traces, num_traces, outfile):
    """Save plot figure to file."""
    colors = itertools.cycle(palette)
    xrange = range(len(traces[0]))
    plot = figure(plot_width=800)
    plot.add_tools(tools.CrosshairTool())
    plot.add_tools(tools.HoverTool())
    for i in range(min(len(traces), num_traces)):
        plot.line(xrange, traces[i], line_color=next(colors))
    output_file(outfile)
    show(plot)
Ejemplo n.º 2
0
def make_plot(amount):

    # call function with desired amount
    mortgage = calculate_mortgage(float(amount))

    # convert the dataframe returned by calculate_mortgage() into a ColumnDataSource (to be used by Bokeh)
    mortgage_cds = convert_df_to_cds(mortgage)
    stacks = ['pay', 'capital', 'interest']
    colors_arr = ["#c9d9d3", "#718dbf", "#e84d60"]

    p = figure(title="Mortgage repayment over time",
               plot_width=600,
               plot_height=600,
               x_axis_label='x',
               y_axis_label='y')

    p.vbar_stack(stacks,
                 source=mortgage_cds,
                 x='year',
                 width=0.9,
                 fill_alpha=0.5,
                 color=colors_arr,
                 line_color='black')

    # refer to data with @ and
    # to graph properties, e.g. x and y, with $
    h = tools.HoverTool(tooltips=[(
        'Year: ',
        '@year'), ('Capital left to repay',
                   '@pay'), ('Repayment on interests',
                             '@interest'), ('Repayment on capital',
                                            '@capital')])

    # add tool to the graph
    p.add_tools(h)

    output_notebook()

    return p
# reg_plot.line(x=runs.freq, y=runs.power, source=source_2,
#               line_width=line_width,
#               color=colors[2],
#               legend='Cannibalism: {}'.format(np.round(param.cannib_2, 3)))

# reg_plot.line(x=runs.freq, y=runs.power, source=source_3,
#               line_width=line_width,
#               color=colors[3],
#               legend='Cannibalism: {}'.format(np.round(param.cannib_3, 3)))

reg_plot.line(x=runs.freq, y=runs.power, source=source_4,
              line_width=line_width,
              color=colors[4],
              legend='Cannibalism: {}'.format(np.round(param.cannib_4, 3)))

reg_hover = tools.HoverTool()
reg_hover.tooltips = [
    ('Frequency', '@freq'),
    ('Period', '@period'),
    ('Spectral Density', '@power'),
    ('Genotype', '@genotype'),
    ('Source', '@comb')
]
reg_plot.add_tools(reg_hover)


reg_plot.legend.location = "bottom_right"
reg_plot.legend.label_text_font_size = legend_font_size
reg_plot.title.text_font_size = title_font_size
reg_plot.yaxis.axis_line_width = axis_line_width
reg_plot.xaxis.axis_line_width = axis_line_width
Ejemplo n.º 4
0
    def periodogram_plotter(self, dataframes: dict,
                                  title:      str):
        """
        Create the bokeh plots for periodograms, mean and median

        Args:
            dataframes: the source data
            title:      title of data

        Returns:
            Array of bokeh plots
        """

        data_sources = self.periodogram_source(dataframes)
        plot_labels  = [mean, median]

        table_plots = {}
        for table_name in tables:
            table_title = table_name.split('_')[1]
            column_plots = {}
            for column_name in columns:
                column_title = column_name.split('_')[1]
                regular_plot = plt.figure()
                regular_plot.title.text = '{} Periodogram for {} genotype {}'.\
                    format(title, table_title, column_title)
                regular_plot.yaxis.axis_label = 'Power Spectral Density'
                regular_plot.xaxis.axis_label = 'Frequency'
                log_plot = plt.figure(y_axis_type='log')
                log_plot.title.text = '{} Log-Scale Periodogram for {} ' \
                                      'genotype {}'. \
                    format(title, table_title, column_title)
                log_plot.yaxis.axis_label = 'log(Power Spectral Density)'
                log_plot.xaxis.axis_label = 'Frequency'

                for index, label_name in enumerate(plot_labels):
                    source = data_sources[label_name][table_name][column_name]

                    regular_plot.line(x=freq, y=power, source=source,
                                      color=colors[index],
                                      legend=label_name)
                    log_plot.line(x=freq, y=power, source=source,
                                  color=colors[index],
                                  legend=label_name)

                regular_hover          = tools.HoverTool()
                regular_hover.tooltips = [
                    ('Frequency', '@freq'),
                    ('Period', '@period'),
                    ('Spectral Density', '@power'),
                    ('Genotype', '@genotype'),
                    ('Source', '@comb')
                ]
                regular_plot.add_tools(regular_hover)
                log_hover          = tools.HoverTool()
                log_hover.tooltips = [
                    ('Frequency', '@freq'),
                    ('Period', '@period'),
                    ('Spectral Density', '@power'),
                    ('Genotype', '@genotype'),
                    ('Source', '@comb')
                ]
                log_plot.add_tools(log_hover)

                column_plots[column_name] = [regular_plot, log_plot]
            table_plots[table_name] = column_plots

        return table_plots
this_plot.circle(
    source=source_female,
    x="total_bill",
    y="tip",
    color="darkorange",
    size=10,
    alpha=0.7,
    legend="Women",
)

# Set axis labels
this_plot.xaxis.axis_label = "Total Bill"
this_plot.yaxis.axis_label = "Tip Amount"

# Show information when hovering the mouse over datapoints
this_plot.add_tools(tools.HoverTool(tooltips=[("Day",
                                               "@day")]))  # @ chooses feature

# Hide all circles of a given category when clicked in legend
this_plot.legend.click_policy = "hide"

output_notebook()
show(this_plot)

# %% [markdown] {"slideshow": {"slide_type": "slide"}}
# # Pivot table plots

# %%
from pivottablejs import pivot_ui
pivot_ui(tips)

# %% [markdown] {"slideshow": {"slide_type": "slide"}}
def periodogram_plotter(periodogram_mean_source, periodogram_median_source,
                        life_stage_title: str):
    """
    Create a set of periodograms
    Args:
        periodogram_mean_source:   mean data periodogram
        periodogram_median_source: median data periodogram
        life_stage_title:          name for life stage

    Returns:
        a plot system to show
    """

    mean_plot = plt.figure()
    mean_plot.title.text = '{} Mean Periodogram'.format(life_stage_title)
    mean_plot.yaxis.axis_label = 'Power Spectral Density'
    mean_plot.xaxis.axis_label = 'Frequency'
    mean_plot.line(x='frequency', y='power',
                   source=periodogram_mean_source['genotype_resistant'],
                   color=colors[0], legend='Resistant')
    mean_plot.line(x='frequency', y='power',
                   source=periodogram_mean_source['genotype_heterozygous'],
                   color=colors[1], legend='Heterozygous')
    mean_plot.line(x='frequency', y='power',
                   source=periodogram_mean_source['genotype_susceptible'],
                   color=colors[2], legend='Susceptible')
    mean_hover = tools.HoverTool()
    mean_hover.tooltips = [
        ('Frequency',        '@frequency'),
        ('Period',           '@period'),
        ('Spectral Density', '@power'),
        ('Genotype',         '@genotype')
    ]
    mean_plot.add_tools(mean_hover)

    median_plot = plt.figure()
    median_plot.title.text = '{} Median Periodogram'.format(life_stage_title)
    median_plot.yaxis.axis_label = 'Power Spectral Density'
    median_plot.xaxis.axis_label = 'Frequency'
    median_plot.line(x='frequency', y='power',
                     source=periodogram_median_source['genotype_resistant'],
                     color=colors[0], legend='Resistant')
    median_plot.line(x='frequency', y='power',
                     source=periodogram_median_source['genotype_heterozygous'],
                     color=colors[1], legend='Heterozygous')
    median_plot.line(x='frequency', y='power',
                     source=periodogram_median_source['genotype_susceptible'],
                     color=colors[2], legend='Susceptible')
    median_hover = tools.HoverTool()
    median_hover.tooltips = [
        ('Frequency', '@frequency'),
        ('Period', '@period'),
        ('Spectral Density', '@power'),
        ('Genotype', '@genotype')
    ]
    median_plot.add_tools(median_hover)

    mean_log_plot = plt.figure(y_axis_type='log')
    mean_log_plot.title.text = '{} Mean Log-Scale Periodogram'.\
        format(life_stage_title)
    mean_log_plot.yaxis.axis_label = 'log(Power Spectral Density)'
    mean_log_plot.xaxis.axis_label = 'Frequency'
    mean_log_plot.line(x='frequency', y='power',
                       source=periodogram_mean_source['genotype_resistant'],
                       color=colors[0], legend='Resistant')
    mean_log_plot.line(x='frequency', y='power',
                       source=periodogram_mean_source['genotype_heterozygous'],
                       color=colors[1], legend='Heterozygous')
    mean_log_plot.line(x='frequency', y='power',
                       source=periodogram_mean_source['genotype_susceptible'],
                       color=colors[2], legend='Susceptible')
    mean_log_hover = tools.HoverTool()
    mean_log_hover.tooltips = [
        ('Frequency', '@frequency'),
        ('Period', '@period'),
        ('Spectral Density', '@power'),
        ('Genotype', '@genotype')
    ]
    mean_log_plot.add_tools(mean_log_hover)

    median_log_plot = plt.figure(y_axis_type='log')
    median_log_plot.title.text = '{} Median Log-Scale Periodogram'. \
        format(life_stage_title)
    median_log_plot.yaxis.axis_label = 'log(Power Spectral Density)'
    median_log_plot.xaxis.axis_label = 'Frequency'
    median_log_plot.line(x='frequency', y='power',
                         source=periodogram_median_source['genotype_resistant'],
                         color=colors[0], legend='Resistant')
    median_log_plot.line(x='frequency', y='power',
                         source=periodogram_median_source['genotype_heterozygous'],
                         color=colors[1], legend='Heterozygous')
    median_log_plot.line(x='frequency', y='power',
                         source=periodogram_median_source['genotype_susceptible'],
                         color=colors[2], legend='Susceptible')
    median_log_hover = tools.HoverTool()
    median_log_hover.tooltips = [
        ('Frequency', '@frequency'),
        ('Period', '@period'),
        ('Spectral Density', '@power'),
        ('Genotype', '@genotype')
    ]
    median_log_plot.add_tools(median_log_hover)

    return lay.gridplot([[mean_plot,     median_plot],
                         [mean_log_plot, median_log_plot]],
                        toolbar_location='left')
Ejemplo n.º 7
0
def create_figure(df_exploded, df_plots, wdg, cols, explode_val=None, explode_group=None):
    '''
    Create and return a figure based on the data in a dataframe and widget configuration.

    Args:
        df_exploded (pandas dataframe): Dataframe of just the data that will be plotted in this figure.
        df_plots (pandas dataframe): Dataframe of all plots data, used only for maintaining consistent series colors.
        wdg (ordered dict): Dictionary of bokeh model widgets.
        cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category.
        explode_val (string, optional): The value in the column designated by wdg['explode'] that applies to this figure.
        explode_group (string, optional): The value in the wdg['explode_group'] column that applies to this figure.

    Returns:
        p (bokeh.model.figure): A figure, with all glyphs added by the add_glyph() function.
    '''
    # If x_group has a value, create a combined column in the dataframe for x and x_group
    x_col = wdg['x'].value
    if wdg['x_group'].value != 'None':
        x_col = str(wdg['x_group'].value) + '_' + str(wdg['x'].value)
        df_exploded[x_col] = df_exploded[wdg['x_group'].value].map(str) + ' ' + df_exploded[wdg['x'].value].map(str)

    #Build x and y ranges and figure title
    kw = dict()

    #Set x and y ranges. When x is grouped, there is added complication of separating the groups
    xs = df_exploded[x_col].values.tolist()
    ys = df_exploded[wdg['y'].value].values.tolist()
    if wdg['x_group'].value != 'None':
        kw['x_range'] = []
        unique_groups = df_exploded[wdg['x_group'].value].unique().tolist()
        unique_xs = df_exploded[wdg['x'].value].unique().tolist()
        for i, ugr in enumerate(unique_groups):
            for uxs in unique_xs:
                kw['x_range'].append(str(ugr) + ' ' + str(uxs))
            #Between groups, add entries that consist of spaces. Increase number of spaces from
            #one break to the next so that each entry is unique
            kw['x_range'].append(' ' * (i + 1))
    elif wdg['x'].value in cols['discrete']:
        kw['x_range'] = sorted(set(xs))
    if wdg['y'].value in cols['discrete']:
        kw['y_range'] = sorted(set(ys))

    #Set figure title
    kw['title'] = wdg['plot_title'].value
    seperator = '' if kw['title'] == '' else ', '
    if explode_val is not None:
        if explode_group is not None:
            kw['title'] = kw['title'] + seperator + "%s = %s" % (wdg['explode_group'].value, str(explode_group))
        seperator = '' if kw['title'] == '' else ', '
        kw['title'] = kw['title'] + seperator + "%s = %s" % (wdg['explode'].value, str(explode_val))

    #Add figure tools
    hover = bmt.HoverTool(
            tooltips=[
                ("ser", "@ser_legend"),
                ("x", "@x_legend"),
                ("y", "@y_legend"),
            ]
    )
    TOOLS = [bmt.BoxZoomTool(), bmt.PanTool(), hover, bmt.ResetTool(), bmt.SaveTool()]

    #Create figure with the ranges, titles, and tools, and adjust formatting and labels
    p = bp.figure(plot_height=int(wdg['plot_height'].value), plot_width=int(wdg['plot_width'].value), tools=TOOLS, **kw)
    p.toolbar.active_drag = TOOLS[0]
    p.title.text_font_size = wdg['plot_title_size'].value + 'pt'
    p.xaxis.axis_label = wdg['x_title'].value
    p.yaxis.axis_label = wdg['y_title'].value
    p.xaxis.axis_label_text_font_size = wdg['x_title_size'].value + 'pt'
    p.yaxis.axis_label_text_font_size = wdg['y_title_size'].value + 'pt'
    p.xaxis.major_label_text_font_size = wdg['x_major_label_size'].value + 'pt'
    p.yaxis.major_label_text_font_size = wdg['y_major_label_size'].value + 'pt'
    p.xaxis.major_label_orientation = 'horizontal' if wdg['x_major_label_orientation'].value == '0' else math.radians(float(wdg['x_major_label_orientation'].value))
    if wdg['x'].value in cols['continuous']:
        if wdg['x_min'].value != '': p.x_range.start = float(wdg['x_min'].value)
        if wdg['x_max'].value != '': p.x_range.end = float(wdg['x_max'].value)
    if wdg['y'].value in cols['continuous']:
        if wdg['y_min'].value != '': p.y_range.start = float(wdg['y_min'].value)
        if wdg['y_max'].value != '': p.y_range.end = float(wdg['y_max'].value)

    #Add glyphs to figure
    c = C_NORM
    if wdg['series'].value == 'None':
        if wdg['y_agg'].value != 'None' and wdg['y'].value in cols['continuous']:
            xs = df_exploded[x_col].values.tolist()
            ys = df_exploded[wdg['y'].value].values.tolist()
        add_glyph(wdg, p, xs, ys, c)
    else:
        full_series = df_plots[wdg['series'].value].unique().tolist() #for colors only
        if wdg['chart_type'].value in STACKEDTYPES: #We are stacking the series
            xs_full = sorted(df_exploded[x_col].unique().tolist())
            y_bases_pos = [0]*len(xs_full)
            y_bases_neg = [0]*len(xs_full)
        for i, ser in enumerate(df_exploded[wdg['series'].value].unique().tolist()):
            c = COLORS[full_series.index(ser)]
            df_series = df_exploded[df_exploded[wdg['series'].value].isin([ser])]
            xs_ser = df_series[x_col].values.tolist()
            ys_ser = df_series[wdg['y'].value].values.tolist()
            if wdg['chart_type'].value not in STACKEDTYPES: #The series will not be stacked
                add_glyph(wdg, p, xs_ser, ys_ser, c, series=ser)
            else: #We are stacking the series
                ys_pos = [ys_ser[xs_ser.index(x)] if x in xs_ser and ys_ser[xs_ser.index(x)] > 0 else 0 for i, x in enumerate(xs_full)]
                ys_neg = [ys_ser[xs_ser.index(x)] if x in xs_ser and ys_ser[xs_ser.index(x)] < 0 else 0 for i, x in enumerate(xs_full)]
                ys_stacked_pos = [ys_pos[i] + y_bases_pos[i] for i in range(len(xs_full))]
                ys_stacked_neg = [ys_neg[i] + y_bases_neg[i] for i in range(len(xs_full))]
                add_glyph(wdg, p, xs_full, ys_stacked_pos, c, y_bases=y_bases_pos, series=ser)
                add_glyph(wdg, p, xs_full, ys_stacked_neg, c, y_bases=y_bases_neg, series=ser)
                y_bases_pos = ys_stacked_pos
                y_bases_neg = ys_stacked_neg
    return p
Ejemplo n.º 8
0
    def __init__(self,
                 source: Source,
                 train_data_source: Optional[ColumnDataSource] = None,
                 num_samples: int = 0,
                 plot_marker: bool = False,
                 xlabel: str = 'x',
                 ylabel: str = 'y',
                 **kargs: Any):
        # Number of samples currently added to the plot
        self._num_samples: int = 0
        self._sample_renderers: List[GlyphRenderer] = []

        if isinstance(source, dict):
            source = ColumnDataSource(data=source)

        x = source.data["x"]
        mu = source.data["mu"]
        cov_diag = np.diag(source.data["cov"])
        uncertainty = 1.96 * np.sqrt(cov_diag)

        assert (len(mu.shape) == 1)

        source.data["lower"] = mu - uncertainty
        source.data["upper"] = mu + uncertainty

        source.data["var"] = cov_diag

        # Get the appropriated minumum and maximum for the plot y range
        min_y, max_y = np.min(mu - uncertainty), np.max(mu + uncertainty)
        min_x, max_x = 1.02 * np.min(x), 1.02 * np.max(x)
        min_y, max_y = 1.05 * min_y, 1.05 * max_y

        # Note that we will add HoverTool later
        if "width" not in kargs:
            kargs["width"] = 900
        if "height" not in kargs:
            kargs["height"] = 400
        if "y_range" in kargs:
            fig = figure(x_range=(min_x, max_x), **kargs)
        else:
            fig = figure(x_range=(min_x, max_x),
                         y_range=(min_y, max_y),
                         **kargs)
        fig.xaxis.axis_label = xlabel
        fig.yaxis.axis_label = ylabel

        prediction_plot = fig.line("x",
                                   "mu",
                                   source=source,
                                   line_width=2,
                                   legend_label="Prediction Mean")
        if plot_marker:
            prediction_plot = fig.circle("x",
                                         "mu",
                                         source=source,
                                         legend_label="Prediction Mean")

        hover1 = tools.HoverTool()
        hover1.renderers = [prediction_plot]
        hover1.tooltips = [("x", "@x"), ("Mean", "@mu"),
                           ("Mean + 2σ", "@upper"), ("Mean - 2σ", "@lower"),
                           ("Var", "@var")]
        fig.add_tools(hover1)

        band = Band(base="x",
                    lower="lower",
                    upper="upper",
                    source=source,
                    level='image',
                    fill_color="#e0ffff",
                    fill_alpha=0.8)

        # Plot the training data
        if train_data_source is not None:
            cross_plot = fig.cross("x",
                                   "y",
                                   source=train_data_source,
                                   size=10,
                                   color="red",
                                   legend_label="Train")
            hover2 = tools.HoverTool()
            hover2.tooltips = [("Training Point", "(@x, @y)")]
            hover2.renderers = [cross_plot]
            fig.add_tools(hover2)

        fig.add_layout(band)
        fig.legend.click_policy = "hide"

        self._source: ColumnDataSource = source
        self._fig: Figure = fig

        if num_samples > 0:
            self.add_samples(num_samples)
Ejemplo n.º 9
0
def plot_gp(source: Source,
            train_data_source: Optional[ColumnDataSource] = None,
            samples: Optional[np.ndarray] = None,
            plot_marker: bool = False,
            xlabel: str = 'x',
            ylabel: str = 'y',
            dont_show: bool = False,
            **kargs: Any) -> Optional[Figure]:
    """
    Plot a Gaussian Process.

    Parameters
    ----------
    source : Source
        Either a bokeh ColumnDataSource of a dictionary containing at least the
        fields 'x', 'mu' and 'cov', where 'x' is a range of values,
        'mu' is the predicted average function response for the range of values
        in 'x', and `cov` is covariance matrix.
    train_data_source : ColumnDataSource, None
        Optional ColumnDataSource containing a 'x' and 'y' columns with
        training data
    samples : np.ndarray
        A 2D numpy array or an integer. In the first two cases each element is
        ploted by the 'x' values in `source`. If an int is passed, then a
        multivariate Gaussian distribution is generated using `mu` and `cov` in
        `source`. A maximum of four samples is possible.
    plot_marker : bool
        If predicted points should be marked with a circle or not.
    xlabel : str
        Label of the 'x' axis (default is "x").
    ylabel : str
        Label of the 'y' axis (default is "y").
    dont_show : bool
        If the plot should not be show and the figure should be returned
        instead. Default is False.
    kargs : dict
        The remaining arguments captured in `kargs` are passed to bokeh figure.
        Ex: width, height, title, etc.

    Returns
    -------
    figure or None
        Returns the bokeh figure if `dont_show` is True.
    """
    if isinstance(source, dict):
        source = ColumnDataSource(data=source)

    x: np.ndarray = source.data["x"]
    mu: np.ndarray = source.data["mu"]
    cov_diag: np.ndarray = np.diag(source.data["cov"])
    uncertainty: np.ndarray = 1.96 * np.sqrt(cov_diag)

    assert (len(mu.shape) == 1)

    source.data["lower"] = mu - uncertainty
    source.data["upper"] = mu + uncertainty

    source.data["var"] = cov_diag

    # Get the appropriated minumum and maximum for the plot y range
    min_y, max_y = np.min(mu - uncertainty), np.max(mu + uncertainty)
    min_x, max_x = 1.02 * np.min(x), 1.02 * np.max(x)

    if samples is not None:
        if isinstance(samples, int):
            cov = source.data["cov"]
            samples = np.random.multivariate_normal(mu, cov, samples)
        min_y, max_y = min(min_y, np.min(samples)), max(max_y, np.max(samples))
    min_y, max_y = 1.05 * min_y, 1.05 * max_y

    # Note that we will add HoverTool later
    if "width" not in kargs:
        kargs["width"] = 900
    if "height" not in kargs:
        kargs["height"] = 400
    if "y_range" in kargs:
        p = figure(x_range=(min_x, max_x), **kargs)
    else:
        p = figure(x_range=(min_x, max_x), y_range=(min_y, max_y), **kargs)
    p.xaxis.axis_label = xlabel
    p.yaxis.axis_label = ylabel

    prediction_plot = p.line("x",
                             "mu",
                             source=source,
                             line_width=2,
                             legend_label="Prediction Mean")
    if plot_marker:
        prediction_plot = p.circle("x",
                                   "mu",
                                   source=source,
                                   legend_label="Prediction Mean")

    hover1 = tools.HoverTool()
    hover1.renderers = [prediction_plot]
    hover1.tooltips = [("x", "@x"), ("Mean", "@mu"), ("Mean + 2σ", "@upper"),
                       ("Mean - 2σ", "@lower"), ("Var", "@var")]
    p.add_tools(hover1)

    band = Band(base="x",
                lower="lower",
                upper="upper",
                source=source,
                level='image',
                fill_color="#e0ffff",
                fill_alpha=0.8)
    if samples is not None:
        for i, sample in enumerate(samples):
            p.line(x,
                   sample,
                   color=palette[i],
                   legend_label=f"Sample {i}",
                   line_dash="dashed")

    # Plot the training data
    if train_data_source is not None:
        cross_plot = p.cross("x",
                             "y",
                             source=train_data_source,
                             size=10,
                             color="red",
                             legend_label="Train")
        hover2 = tools.HoverTool()
        hover2.tooltips = [("Training Point", "(@x, @y)")]
        hover2.renderers = [cross_plot]
        p.add_tools(hover2)

    p.add_layout(band)
    p.legend.click_policy = "hide"

    if dont_show:
        return p

    show(p)
    return None
Ejemplo n.º 10
0
    def _plot_periodogram(dataframe_low: hint.dataframe,
                          dataframe_high: hint.dataframe, title: str) -> dict:
        """
        Create a Bokeh plot of the periodogram dataframe
        Args:
            dataframe_low:  the dataframe low  survival
            dataframe_high: the dataframe high survival
            title:          the title for the plot

        Returns:
            a dictionary of Bokeh plots
        """

        source_low = mdl.ColumnDataSource(dataframe_low)
        source_high = mdl.ColumnDataSource(dataframe_high)

        base_title = 'Main period: Low: {} or High: {}'. \
            format(np.round(dataframe_low[runs.primary].iloc[0], 3),
                   np.round(dataframe_high[runs.primary].iloc[0], 3))

        reg_plot = plt.figure(plot_height=plot_height, plot_width=plot_width)
        reg_plot.title.text = base_title
        reg_plot.xaxis.axis_label = 'Frequency'
        reg_plot.yaxis.axis_label = 'Power Spectral Density'

        reg_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source_low,
                      line_width=line_width,
                      color=colors[0],
                      legend='Survival: {}'.format(
                          np.round(param.larva_prob_bt_low_ss, 3)))
        reg_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source_high,
                      line_width=line_width,
                      color=colors[1],
                      legend='Survival: {}'.format(
                          np.round(param.larva_prob_bt_high_ss, 3)))

        reg_hover = tools.HoverTool()
        reg_hover.tooltips = [('Frequency', '@freq'), ('Period', '@period'),
                              ('Spectral Density', '@power'),
                              ('Genotype', '@genotype'), ('Source', '@comb')]
        reg_plot.add_tools(reg_hover)

        reg_plot.legend.location = "top_right"

        reg_plot.legend.label_text_font_size = legend_font_size
        reg_plot.title.text_font_size = title_font_size
        reg_plot.yaxis.axis_line_width = axis_line_width
        reg_plot.xaxis.axis_line_width = axis_line_width
        reg_plot.yaxis.axis_label_text_font_size = axis_font_size
        reg_plot.xaxis.axis_label_text_font_size = axis_font_size
        reg_plot.yaxis.major_label_text_font_size = axis_tick_font_size
        reg_plot.xaxis.major_label_text_font_size = axis_tick_font_size
        reg_plot.ygrid.grid_line_width = grid_line_width
        reg_plot.xgrid.grid_line_width = grid_line_width

        log_plot = plt.figure(plot_height=plot_height,
                              plot_width=plot_width,
                              y_axis_type='log')
        log_plot.title.text = 'Log-scale {}'. \
            format(base_title)
        log_plot.xaxis.axis_label = 'Frequency'
        log_plot.yaxis.axis_label = 'log(Power Spectral Density)'

        log_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source_low,
                      line_width=line_width,
                      color=colors[0],
                      legend='Survival: {}'.format(
                          np.round(param.larva_prob_bt_low_ss, 3)))
        log_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source_high,
                      line_width=line_width,
                      color=colors[1],
                      legend='Survival: {}'.format(
                          np.round(param.larva_prob_bt_high_ss, 3)))

        log_hover = tools.HoverTool()
        log_hover.tooltips = [('Frequency', '@freq'), ('Period', '@period'),
                              ('Spectral Density', '@power'),
                              ('Genotype', '@genotype'), ('Source', '@comb')]
        log_plot.add_tools(log_hover)

        log_plot.legend.location = "top_right"

        log_plot.legend.label_text_font_size = legend_font_size
        log_plot.title.text_font_size = title_font_size
        log_plot.yaxis.axis_line_width = axis_line_width
        log_plot.xaxis.axis_line_width = axis_line_width
        log_plot.yaxis.axis_label_text_font_size = axis_font_size
        log_plot.xaxis.axis_label_text_font_size = axis_font_size
        log_plot.yaxis.major_label_text_font_size = axis_tick_font_size
        log_plot.xaxis.major_label_text_font_size = axis_tick_font_size
        log_plot.ygrid.grid_line_width = grid_line_width
        log_plot.xgrid.grid_line_width = grid_line_width

        return {runs.reg: reg_plot, runs.log: log_plot}
Ejemplo n.º 11
0
    def _plot_periodogram(dataframe: hint.dataframe, title: str) -> dict:
        """
        Create a Bokeh plot of the periodogram dataframe
        Args:
            dataframe: the dataframe to use
            title:     the title for the plot

        Returns:
            a dictionary of Bokeh plots
        """

        source = mdl.ColumnDataSource(dataframe)

        base_title = 'Main period: {}'.\
            format(np.round(dataframe[runs.primary].iloc[0], 3))

        reg_plot = plt.figure(plot_height=plot_height, plot_width=plot_width)
        reg_plot.title.text = base_title
        reg_plot.xaxis.axis_label = 'Frequency'
        reg_plot.yaxis.axis_label = 'Power Spectral Density'

        reg_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source,
                      line_width=line_width,
                      color=colors[0])

        reg_hover = tools.HoverTool()
        reg_hover.tooltips = [('Frequency', '@freq'), ('Period', '@period'),
                              ('Spectral Density', '@power'),
                              ('Genotype', '@genotype'), ('Source', '@comb')]
        reg_plot.add_tools(reg_hover)

        reg_plot.title.text_font_size = title_font_size
        reg_plot.yaxis.axis_line_width = axis_line_width
        reg_plot.xaxis.axis_line_width = axis_line_width
        reg_plot.yaxis.axis_label_text_font_size = axis_font_size
        reg_plot.xaxis.axis_label_text_font_size = axis_font_size
        reg_plot.yaxis.major_label_text_font_size = axis_tick_font_size
        reg_plot.xaxis.major_label_text_font_size = axis_tick_font_size
        reg_plot.ygrid.grid_line_width = grid_line_width
        reg_plot.xgrid.grid_line_width = grid_line_width

        log_plot = plt.figure(plot_height=plot_height,
                              plot_width=plot_width,
                              y_axis_type='log')
        log_plot.title.text = 'Log-scale {}'.\
            format(base_title)
        log_plot.xaxis.axis_label = 'Frequency'
        log_plot.yaxis.axis_label = 'log(Power Spectral Density)'

        log_plot.line(x=runs.freq,
                      y=runs.power,
                      source=source,
                      line_width=line_width,
                      color=colors[0])

        log_hover = tools.HoverTool()
        log_hover.tooltips = [('Frequency', '@freq'), ('Period', '@period'),
                              ('Spectral Density', '@power'),
                              ('Genotype', '@genotype'), ('Source', '@comb')]
        log_plot.add_tools(log_hover)

        log_plot.title.text_font_size = title_font_size
        log_plot.yaxis.axis_line_width = axis_line_width
        log_plot.xaxis.axis_line_width = axis_line_width
        log_plot.yaxis.axis_label_text_font_size = axis_font_size
        log_plot.xaxis.axis_label_text_font_size = axis_font_size
        log_plot.yaxis.major_label_text_font_size = axis_tick_font_size
        log_plot.xaxis.major_label_text_font_size = axis_tick_font_size
        log_plot.ygrid.grid_line_width = grid_line_width
        log_plot.xgrid.grid_line_width = grid_line_width

        return {runs.reg: reg_plot, runs.log: log_plot}
Ejemplo n.º 12
0
    def add_tools(self,
                  chart: Chart,
                  df: DataFrame,
                  center_name: str,
                  absolute: bool,
                  ordinal: bool,
                  use_adjusted_intervals: bool):
        self.add_ci_to_chart_datasources(chart,
                                         df,
                                         center_name,
                                         ordinal,
                                         use_adjusted_intervals)
        LOWER, UPPER = ((ADJUSTED_LOWER, ADJUSTED_UPPER)
                        if use_adjusted_intervals
                        else (CI_LOWER, CI_UPPER))

        if len(chart.figure.legend) > 0:
            chart.figure.legend.click_policy = "hide"
        axis_format, y_min, y_max = axis_format_precision(
            numbers=(df[LOWER]
                     .append(df[center_name])
                     .append(df[UPPER])
                     .append(df[NULL_HYPOTHESIS]
                             if NULL_HYPOTHESIS in df.columns
                             else None)
                     ),
            absolute=absolute,
            extra_zeros=2)
        ordinal_tool_tip = (
             [] if not ordinal else
             [(self._ordinal_group_column, f"@{self._ordinal_group_column}")]
         )
        p_value_tool_tip = (
          ([("p-value", "@p_value{0.0000}")] +
           ([("adjusted p-value", "@adjusted_p{0.0000}")]
            if len(df) > 1 else []))
          if center_name == DIFFERENCE else [])
        nim_tool_tip = (
            [("null hypothesis", f"@null_hyp{{{axis_format}}}")]
            if NULL_HYPOTHESIS in df.columns else [])
        tooltips = (
            [("group", "@color")] +
            ordinal_tool_tip +
            [(f"{center_name}", f"@{center_name}{{{axis_format}}}")] +
            [(("adjusted " if use_adjusted_intervals else "") +
              "confidence interval",
              f"(@{{{LOWER}}}{{{axis_format}}},"
              f" @{{{UPPER}}}{{{axis_format}}})")] +
            p_value_tool_tip +
            nim_tool_tip
        )
        lines_with_hover = [] if ordinal else ['center', 'nim']
        hover = tools.HoverTool(tooltips=tooltips, names=lines_with_hover)
        box_zoom = tools.BoxZoomTool()

        chart.figure.add_tools(hover,
                               tools.ZoomInTool(),
                               tools.ZoomOutTool(),
                               box_zoom,
                               tools.PanTool(),
                               tools.ResetTool())
        chart.figure.toolbar.active_drag = box_zoom