Exemplo n.º 1
0
def get(n,b):

    r = []
    
    now = datetime.datetime.now()
    t = str(now.strftime("%Y,%m,%d"))

    y = int(t[0:4])
    m = int(t[6])
    d = int(t[8:10]) 

    start=datetime.datetime(2019,1,1)
    end=datetime.datetime(y,m,d)

    d = data.DataReader(name=n,data_source="yahoo",start=start,end=end)

    def inc_dec(c,o):
        if c > o:
            value = "Increase"
        elif c < o:
            value = "Decrease"
        else:
            value = "Equal"

        return value

    d["Status"] = [inc_dec(c,o) for c,o in zip(d.Close,d.Open)]
    d["Middle"] = (d.Open + d.Close)/2
    d["Height"] = abs(d.Close-d.Open)

    p = figure(x_axis_type='datetime', width=1000, height=245,sizing_mode="scale_width")
    p.yaxis.axis_label = 'usd'
    
    t = Title()

    p.title= t
    p.grid.grid_line_alpha = 0.3

    hours_12 = 12*60*60*1000

    p.segment(d.index,d.High,d.index,d.Low,color="black")




    p.rect(d.index[d.Status=="Increase"],d.Middle[d.Status=="Increase"],
        hours_12,d.Height[d.Status=="Increase"],fill_color='#CCFFFF',line_color="black")


    p.rect(d.index[d.Status=="Decrease"],d.Middle[d.Status=="Decrease"],
        hours_12,d.Height[d.Status=="Decrease"],fill_color='#FF3333',line_color="black")


    script, div = components(p)

    cdn_js=CDN.js_files[0]
    cdn_css=CDN.css_files[0]

    re = [script,div,n,b,cdn_js,cdn_css]

    return re
Exemplo n.º 2
0
def plot_bpv(
    ax,
    length_plotters,
    rows,
    cols,
    obs_plotters,
    pp_plotters,
    total_pp_samples,
    kind,
    t_stat,
    bpv,
    plot_mean,
    reference,
    mse,
    n_ref,
    hdi_prob,
    color,
    figsize,
    textsize,
    labeller,
    plot_ref_kwargs,
    backend_kwargs,
    show,
):
    """Bokeh bpv plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(),
        **backend_kwargs,
    }

    color = vectorized_to_hex(color)

    if plot_ref_kwargs is None:
        plot_ref_kwargs = {}
    if kind == "p_value" and reference == "analytical":
        plot_ref_kwargs.setdefault("line_color", "black")
        plot_ref_kwargs.setdefault("line_dash", "dashed")
    else:
        plot_ref_kwargs.setdefault("alpha", 0.1)
        plot_ref_kwargs.setdefault("line_color", color)

    (figsize, ax_labelsize, _, _, linewidth,
     markersize) = _scale_fig_size(figsize, textsize, rows, cols)

    if ax is None:
        axes = create_axes_grid(
            length_plotters,
            rows,
            cols,
            figsize=figsize,
            backend_kwargs=backend_kwargs,
        )
    else:
        axes = np.atleast_2d(ax)

        if len([item for item in axes.ravel() if not None]) != length_plotters:
            raise ValueError(
                "Found {} variables to plot but {} axes instances. They must be equal."
                .format(length_plotters, len(axes)))

    for i, ax_i in enumerate(
        (item for item in axes.flatten() if item is not None)):
        var_name, sel, isel, obs_vals = obs_plotters[i]
        pp_var_name, _, _, pp_vals = pp_plotters[i]

        obs_vals = obs_vals.flatten()
        pp_vals = pp_vals.reshape(total_pp_samples, -1)

        if obs_vals.dtype.kind == "i" or pp_vals.dtype.kind == "i":
            obs_vals, pp_vals = smooth_data(obs_vals, pp_vals)

        if kind == "p_value":
            tstat_pit = np.mean(pp_vals <= obs_vals, axis=-1)
            x_s, tstat_pit_dens = kde(tstat_pit)
            ax_i.line(x_s,
                      tstat_pit_dens,
                      line_width=linewidth,
                      line_color=color)
            if reference is not None:
                dist = stats.beta(obs_vals.size / 2, obs_vals.size / 2)
                if reference == "analytical":
                    lwb = dist.ppf((1 - 0.9999) / 2)
                    upb = 1 - lwb
                    x = np.linspace(lwb, upb, 500)
                    dens_ref = dist.pdf(x)
                    ax_i.line(x, dens_ref, **plot_ref_kwargs)
                elif reference == "samples":
                    x_ss, u_dens = sample_reference_distribution(
                        dist,
                        (
                            tstat_pit_dens.size,
                            n_ref,
                        ),
                    )
                    ax_i.multi_line(list(x_ss.T),
                                    list(u_dens.T),
                                    line_width=linewidth,
                                    **plot_ref_kwargs)

        elif kind == "u_value":
            tstat_pit = np.mean(pp_vals <= obs_vals, axis=0)
            x_s, tstat_pit_dens = kde(tstat_pit)
            ax_i.line(x_s, tstat_pit_dens, color=color)
            if reference is not None:
                if reference == "analytical":
                    n_obs = obs_vals.size
                    hdi_ = stats.beta(n_obs / 2, n_obs / 2).ppf(
                        (1 - hdi_prob) / 2)
                    hdi_odds = (hdi_ / (1 - hdi_), (1 - hdi_) / hdi_)
                    ax_i.add_layout(
                        BoxAnnotation(
                            bottom=hdi_odds[1],
                            top=hdi_odds[0],
                            fill_alpha=plot_ref_kwargs.pop("alpha"),
                            fill_color=plot_ref_kwargs.pop("line_color"),
                            **plot_ref_kwargs,
                        ))
                    ax_i.line([0, 1], [1, 1], line_color="white")
                elif reference == "samples":
                    dist = stats.uniform(0, 1)
                    x_ss, u_dens = sample_reference_distribution(
                        dist, (tstat_pit_dens.size, n_ref))
                    for x_ss_i, u_dens_i in zip(x_ss.T, u_dens.T):
                        ax_i.line(x_ss_i,
                                  u_dens_i,
                                  line_width=linewidth,
                                  **plot_ref_kwargs)
            if mse:
                ax_i.line(0,
                          0,
                          legend_label=
                          f"mse={np.mean((1 - tstat_pit_dens)**2) * 100:.2f}")

            ax_i.line(0, 0)
        else:
            if t_stat in ["mean", "median", "std"]:
                if t_stat == "mean":
                    tfunc = np.mean
                elif t_stat == "median":
                    tfunc = np.median
                elif t_stat == "std":
                    tfunc = np.std
                obs_vals = tfunc(obs_vals)
                pp_vals = tfunc(pp_vals, axis=1)
            elif hasattr(t_stat, "__call__"):
                obs_vals = t_stat(obs_vals.flatten())
                pp_vals = t_stat(pp_vals)
            elif is_valid_quantile(t_stat):
                t_stat = float(t_stat)
                obs_vals = np.quantile(obs_vals, q=t_stat)
                pp_vals = np.quantile(pp_vals, q=t_stat, axis=1)
            else:
                raise ValueError(f"T statistics {t_stat} not implemented")

            plot_kde(pp_vals,
                     ax=ax_i,
                     plot_kwargs={"color": color},
                     backend="bokeh",
                     show=False)
            # ax_i.set_yticks([])
            if bpv:
                p_value = np.mean(pp_vals <= obs_vals)
                ax_i.line(0, 0, legend_label=f"bpv={p_value:.2f}", alpha=0)

            if plot_mean:
                ax_i.circle(obs_vals.mean(),
                            0,
                            fill_color=color,
                            line_color="black",
                            size=markersize)

        _title = Title()
        _title.text = labeller.make_pp_label(var_name, pp_var_name, sel, isel)
        ax_i.title = _title
        size = str(int(ax_labelsize))
        ax_i.title.text_font_size = f"{size}pt"

    show_layout(axes, show)

    return axes
    def tweets_per_hour_plot(self, data_path, emotion=None, color="#b3de69"):
        #data_path = os.path.dirname(__file__) + "/../data/pbFollowers/merged/"
        data_path = data_path + "merged/"
        dir_files = os.listdir(data_path)

        counts_of_tweets = {}

        for filename in dir_files:
            #df = pd.read_json(data_path + filename)
            df = self.get_flattened_data(data_path + filename, 'tones',
                                         ['user', 'created_at'])
            if emotion is not None:
                try:
                    df = df[df.tone_name == emotion]
                except AttributeError:
                    continue
            try:
                df['created_at'] = df['created_at'] / 1000
            except TypeError:
                print("\'Created_at\' error where it is somehow a dict")
                continue
            offset = 0
            try:
                offset = df['user'][0]['utc_offset']
            except (IndexError, KeyError):
                offset = 0
            if offset is None:
                offset = 0
            #df['std_time'] = df['created_at'] + pd.TimedeltaIndex(df['offset'], unit='s')
            df['std_time'] = df['created_at'] + offset
            df['std_time'] = [
                datetime.datetime.fromtimestamp(x) for x in df['std_time']
            ]
            df = df.set_index(df['std_time'])
            temp = pd.DatetimeIndex(df['std_time'])
            df['hour'] = temp.hour
            p = df.groupby(df['hour'])
            freq_of_tweets = p['std_time'].count()
            freq_dict = freq_of_tweets.to_dict()
            for key, value in freq_dict.items():
                try:
                    counts_of_tweets[key] += value
                except KeyError:
                    counts_of_tweets[key] = value

        hours = np.fromiter(counts_of_tweets.keys(), dtype=float)
        hours += 1
        numTweets = np.fromiter(counts_of_tweets.values(), dtype=float)

        # output to static HTML file
        if emotion is None:
            hourly_freq_plot_path = data_path + "../plots/Hourly_freq_plot.html"
            output_file(hourly_freq_plot_path)

        source = ColumnDataSource(data=dict(hours=hours, numTweets=numTweets))

        hover = HoverTool(tooltips=[
            ('hours', '@hours'),
            ('numTweets', '@numTweets'),
        ])

        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(x_range=xdr,
                    y_range=ydr,
                    plot_width=500,
                    plot_height=500,
                    h_symmetry=False,
                    v_symmetry=False,
                    min_border=0,
                    tools=[hover])

        glyph = VBar(x="hours",
                     top="numTweets",
                     bottom=0,
                     width=0.5,
                     fill_color=color)
        plot.add_glyph(source, glyph)

        xaxis = LinearAxis()
        plot.add_layout(xaxis, 'below')

        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')

        t = Title()
        if emotion is not None:
            t.text = "(" + emotion + ") Number of Tweets by Hour"
        else:
            t.text = "(all emotions) Number of Tweets by Hour"
        plot.title = t
        plot.xaxis.axis_label = 'Hours'
        plot.yaxis.axis_label = 'Number of Tweets'

        if emotion is not None:
            return plot
        else:
            show(plot)
            return plot
Exemplo n.º 4
0
def plot():
    from pandas_datareader import data
    import datetime
    from bokeh.plotting import figure, show, output_file
    from bokeh.models.annotations import Title
    # from bokeh.io import show, output_file
    from bokeh.embed import components
    from bokeh.resources import CDN

    start = datetime.datetime(2020, 7, 23)
    end = datetime.datetime(2021, 1, 23)

    df = data.DataReader(name="TSLA",
                         data_source="yahoo",
                         start=start,
                         end=end)

    def inc_dec(c, o):
        if c > o:
            value = "Increase"
        elif c < o:
            value = "Decrease"
        else:
            value = "Equal"
        return value

    df['Status'] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)]
    df["Middle"] = (df.Open + df.Close) / 2
    df["Height"] = abs(df.Close - df.Open)
    p = figure(x_axis_type='datetime',
               width=800,
               height=300,
               sizing_mode='scale_width')
    t = Title()
    t.text = "Tesla Candlestick Chart 7/23/2020 - 1/23/2021"
    p.title = t

    p.grid.grid_line_alpha = 0.3
    hours_12 = 12 * 60 * 60 * 1000

    p.segment(df.index, df.High, df.index, df.Low, color="black")
    p.rect(df.index[df.Status == "Increase"],
           df.Middle[df.Status == "Increase"],
           hours_12,
           df.Height[df.Status == "Increase"],
           fill_color="green",
           line_color="black")
    p.rect(df.index[df.Status == "Decrease"],
           df.Middle[df.Status == "Decrease"],
           hours_12,
           df.Height[df.Status == "Decrease"],
           fill_color="red",
           line_color="black")

    script1, div1 = components(p)
    cdn_js = CDN.js_files[0]
    cdn_css = CDN.css_files
    return render_template("plot.html",
                           script1=script1,
                           div1=div1,
                           cdn_css=cdn_css,
                           cdn_js=cdn_js)
Exemplo n.º 5
0
def plot():
    from pandas_datareader import data
    import datetime
    from bokeh.plotting import figure, show, output_file
    from bokeh.models.annotations import Title
    from bokeh.embed import components
    from bokeh.resources import CDN

    start = datetime.datetime(2015, 11, 1)
    end = datetime.datetime(2016, 3, 10)

    df = data.DataReader(name='GOOG',
                         data_source='yahoo',
                         start=start,
                         end=end)

    def inc_dec(c, o):
        if c > o:
            value = "Increase"
        elif c < o:
            value = "Decrease"
        else:
            value = "Equal"
        return value

    df["Status"] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)]

    df["Middle"] = (df.Open + df.Close) / 2
    df["Height"] = abs(df.Close - df.Open)

    p = figure(x_axis_type='datetime',
               width=1000,
               height=300,
               sizing_mode="scale_width")
    a = Title()
    a.text = "Candlestick Chart"
    p.title = a
    p.grid.grid_line_alpha = 0.3

    #Define rectangles for gray parts of candlestick chart, pass x and y coords of center, as well as length and width
    hours_12 = 12 * 60 * 60 * 1000

    p.segment(df.index, df.High, df.index, df.Low, color="Black")
    p.rect(df.index[df.Status == 'Increase'],
           df.Middle[df.Status == "Increase"],
           hours_12,
           df.Height[df.Status == "Increase"],
           fill_color='green',
           line_color='black')
    p.rect(df.index[df.Status == 'Decrease'],
           df.Middle[df.Status == "Decrease"],
           hours_12,
           df.Height[df.Status == "Decrease"],
           fill_color='red',
           line_color='black')

    script1, div1 = components(p)
    cdn_js = CDN.js_files[0]
    cdn_css = CDN.css_files[0]
    return render_template("plot.html",
                           script1=script1,
                           div1=div1,
                           cdn_css=cdn_css,
                           cdn_js=cdn_js)
    output_file('CS.html')
    show(p)
Exemplo n.º 6
0
def plot_trace(
    data,
    var_names,
    divergences,
    kind,
    figsize,
    rug,
    lines,
    circ_var_names,  # pylint: disable=unused-argument
    circ_var_units,  # pylint: disable=unused-argument
    compact,
    compact_prop,
    combined,
    chain_prop,
    legend,
    labeller,
    plot_kwargs,
    fill_kwargs,
    rug_kwargs,
    hist_kwargs,
    trace_kwargs,
    rank_kwargs,
    plotters,
    divergence_data,
    axes,
    backend_kwargs,
    backend_config,
    show,
):
    """Bokeh traceplot."""
    # If divergences are plotted they must be provided
    if divergences is not False:
        assert divergence_data is not None

    if backend_config is None:
        backend_config = {}

    backend_config = {
        **backend_kwarg_defaults(("bounds_y_range", "plot.bokeh.bounds_y_range"), ),
        **backend_config,
    }

    # Set plot default backend kwargs
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ),
        **backend_kwargs,
    }
    dpi = backend_kwargs.pop("dpi")

    if figsize is None:
        figsize = (12, len(plotters) * 2)

    figsize, _, _, _, linewidth, _ = _scale_fig_size(figsize,
                                                     10,
                                                     rows=len(plotters),
                                                     cols=2)

    backend_kwargs.setdefault("height", int(figsize[1] * dpi // len(plotters)))
    backend_kwargs.setdefault("width", int(figsize[0] * dpi // 2))

    if lines is None:
        lines = ()

    num_chain_props = len(data.chain) + 1 if combined else len(data.chain)
    if not compact:
        chain_prop = ({
            "line_color":
            plt.rcParams["axes.prop_cycle"].by_key()["color"]
        } if chain_prop is None else chain_prop)
    else:
        chain_prop = ({
            "line_dash": ("solid", "dotted", "dashed", "dashdot"),
        } if chain_prop is None else chain_prop)
        compact_prop = ({
            "line_color":
            plt.rcParams["axes.prop_cycle"].by_key()["color"]
        } if compact_prop is None else compact_prop)

    if isinstance(chain_prop, str):
        chain_prop = {
            chain_prop: plt.rcParams["axes.prop_cycle"].by_key()[chain_prop]
        }
    if isinstance(chain_prop, tuple):
        warnings.warn(
            "chain_prop as a tuple will be deprecated in a future warning, use a dict instead",
            FutureWarning,
        )
        chain_prop = {chain_prop[0]: chain_prop[1]}
    chain_prop = {
        prop_name:
        [prop for _, prop in zip(range(num_chain_props), cycle(props))]
        for prop_name, props in chain_prop.items()
    }

    if isinstance(compact_prop, str):
        compact_prop = {
            compact_prop:
            plt.rcParams["axes.prop_cycle"].by_key()[compact_prop]
        }
    if isinstance(compact_prop, tuple):
        warnings.warn(
            "compact_prop as a tuple will be deprecated in a future warning, use a dict instead",
            FutureWarning,
        )
        compact_prop = {compact_prop[0]: compact_prop[1]}

    trace_kwargs = {} if trace_kwargs is None else trace_kwargs
    trace_kwargs.setdefault("alpha", 0.35)

    if hist_kwargs is None:
        hist_kwargs = {}
    hist_kwargs.setdefault("alpha", 0.35)

    if plot_kwargs is None:
        plot_kwargs = {}
    if fill_kwargs is None:
        fill_kwargs = {}
    if rug_kwargs is None:
        rug_kwargs = {}
    if rank_kwargs is None:
        rank_kwargs = {}

    trace_kwargs.setdefault("line_width", linewidth)
    plot_kwargs.setdefault("line_width", linewidth)

    if rank_kwargs is None:
        rank_kwargs = {}

    if axes is None:
        axes = []
        backend_kwargs_copy = backend_kwargs.copy()
        for i in range(len(plotters)):
            if not i:
                _axes = [
                    bkp.figure(**backend_kwargs),
                    bkp.figure(**backend_kwargs_copy)
                ]
                backend_kwargs_copy.setdefault("x_range", _axes[1].x_range)
            else:
                _axes = [
                    bkp.figure(**backend_kwargs),
                    bkp.figure(**backend_kwargs_copy),
                ]
            axes.append(_axes)

    axes = np.atleast_2d(axes)

    cds_data = {}
    cds_var_groups = {}
    draw_name = "draw"

    for var_name, selection, isel, value in list(
            xarray_var_iter(data, var_names=var_names, combined=True)):
        if selection:
            cds_name = "{}_ARVIZ_CDS_SELECTION_{}".format(
                var_name,
                "_".join(
                    str(item) for key, value in selection.items()
                    for item in ([key, value] if (
                        isinstance(value, str) or
                        not isinstance(value, Iterable)) else [key, *value])),
            )
        else:
            cds_name = var_name

        if var_name not in cds_var_groups:
            cds_var_groups[var_name] = []
        cds_var_groups[var_name].append(cds_name)

        for chain_idx, _ in enumerate(data.chain.values):
            if chain_idx not in cds_data:
                cds_data[chain_idx] = {}
            _data = value[chain_idx]
            cds_data[chain_idx][cds_name] = _data

    while any(key == draw_name for key in cds_data[0]):
        draw_name += "w"

    for chain_idx in cds_data:
        cds_data[chain_idx][draw_name] = data.draw.values

    cds_data = {
        chain_idx: ColumnDataSource(cds)
        for chain_idx, cds in cds_data.items()
    }

    for idx, (var_name, selection, isel, value) in enumerate(plotters):
        value = np.atleast_2d(value)

        if len(value.shape) == 2:
            y_name = (var_name
                      if not selection else "{}_ARVIZ_CDS_SELECTION_{}".format(
                          var_name,
                          "_".join(
                              str(item) for key, value in selection.items()
                              for item in ((key, value) if (
                                  isinstance(value, str)
                                  or not isinstance(value, Iterable)) else (
                                      key, *value))),
                      ))
            if rug:
                rug_kwargs["y"] = y_name
            _plot_chains_bokeh(
                ax_density=axes[idx, 0],
                ax_trace=axes[idx, 1],
                data=cds_data,
                x_name=draw_name,
                y_name=y_name,
                chain_prop=chain_prop,
                combined=combined,
                rug=rug,
                kind=kind,
                legend=legend,
                trace_kwargs=trace_kwargs,
                hist_kwargs=hist_kwargs,
                plot_kwargs=plot_kwargs,
                fill_kwargs=fill_kwargs,
                rug_kwargs=rug_kwargs,
                rank_kwargs=rank_kwargs,
            )
        else:
            for y_name in cds_var_groups[var_name]:
                if rug:
                    rug_kwargs["y"] = y_name
                _plot_chains_bokeh(
                    ax_density=axes[idx, 0],
                    ax_trace=axes[idx, 1],
                    data=cds_data,
                    x_name=draw_name,
                    y_name=y_name,
                    chain_prop=chain_prop,
                    combined=combined,
                    rug=rug,
                    kind=kind,
                    legend=legend,
                    trace_kwargs=trace_kwargs,
                    hist_kwargs=hist_kwargs,
                    plot_kwargs=plot_kwargs,
                    fill_kwargs=fill_kwargs,
                    rug_kwargs=rug_kwargs,
                    rank_kwargs=rank_kwargs,
                )

        for col in (0, 1):
            _title = Title()
            _title.text = labeller.make_label_vert(var_name, selection, isel)
            axes[idx, col].title = _title
            axes[idx, col].y_range = DataRange1d(
                bounds=backend_config["bounds_y_range"], min_interval=0.1)

        for _, _, vlines in (j for j in lines
                             if j[0] == var_name and j[1] == selection):
            if isinstance(vlines, (float, int)):
                line_values = [vlines]
            else:
                line_values = np.atleast_1d(vlines).ravel()

            for line_value in line_values:
                vline = Span(
                    location=line_value,
                    dimension="height",
                    line_color="black",
                    line_width=1.5,
                    line_alpha=0.75,
                )
                hline = Span(
                    location=line_value,
                    dimension="width",
                    line_color="black",
                    line_width=1.5,
                    line_alpha=trace_kwargs["alpha"],
                )

                axes[idx, 0].renderers.append(vline)
                axes[idx, 1].renderers.append(hline)

        if legend:
            for col in (0, 1):
                axes[idx, col].legend.location = "top_left"
                axes[idx, col].legend.click_policy = "hide"
        else:
            for col in (0, 1):
                if axes[idx, col].legend:
                    axes[idx, col].legend.visible = False

        if divergences:
            div_density_kwargs = {}
            div_density_kwargs.setdefault("size", 14)
            div_density_kwargs.setdefault("line_color", "red")
            div_density_kwargs.setdefault("line_width", 2)
            div_density_kwargs.setdefault("line_alpha", 0.50)
            div_density_kwargs.setdefault("angle", np.pi / 2)

            div_trace_kwargs = {}
            div_trace_kwargs.setdefault("size", 14)
            div_trace_kwargs.setdefault("line_color", "red")
            div_trace_kwargs.setdefault("line_width", 2)
            div_trace_kwargs.setdefault("line_alpha", 0.50)
            div_trace_kwargs.setdefault("angle", np.pi / 2)

            div_selection = {
                k: v
                for k, v in selection.items() if k in divergence_data.dims
            }
            divs = divergence_data.sel(**div_selection).values
            divs = np.atleast_2d(divs)

            for chain, chain_divs in enumerate(divs):
                div_idxs = np.arange(len(chain_divs))[chain_divs]
                if div_idxs.size > 0:
                    values = value[chain, div_idxs]
                    tmp_cds = ColumnDataSource({"y": values, "x": div_idxs})
                    if divergences == "top":
                        y_div_trace = value.max()
                    else:
                        y_div_trace = value.min()
                    glyph_density = Dash(x="y", y=0.0, **div_density_kwargs)
                    if kind == "trace":
                        glyph_trace = Dash(x="x",
                                           y=y_div_trace,
                                           **div_trace_kwargs)
                        axes[idx, 1].add_glyph(tmp_cds, glyph_trace)

                    axes[idx, 0].add_glyph(tmp_cds, glyph_density)

    show_layout(axes, show)

    return axes
Exemplo n.º 7
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
Exemplo n.º 8
0
def _d_helper(
    vec,
    vname,
    color,
    bw,
    line_width,
    markersize,
    credible_interval,
    point_estimate,
    hpd_markers,
    outline,
    shade,
    ax,
    data_label,
):
    extra = dict()
    if data_label is not None:
        extra["legend_label"] = data_label

    if vec.dtype.kind == "f":
        if credible_interval != 1:
            hpd_ = hpd(vec, credible_interval, multimodal=False)
            new_vec = vec[(vec >= hpd_[0]) & (vec <= hpd_[1])]
        else:
            new_vec = vec

        density, xmin, xmax = _fast_kde(new_vec, bw=bw)
        density *= credible_interval
        x = np.linspace(xmin, xmax, len(density))
        ymin = density[0]
        ymax = density[-1]

        if outline:
            ax.line(x,
                    density,
                    line_color=color,
                    line_width=line_width,
                    **extra)
            ax.line(
                [xmin, xmin],
                [-ymin / 100, ymin],
                line_color=color,
                line_dash="solid",
                line_width=line_width,
            )
            ax.line(
                [xmax, xmax],
                [-ymax / 100, ymax],
                line_color=color,
                line_dash="solid",
                line_width=line_width,
            )

        if shade:
            ax.patch(np.r_[x[::-1], x, x[-1:]],
                     np.r_[np.zeros_like(x), density, [0]],
                     fill_color=color,
                     fill_alpha=shade,
                     **extra)

    else:
        xmin, xmax = hpd(vec, credible_interval, multimodal=False)
        bins = range(xmin, xmax + 2)

        _, hist, edges = histogram(vec, bins=bins)

        if outline:
            ax.quad(top=hist,
                    bottom=0,
                    left=edges[:-1],
                    right=edges[1:],
                    line_color=color,
                    fill_color=None,
                    **extra)
        else:
            ax.quad(top=hist,
                    bottom=0,
                    left=edges[:-1],
                    right=edges[1:],
                    line_color=color,
                    fill_color=color,
                    fill_alpha=shade,
                    **extra)

    if hpd_markers:
        ax.diamond(xmin,
                   0,
                   line_color="black",
                   fill_color=color,
                   size=markersize)
        ax.diamond(xmax,
                   0,
                   line_color="black",
                   fill_color=color,
                   size=markersize)

    if point_estimate is not None:
        if point_estimate == "mean":
            est = np.mean(vec)
        elif point_estimate == "median":
            est = np.median(vec)
        ax.circle(est,
                  0,
                  fill_color=color,
                  line_color="black",
                  size=markersize)

    _title = Title()
    _title.text = vname
    ax.title = _title
Exemplo n.º 9
0
    items.append(a[1])
count = Counter(items)
result = {}
"""
for x in count.keys():
        result = {months[int(x)]: count[x]}
        print count[x]
        #birthday.update({person: date})
"""
result = {months[int(x)]: count[x] for x in count.keys()}

print(result.keys())
output_file("plot.html")
categories = list(months.values())
print(categories)
x = list(result.keys())
y = list(count.values())

p = figure(x_range=categories)
p.vbar(x=x, top=y, width=0.5)

p.xaxis.axis_label = 'Miesiace'
p.yaxis.axis_label = 'Liczba naukowcow'
t = Title()
t.text = 'Moja figura'
p.title = t
show(p)
"""
for x in birthday.keys():
   type(x.encode('utf-8'))
"""
Exemplo n.º 10
0
}
geomap.patches(**patches_opts)

##create chart

chart_opts = {
    'plot_width':840,
    'plot_height':350,
    'tools':'',
    'x_axis_type': 'datetime',
    'output_backend': 'webgl',
    'title': '',
}

chart = figure(**chart_opts)
chart_title = Title()
chart_title.text = "starting title"
chart.title = chart_title

chart_wheel_zoom = WheelZoomTool()
chart_pan_tool = PanTool()

chart.add_tools(chart_wheel_zoom, chart_pan_tool)
chart.toolbar.active_scroll = chart_wheel_zoom

chart.xaxis.visible = False
chart_lines = None
chart_hover = None

chart.toolbar.logo = None
chart.toolbar_location = None
Exemplo n.º 11
0
def plot_posterior(
    ax,
    length_plotters,
    rows,
    cols,
    figsize,
    plotters,
    bw,
    circular,
    bins,
    kind,
    point_estimate,
    round_to,
    hdi_prob,
    multimodal,
    skipna,
    textsize,
    ref_val,
    rope,
    kwargs,
    backend_kwargs,
    show,
):
    """Bokeh posterior plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ),
        **backend_kwargs,
    }

    (figsize, ax_labelsize, *_, linewidth,
     _) = _scale_fig_size(figsize, textsize, rows, cols)

    if ax is None:
        ax = create_axes_grid(
            length_plotters,
            rows,
            cols,
            figsize=figsize,
            backend_kwargs=backend_kwargs,
        )
    else:
        ax = np.atleast_2d(ax)
    idx = 0
    for (var_name, selection,
         x), ax_ in zip(plotters,
                        (item for item in ax.flatten() if item is not None)):
        _plot_posterior_op(idx,
                           x.flatten(),
                           var_name,
                           selection,
                           ax=ax_,
                           bw=bw,
                           circular=circular,
                           bins=bins,
                           kind=kind,
                           point_estimate=point_estimate,
                           round_to=round_to,
                           hdi_prob=hdi_prob,
                           multimodal=multimodal,
                           skipna=skipna,
                           linewidth=linewidth,
                           ref_val=ref_val,
                           rope=rope,
                           ax_labelsize=ax_labelsize,
                           **kwargs)
        idx += 1
        _title = Title()
        _title.text = make_label(var_name, selection)
        ax_.title = _title

    show_layout(ax, show)

    return ax
Exemplo n.º 12
0
def plot_ious_bokeh(ious, zvalues):
    per_row = 50
    dz = (ious.shape[1] - 1) // 2
    ylabels = [z for z in range(-dz, dz + 1)]

    mapper = LinearColorMapper(palette=Plasma256, low=0.0, high=1.0)
    colorbar = ColorBar(color_mapper=mapper,
                        major_label_text_font_size="5pt",
                        label_standoff=12,
                        location=(0, 0))
    tabs = []
    # one figure for every 200 sections
    newz = []
    newiou = []

    t = Title()
    t.text = "IOU Plot"
    xaxis = LinearAxis()
    yaxis = LinearAxis()

    for i in range(0, len(zvalues), 200):
        if i + 199 > len(zvalues):
            newz = zvalues[i:]
            newiou = ious[i:, :]
        else:
            newz = zvalues[i:i + 199]
            newiou = ious[i:i + 199, :]

        if len(newz) % per_row == 0:
            rows = len(newz) // per_row
        else:
            rows = (len(newz) // per_row) + 1

        plots = []

        if rows > 1:
            #p.add_layout(xaxis, 'below')
            #p.add_layout(yaxis, 'left')

            for r in range(rows):
                start = r * per_row
                xvalues = np.ndarray.flatten(newiou[start:start + per_row])
                x_range1 = newz[start:start +
                                per_row]  #range(start, start+per_row+1)
                x_range = np.repeat(x_range1, len(ylabels))
                y_range = np.tile(ylabels, len(x_range1))

                source = ColumnDataSource(
                    dict(x=x_range, y=y_range, iou=xvalues))
                p = figure(title=t,
                           plot_width=400 * rows,
                           plot_height=100 * rows)
                p.axis.axis_line_color = None
                p.axis.major_tick_line_color = None
                p.axis.major_label_text_font_size = "10pt"
                p.axis.major_label_standoff = 0
                #p.axis.major_label_orientation = 1.0
                '''
                glyph = Rect(x="x", y="y",
                        width=1, height=1,
                        fill_color={'field': 'iou', 'transform': mapper},
                        line_color=None)
                p.add_glyph(source, glyph)
                '''
                p.rect(x="x",
                       y="y",
                       width=1,
                       height=1,
                       source=source,
                       fill_color={
                           'field': 'iou',
                           'transform': mapper
                       },
                       line_color=None)
                plots.append(p)
        #        tabs.append([p])
        else:
            xvalues = np.ndarray.flatten(newiou)
            x_range = np.repeat(zvalues, len(ylabels))
            y_range = [int(z) for z in ylabels]
            y_range = np.tile(y_range, len(zvalues))

            p = figure(title=t)
            source = ColumnDataSource(dict(x=x_range, y=y_range, iou=xvalues))
            glyph = Rect(x="x",
                         y="y",
                         width=1,
                         height=1,
                         fill_color={
                             'field': 'iou',
                             'transform': mapper
                         },
                         line_color=None)
            p.add_glyph(source, glyph)
            '''
            p = figure(title=t)
            source = ColumnDataSource(dict(x=x_range, y=y_range, iou=xvalues))
            p.rect(x="x", y="y",
                    width=1, height=1,
                    source=source,
                    fill_color={'field': 'iou', 'transform': mapper},
                    line_color=None)
            '''
            p.add_layout(colorbar, 'right')
            #show(p)
            #tabs.append([p])
            plots.append(p)
        tabs = [[p] for p in plots]

    grid = gridplot(tabs)
    return grid
Exemplo n.º 13
0
    life.name = 'life'
    population = population_df_size[year]
    population.name = 'population'
    new_df = pd.concat([fertility, life, population, region_name], axis=1)
    sources['_' + str(year)] = ColumnDataSource(new_df)

dictionary_of_sources = dict(
    zip([x for x in years], ['_%s' % x for x in years]))
js_source_array = str(dictionary_of_sources).replace("'", "")

xdr = Range1d(1, 9)
ydr = Range1d(20, 100)
plot = Plot(
    x_range=xdr,
    y_range=ydr,
    title=Title(text=''),
    plot_width=800,
    plot_height=400,
    outline_line_color=None,
    toolbar_location=None,
    min_border=20,
)

AXIS_FORMATS = dict(
    minor_tick_in=None,
    minor_tick_out=None,
    major_tick_in=None,
    major_label_text_font_size="10pt",
    major_label_text_font_style="normal",
    axis_label_text_font_size="10pt",
    axis_line_color='#AAAAAA',
Exemplo n.º 14
0
def _plot_mcse(
    ax,
    plotters,
    length_plotters,
    rows,
    cols,
    figsize,
    errorbar,
    rug,
    data,
    probs,
    extra_kwargs,
    extra_methods,
    mean_mcse,
    sd_mcse,
    rug_kwargs,
    idata,
    rug_kind,
    _markersize,
    _linewidth,
    show,
):
    if ax is None:
        _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, backend="bokeh")

    for (var_name, selection, x), ax_ in zip(plotters, np.ravel(ax)):
        if errorbar or rug:
            values = data[var_name].sel(**selection).values.flatten()
        if errorbar:
            quantile_values = _quantile(values, probs)
            ax_.dash(probs, quantile_values)
            ax_.multi_line(
                list(zip(probs, probs)),
                [(quant - err, quant + err) for quant, err in zip(quantile_values, x)],
            )
        else:
            ax_.circle(probs, x)
            if extra_methods:
                mean_mcse_i = mean_mcse[var_name].sel(**selection).values.item()
                sd_mcse_i = sd_mcse[var_name].sel(**selection).values.item()
                hline_mean = Span(
                    location=mean_mcse_i,
                    dimension="width",
                    line_color="black",
                    line_width=extra_kwargs["linewidth"] * 2,
                    line_alpha=extra_kwargs["alpha"],
                )

                ax_.renderers.append(hline_mean)

                hline_sd = Span(
                    location=sd_mcse_i,
                    dimension="width",
                    line_color="black",
                    line_width=extra_kwargs["linewidth"],
                    line_alpha=extra_kwargs["alpha"],
                )

                ax_.renderers.append(hline_sd)

        if rug:
            if rug_kwargs is None:
                rug_kwargs = {}
            if not hasattr(idata, "sample_stats"):
                raise ValueError("InferenceData object must contain sample_stats for rug plot")
            if not hasattr(idata.sample_stats, rug_kind):
                raise ValueError("InferenceData does not contain {} data".format(rug_kind))
            rug_kwargs.setdefault("space", 0.1)

            _rug_kwargs = {}
            _rug_kwargs.setdefault("size", 8)
            _rug_kwargs.setdefault("line_color", rug_kwargs.get("line_color", "black"))
            _rug_kwargs.setdefault("line_width", 1)
            _rug_kwargs.setdefault("line_alpha", 0.35)
            _rug_kwargs.setdefault("angle", np.pi / 2)

            mask = idata.sample_stats[rug_kind].values.flatten()
            values = rankdata(values)[mask]
            if errorbar:
                rug_x, rug_y = (
                    values / (len(mask) - 1),
                    np.full_like(
                        values,
                        min(
                            0,
                            min(quantile_values)
                            - (max(quantile_values) - min(quantile_values)) * 0.05,
                        ),
                    ),
                )

                hline = Span(
                    location=min(
                        0,
                        min(quantile_values) - (max(quantile_values) - min(quantile_values)) * 0.05,
                    ),
                    dimension="width",
                    line_color="black",
                    line_width=_linewidth,
                    line_alpha=0.7,
                )

            else:
                rug_x, rug_y = (
                    values / (len(mask) - 1),
                    np.full_like(values, 0,),
                )

                hline = Span(
                    location=0,
                    dimension="width",
                    line_color="black",
                    line_width=_linewidth,
                    line_alpha=0.7,
                )

            ax_.renderers.append(hline)

            glyph = Dash(x="rug_x", y="rug_y", **_rug_kwargs)
            cds_rug = ColumnDataSource({"rug_x": np.asarray(rug_x), "rug_y": np.asarray(rug_y)})
            ax_.add_glyph(cds_rug, glyph)

        title = Title()
        title.text = make_label(var_name, selection)
        ax_.title = title

        ax_.xaxis.axis_label = "Quantile"
        ax_.yaxis.axis_label = (
            r"Value $\pm$ MCSE for quantiles" if errorbar else "MCSE for quantiles"
        )

        if not errorbar:
            ax_.y_range._property_values["start"] = -0.05  # pylint: disable=protected-access
            ax_.y_range._property_values["end"] = 1  # pylint: disable=protected-access

    if show:
        grid = gridplot([list(item) for item in ax], toolbar_location="above")
        bkp.show(grid)

    return ax
Exemplo n.º 15
0
def plot_violin(
    ax,
    plotters,
    figsize,
    rows,
    cols,
    sharex,
    sharey,
    shade_kwargs,
    shade,
    rug,
    rug_kwargs,
    bw,
    textsize,
    circular,
    hdi_prob,
    quartiles,
    backend_kwargs,
    show,
):
    """Bokeh violin plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"),),
        **backend_kwargs,
    }
    (figsize, *_, linewidth, _) = _scale_fig_size(figsize, textsize, rows, cols)

    shade_kwargs = {} if shade_kwargs is None else shade_kwargs
    rug_kwargs = {} if rug_kwargs is None else rug_kwargs
    rug_kwargs.setdefault("fill_alpha", 0.1)
    rug_kwargs.setdefault("line_alpha", 0.1)
    if ax is None:
        _, ax = _create_axes_grid(
            len(plotters),
            rows,
            cols,
            sharex=sharex,
            sharey=sharey,
            figsize=figsize,
            squeeze=False,
            backend="bokeh",
            backend_kwargs=backend_kwargs,
        )
    else:
        ax = np.atleast_2d(ax)

    for (var_name, selection, x), ax_ in zip(
        plotters, (item for item in ax.flatten() if item is not None)
    ):
        val = x.flatten()
        if val[0].dtype.kind == "i":
            dens = cat_hist(val, rug, shade, ax_, **shade_kwargs)
        else:
            dens = _violinplot(val, rug, shade, bw, circular, ax_, **shade_kwargs)

        if rug:
            rug_x = -np.abs(np.random.normal(scale=max(dens) / 3.5, size=len(val)))
            ax_.scatter(rug_x, val, **rug_kwargs)

        per = np.percentile(val, [25, 75, 50])
        hdi_probs = hdi(val, hdi_prob, multimodal=False)

        if quartiles:
            ax_.line(
                [0, 0], per[:2], line_width=linewidth * 3, line_color="black", line_cap="round"
            )
        ax_.line([0, 0], hdi_probs, line_width=linewidth, line_color="black", line_cap="round")
        ax_.circle(
            0,
            per[-1],
            line_color="white",
            fill_color="white",
            size=linewidth * 1.5,
            line_width=linewidth,
        )

        _title = Title()
        _title.text = make_label(var_name, selection)
        ax_.title = _title
        ax_.xaxis.major_tick_line_color = None
        ax_.xaxis.minor_tick_line_color = None
        ax_.xaxis.major_label_text_font_size = "0pt"

    show_layout(ax, show)

    return ax
Exemplo n.º 16
0
def _d_helper(
    vec,
    vname,
    color,
    bw,
    line_width,
    markersize,
    credible_interval,
    point_estimate,
    hpd_markers,
    outline,
    shade,
    ax,
):

    extra = dict()
    plotted = []

    if vec.dtype.kind == "f":
        if credible_interval != 1:
            hpd_ = hpd(vec, credible_interval, multimodal=False)
            new_vec = vec[(vec >= hpd_[0]) & (vec <= hpd_[1])]
        else:
            new_vec = vec

        density, xmin, xmax = _fast_kde(new_vec, bw=bw)
        density *= credible_interval
        x = np.linspace(xmin, xmax, len(density))
        ymin = density[0]
        ymax = density[-1]

        if outline:
            plotted.append(
                ax.line(x,
                        density,
                        line_color=color,
                        line_width=line_width,
                        **extra))
            plotted.append(
                ax.line(
                    [xmin, xmin],
                    [-ymin / 100, ymin],
                    line_color=color,
                    line_dash="solid",
                    line_width=line_width,
                    muted_color=color,
                    muted_alpha=0.2,
                ))
            plotted.append(
                ax.line(
                    [xmax, xmax],
                    [-ymax / 100, ymax],
                    line_color=color,
                    line_dash="solid",
                    line_width=line_width,
                    muted_color=color,
                    muted_alpha=0.2,
                ))

        if shade:
            plotted.append(
                ax.patch(np.r_[x[::-1], x, x[-1:]],
                         np.r_[np.zeros_like(x), density, [0]],
                         fill_color=color,
                         fill_alpha=shade,
                         muted_color=color,
                         muted_alpha=0.2,
                         **extra))

    else:
        xmin, xmax = hpd(vec, credible_interval, multimodal=False)
        bins = get_bins(vec)

        _, hist, edges = histogram(vec, bins=bins)

        if outline:
            plotted.append(
                ax.quad(top=hist,
                        bottom=0,
                        left=edges[:-1],
                        right=edges[1:],
                        line_color=color,
                        fill_color=None,
                        muted_color=color,
                        muted_alpha=0.2,
                        **extra))
        else:
            plotted.append(
                ax.quad(top=hist,
                        bottom=0,
                        left=edges[:-1],
                        right=edges[1:],
                        line_color=color,
                        fill_color=color,
                        fill_alpha=shade,
                        muted_color=color,
                        muted_alpha=0.2,
                        **extra))

    if hpd_markers:
        plotted.append(
            ax.diamond(xmin,
                       0,
                       line_color="black",
                       fill_color=color,
                       size=markersize))
        plotted.append(
            ax.diamond(xmax,
                       0,
                       line_color="black",
                       fill_color=color,
                       size=markersize))

    if point_estimate is not None:
        est = calculate_point_estimate(point_estimate, vec, bw)
        plotted.append(
            ax.circle(est,
                      0,
                      fill_color=color,
                      line_color="black",
                      size=markersize))

    _title = Title()
    _title.text = vname
    ax.title = _title
    ax.title.text_font_size = "13pt"

    return plotted
Exemplo n.º 17
0
def plot_rank(
    axes,
    length_plotters,
    rows,
    cols,
    figsize,
    plotters,
    bins,
    kind,
    colors,
    ref_line,
    labels,
    backend_kwargs,
    show,
):
    """Bokeh rank plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ),
        **backend_kwargs,
    }
    figsize, *_ = _scale_fig_size(figsize, None, rows=rows, cols=cols)
    if axes is None:
        _, axes = _create_axes_grid(
            length_plotters,
            rows,
            cols,
            figsize=figsize,
            squeeze=False,
            sharex=True,
            sharey=True,
            backend="bokeh",
            backend_kwargs=backend_kwargs,
        )
    else:
        axes = np.atleast_2d(axes)

    for ax, (var_name, selection, var_data) in zip(
        (item for item in axes.flatten() if item is not None), plotters):
        ranks = scipy.stats.rankdata(var_data).reshape(var_data.shape)
        bin_ary = np.histogram_bin_edges(ranks,
                                         bins=bins,
                                         range=(0, ranks.size))
        all_counts = np.empty((len(ranks), len(bin_ary) - 1))
        for idx, row in enumerate(ranks):
            _, all_counts[idx], _ = histogram(row, bins=bin_ary)
        counts_normalizer = all_counts.max() / 0.95
        gap = 1
        width = bin_ary[1] - bin_ary[0]

        # Center the bins
        bin_ary = (bin_ary[1:] + bin_ary[:-1]) / 2

        y_ticks = []
        if kind == "bars":
            for idx, counts in enumerate(all_counts):
                counts = counts / counts_normalizer
                y_ticks.append(idx * gap)
                ax.vbar(
                    x=bin_ary,
                    top=y_ticks[-1] + counts,
                    bottom=y_ticks[-1],
                    width=width,
                    fill_color=colors[idx],
                    line_color="white",
                )
                if ref_line:
                    hline = Span(location=y_ticks[-1] + counts.mean(),
                                 line_dash="dashed",
                                 line_color="black")
                    ax.add_layout(hline)
            if labels:
                ax.yaxis.axis_label = "Chain"
        elif kind == "vlines":
            ymin = np.full(len(all_counts), all_counts.mean())
            for idx, counts in enumerate(all_counts):
                ax.circle(bin_ary,
                          counts,
                          fill_color=colors[idx],
                          line_color=colors[idx])

                x_locations = [(bin, bin) for bin in bin_ary]
                y_locations = [(ymin[idx], counts_) for counts_ in counts]
                ax.multi_line(
                    x_locations,
                    y_locations,
                    line_dash="solid",
                    line_color=colors[idx],
                    line_width=3,
                )

            if ref_line:
                hline = Span(location=all_counts.mean(),
                             line_dash="dashed",
                             line_color="black")
                ax.add_layout(hline)

        if labels:
            ax.xaxis.axis_label = "Rank (all chains)"

            ax.yaxis.ticker = FixedTicker(ticks=y_ticks)
            ax.xaxis.major_label_overrides = dict(
                zip(map(str, y_ticks), map(str, range(len(y_ticks)))))

        else:
            ax.yaxis.major_tick_line_color = None
            ax.yaxis.minor_tick_line_color = None

            ax.xaxis.major_label_text_font_size = "0pt"
            ax.yaxis.major_label_text_font_size = "0pt"

        _title = Title()
        _title.text = make_label(var_name, selection)
        ax.title = _title

    show_layout(axes, show)

    return axes
Exemplo n.º 18
0
def _plot_ess(
    ax,
    plotters,
    xdata,
    ess_tail_dataset,
    mean_ess,
    sd_ess,
    idata,
    data,
    text_x,
    text_va,
    kind,
    extra_methods,
    rows,
    cols,
    figsize,
    kwargs,
    extra_kwargs,
    text_kwargs,
    _linewidth,
    _markersize,
    n_samples,
    relative,
    min_ess,
    xt_labelsize,
    titlesize,
    ax_labelsize,
    ylabel,
    rug,
    rug_kind,
    rug_kwargs,
    hline_kwargs,
    show,
):
    if ax is None:
        _, ax = _create_axes_grid(
            len(plotters),
            rows,
            cols,
            figsize=figsize,
            squeeze=False,
            constrained_layout=True,
            backend="bokeh",
        )
    for (var_name, selection, x), ax_ in zip(plotters, np.ravel(ax)):
        ax_.circle(np.asarray(xdata), np.asarray(x), size=6)
        if kind == "evolution":
            ax_.line(np.asarray(xdata), np.asarray(x), legend_label="bulk")
            ess_tail = ess_tail_dataset[var_name].sel(**selection)
            ax_.line(np.asarray(xdata),
                     np.asarray(ess_tail),
                     color="orange",
                     legend_label="tail")
            ax_.circle(np.asarray(xdata),
                       np.asarray(ess_tail),
                       size=6,
                       color="orange")
        elif rug:
            if rug_kwargs is None:
                rug_kwargs = {}
            if not hasattr(idata, "sample_stats"):
                raise ValueError(
                    "InferenceData object must contain sample_stats for rug plot"
                )
            if not hasattr(idata.sample_stats, rug_kind):
                raise ValueError(
                    "InferenceData does not contain {} data".format(rug_kind))

            rug_kwargs.setdefault("space", 0.1)
            _rug_kwargs = {}
            _rug_kwargs.setdefault("size", 8)
            _rug_kwargs.setdefault("line_color",
                                   rug_kwargs.get("line_color", "black"))
            _rug_kwargs.setdefault("line_width", 1)
            _rug_kwargs.setdefault("line_alpha", 0.35)
            _rug_kwargs.setdefault("angle", np.pi / 2)

            values = data[var_name].sel(**selection).values.flatten()
            mask = idata.sample_stats[rug_kind].values.flatten()
            values = rankdata(values)[mask]
            rug_space = np.max(x) * rug_kwargs.pop("space")
            rug_x, rug_y = values / (len(mask) -
                                     1), np.zeros_like(values) - rug_space

            glyph = Dash(x="rug_x", y="rug_y", **_rug_kwargs)
            cds_rug = ColumnDataSource({
                "rug_x": np.asarray(rug_x),
                "rug_y": np.asarray(rug_y)
            })
            ax_.add_glyph(cds_rug, glyph)

            hline = Span(
                location=0,
                dimension="width",
                line_color="black",
                line_width=_linewidth,
                line_alpha=0.7,
            )

            ax_.renderers.append(hline)

        if extra_methods:
            mean_ess_i = mean_ess[var_name].sel(**selection).values.item()
            sd_ess_i = sd_ess[var_name].sel(**selection).values.item()

            hline = Span(
                location=mean_ess_i,
                dimension="width",
                line_color="black",
                line_width=2,
                line_dash="dashed",
                line_alpha=1.0,
            )

            ax_.renderers.append(hline)

            hline = Span(
                location=sd_ess_i,
                dimension="width",
                line_color="black",
                line_width=1,
                line_dash="dashed",
                line_alpha=1.0,
            )

            ax_.renderers.append(hline)

        hline = Span(
            location=400 / n_samples if relative else min_ess,
            dimension="width",
            line_color="red",
            line_width=3,
            line_dash="dashed",
            line_alpha=1.0,
        )

        ax_.renderers.append(hline)

        title = Title()
        title.text = make_label(var_name, selection)
        ax_.title = title

        ax_.xaxis.axis_label = "Total number of draws" if kind == "evolution" else "Quantile"
        ax_.yaxis.axis_label = ylabel.format(
            "Relative ESS" if relative else "ESS")

    if show:
        grid = gridplot([list(item) for item in ax], toolbar_location="above")
        bkp.show(grid)

    return ax
Exemplo n.º 19
0
def plot_autocorr(
    axes,
    plotters,
    max_lag,
    figsize,
    rows,
    cols,
    combined,
    textsize,
    backend_config,
    backend_kwargs,
    show,
):
    """Bokeh autocorrelation plot."""
    if backend_config is None:
        backend_config = {}

    len_y = plotters[0][2].size
    backend_config.setdefault("bounds_x_range", (0, len_y))

    backend_config = {
        **backend_kwarg_defaults(("bounds_y_range", "plot.bokeh.bounds_y_range"),),
        **backend_config,
    }

    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"),),
        **backend_kwargs,
    }

    figsize, _, _, _, line_width, _ = _scale_fig_size(figsize, textsize, rows, cols)

    if axes is None:
        axes = create_axes_grid(
            len(plotters),
            rows,
            cols,
            figsize=figsize,
            sharex=True,
            sharey=True,
            backend_kwargs=backend_kwargs,
        )
    else:
        axes = np.atleast_2d(axes)

    data_range_x = DataRange1d(
        start=0, end=max_lag, bounds=backend_config["bounds_x_range"], min_interval=5
    )
    data_range_y = DataRange1d(
        start=-1, end=1, bounds=backend_config["bounds_y_range"], min_interval=0.1
    )

    for (var_name, selection, x), ax in zip(
        plotters, (item for item in axes.flatten() if item is not None)
    ):
        x_prime = x
        if combined:
            x_prime = x.flatten()
        y = autocorr(x_prime)

        ax.segment(
            x0=np.arange(len(y)),
            y0=0,
            x1=np.arange(len(y)),
            y1=y,
            line_width=line_width,
            line_color="black",
        )
        ax.line([0, 0], [0, max_lag], line_color="steelblue")

        title = Title()
        title.text = make_label(var_name, selection)
        ax.title = title
        ax.x_range = data_range_x
        ax.y_range = data_range_y

    show_layout(axes, show)

    return axes
Exemplo n.º 20
0
def plot():
    from pandas_datareader import data
    import datetime
    from bokeh.models.annotations import Title
    from bokeh.plotting import figure, show, output_file
    from bokeh.embed import components
    from bokeh.resources import CDN

    start = datetime.datetime(2019, 8, 16)
    end = datetime.datetime(2020, 1, 16)
    df = data.DataReader(name="AAPL",
                         data_source="yahoo",
                         start=start,
                         end=end)

    def increase_or_decrease(close, open):
        if close > open:
            value = "Increase"
        elif close < open:
            value = "Decrease"
        else:
            value = "Equal"
        return value

    df["Status"] = [
        increase_or_decrease(close, open)
        for close, open in zip(df.Close, df.Open)
    ]
    df["Middle"] = (df.Open + df.Close) / 2
    df["Height"] = abs(df.Close - df.Open)

    p = figure(x_axis_type='datetime',
               width=1000,
               height=300,
               sizing_mode='scale_width')
    title = Title()
    title.text = "Candlestick Chart"
    p.title = title
    p.grid.grid_line_alpha = 0.3

    hours_12 = 12 * 60 * 60 * 1000

    p.segment(df.index, df.Low, df.index, df.High, color="Black")

    p.rect(df.index[df.Status == "Increase"],
           df.Middle[df.Status == "Increase"],
           hours_12,
           df.Height[df.Status == "Increase"],
           fill_color="#27AF39",
           line_color="black")
    p.rect(df.index[df.Status == "Decrease"],
           df.Middle[df.Status == "Decrease"],
           hours_12,
           df.Height[df.Status == "Decrease"],
           fill_color="#DB1D1D",
           line_color="black")

    script1, div1 = components(p)
    cdn_js = CDN.js_files
    return render_template("plot.html",
                           script1=script1,
                           div1=div1,
                           cdn_js=cdn_js[0])
p2.yaxis.axis_label = 'Ось 2'
p2.xaxis.axis_label = 'временная ось 2'
# p2.yaxis.axis_label = 'Скорость'
# p2.xaxis.axis_label = 'время формирования точки на БВ'

legend1 = Legend(items=[
    ('Параметр 1', [aline]),
    ('Параметр 2', [bline]),
], location=(0, 250))

legend2 = Legend(items=[
    ('Параметр 3', [cline]),
    ('Параметр 4', [dline]),
], location=(0, 250))

t1 = Title()
t1.text = 'BOKEH_EXAMPLE_1_EMOTIONS'
p1.title = t1

t2 = Title()
t2.text = 'BOKEH_EXAMPLE_2_EMOTIONS'
p2.title = t2
# p2.title = t
p1.add_layout(legend1, 'left')
p2.add_layout(legend2, 'left')
# p2.add_layout(legend, 'left')
checkboxes1 = CheckboxGroup(labels=list(['Параметр 1', 'Параметр 2']),
                           active=[0, 1])
checkboxes2 = CheckboxGroup(labels=list(['Параметр 3', 'Параметр 4']),
                           active=[0, 1])
Exemplo n.º 22
0
def render_crossfilter(itmdt: Intermediate, plot_width: int, plot_height: int) -> column:
    """
    Render crossfilter scatter plot with a regression line.
    """

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

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

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

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )
    scatter = fig.scatter("__x__", "__y__", source=source_scatter)

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

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

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

        xyValueData['x'][0] = currentSelect;
        scatterData['__x__'] = scatterData[currentSelect];

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

        xyValueData['y'][0] = currentSelect;
        scatterData['__y__'] = scatterData[currentSelect];

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

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