Esempio n. 1
0
def utilization_bar(max_y):
    plot = Figure(
        plot_width=
        150,  # this is more for the ratio, because we have auto-width scaling
        plot_height=150,
        tools=[],  # no tools needed for this one
        title='Utilization')
    plot.toolbar.logo = None  # hides logo
    plot.x_range = Range1d(0, 1)
    plot.y_range = Range1d(
        0,
        max_y)  # sometimes you want it to be way less than 1, to see it move
    plot.xaxis.visible = False  # hide x axis
    # Add input buffer
    manager = Manager()
    plot._input_buffer = manager.dict()
    return plot
Esempio n. 2
0
def jwst_noise(result_dict, plot=True, output_file='noise.html'):
    """Plot background
    
    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo 
        make sure to restructure the input as a list of dictionaries without they key words 
        that run_pandexo assigns. 
    plot : bool 
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'noise.html'
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D noise (ppm)

    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_1d_flux, jwst_1d_snr, jwst_2d_det, jwst_2d_sat
    """
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"  #saturation

    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['error_w_floor'] * 1e6
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]
    ymed = np.median(y)

    plot_noise_1d1 = Figure(
        tools=TOOLS,  #responsive=True,
        x_axis_label='Wavelength (micron)',
        y_axis_label='Error on Spectrum (PPM)',
        title="Error Curve",
        plot_width=800,
        plot_height=300,
        y_range=[0, 2.0 * ymed])
    ymed = np.median(y)
    plot_noise_1d1.circle(x, y, line_width=4, alpha=.7)
    if plot:
        outputfile(output_file)
        show(plot_noise_1d1)
    return x, y
Esempio n. 3
0
def view_database_file(_id, file_type):

    ds = load_file(_id, file_type)
    d = {}
    for data_var in ds.data_vars:
        d[data_var] = [ds[data_var].values]
    d["to_plot"] = [ds[list(ds.data_vars)[0]].values]
    source = ColumnDataSource(d)

    callback = CustomJS(
        args=dict(source=source),
        code="""
        var data = source.data;
        data['to_plot'] = data[cb_obj.value];
        source.change.emit();
    """,
    )
    select = Select(title="Variable:", options=list(ds.data_vars))
    select.js_on_change("value", callback)

    p = Figure(
        x_range=(-180, 180),
        y_range=(-90, 90),
        aspect_ratio=2.5,
        tools="pan,wheel_zoom,box_zoom,reset, hover",
    )
    p.sizing_mode = "scale_width"
    p.image(
        image="to_plot",
        x=-180,
        y=-90,
        dw=360,
        dh=180,
        source=source,
        palette="Viridis11",
    )
    script, div = components(
        column(column(select), p, sizing_mode="stretch_width"))

    return render_template(
        "app/bokeh_plot.html",
        script=script,
        div=div,
        data_file_id=_id,
        title=file_type.capitalize(),
    )
Esempio n. 4
0
def create_ramp_legend(agg, cmap, how='linear', width=600):
    '''
    Helper function to create a Bokeh ``Figure`` object
    with a color ramp corresponding to input aggregate and transfer function.

    Parameters
    ----------
    agg : xarray
        Datashader aggregate object (e.g. result of Canvas.points())

    cmap : list of colors or matplotlib.colors.Colormap, optional
        The colormap to use. Can be either a list of colors (in any of the
        formats described above), or a matplotlib colormap object.

    how : str
        Datashader transfer function name (either linear or log)

    width : int
        Width in pixels of resulting legend figure (default=600)
    '''

    vals_arr, min_val, max_val = summarize_aggregate_values(agg, how=how)
    img = tf.shade(vals_arr, cmap=cmap, how=how)
    x_axis_type = how
    assert x_axis_type == 'linear' or x_axis_type == 'log'
    legend_fig = Figure(x_range=(min_val, max_val),
                        plot_height=50,
                        plot_width=width,
                        lod_threshold=None,
                        toolbar_location=None,
                        y_range=(0, 18),
                        x_axis_type=x_axis_type)

    legend_fig.min_border_top = 0
    legend_fig.min_border_bottom = 10
    legend_fig.min_border_left = 15
    legend_fig.min_border_right = 15
    legend_fig.yaxis.visible = False
    legend_fig.grid.grid_line_alpha = 0
    legend_fig.image_rgba(image=[img.values],
                          x=[min_val],
                          y=[0],
                          dw=[max_val - min_val],
                          dh=[18],
                          dw_units='screen')
    return legend_fig
Esempio n. 5
0
def _internal_bokeh(doc, example=None):
    moduleview = inspect.getsource(sys.modules[__name__])

    # Note: if launched by package, the result of _internal_example is passed via kwargs
    ddmodel1 = example[0]
    ddmodel2 = example[1]

    # Debug Bokeh Figure
    debug_fig = Figure(
        title="Random Test",
        plot_height=480,
        tools="pan, xwheel_zoom, reset",
        toolbar_location="left",
        y_axis_location="right",
        x_axis_type="datetime",
        sizing_mode="scale_width",
    )
    # TODO : use DataView.plot instead...
    # dynamic datasource plots as simply as possible
    debug_fig.line(
        x="index",
        y="random1",
        color="blue",
        source=ddmodel1.source,
        legend_label="Patch+Stream",
    )
    debug_fig.line(
        x="index",
        y="random2",
        color="red",
        source=ddmodel2.source,
        legend_label="Stream",
    )

    doc.add_root(
        layout(
            [[  # we want one row with two columns
                [PreText(text=moduleview)],  # TODO : niceties like pygments ??
                [
                    # to help compare / visually debug
                    debug_fig,
                    ddmodel1.view.table,
                    ddmodel2.view.table,
                ],
            ]], ))
Esempio n. 6
0
def calc_volatility(df,
                    returnFunc,
                    min_periods=75,
                    template_name='volatility',
                    notebook=False,
                    xlabel='Date',
                    ylabel='Volatility',
                    title='AAPL Volatility of Daily Returns'):
    """
    Bokeh plot for computed volatility of stock return price
    min_periods: Define the minumum of periods to consider
    template_name: output file name of plot
    notebook: boolean for showing plot on jupyter notebook
    """
    pct_change = returnFunc(df['Adj. Close'])

    # create a new plot with a title and axis labels
    p = Figure(title=title,
               x_axis_label=xlabel,
               y_axis_label=ylabel,
               x_axis_type='datetime',
               plot_height=500,
               plot_width=950,
               tools=['pan', 'wheel_zoom'],
               toolbar_location='below')

    # configure so that Bokeh chooses what (if any) scroll tool is active
    p.toolbar.active_scroll = "auto"

    # Calculate the volatility
    vol = pct_change.rolling(min_periods).std() * np.sqrt(min_periods)

    # add a line renderer with legend and line thickness
    p.line(vol.index, vol, line_width=2, legend='Volatility')
    p.legend.location = "top_left"
    p.legend.click_policy = "hide"

    if notebook:
        # show the results
        show(p, notebook_handle=True)
        push_notebook()
    else:
        # output the results
        output_file('%s.html' % template_name)
        save(p)
Esempio n. 7
0
    def make_plot(self):
        """Time series plot with a hover and other bokeh tools.
        """
        self.plot = Figure(x_axis_type="datetime",
                           tools="pan, wheel_zoom, xbox_zoom, \
                                  save, reset, tap",
                           active_scroll="wheel_zoom")

        self.plot.x_range.follow = 'end'
        self.plot.x_range.range_padding = 0
        self.plot.xaxis.axis_label = 'Time (UTC)'

        hover = HoverTool(tooltips=[("Time (UTC)", "@date_created"),
                                    ("CI ID", "@ci_id"),
                                    ("Metric measurement", "@formatted_value"),
                                    ("Filter", "@filter_name"),
                                    ("# of packages changed", "@count")])

        self.plot.add_tools(hover)

        self.plot.line(x='time', y='value', color='gray',
                       legend='filter_name', source=self.cds)

        self.plot.circle(x='time', y='value',
                         color='color', legend='filter_name',
                         source=self.cds, fill_color='white',
                         size=12)

        # Legend
        self.plot.background_fill_alpha = 0
        self.plot.legend.location = 'top_right'
        self.plot.legend.click_policy = 'hide'
        self.plot.legend.orientation = 'horizontal'

        # Toolbar
        self.plot.toolbar.logo = None

        self.status = Label(x=350, y=75, x_units='screen', y_units='screen',
                            text="", text_color="lightgray",
                            text_font_size='24pt',
                            text_font_style='normal')

        self.plot.add_layout(self.status)

        self.update_plot()
Esempio n. 8
0
def render_correlation(
    itmdt: Intermediate,
    plot_width: int = 400,
    plot_height: int = 400,
    palette: Optional[Sequence[str]] = None,
) -> Figure:
    """
    Render a correlation plot

    Parameters
    ----------
    itmdt
    plot_width
        The width of the plot
    plot_height
        The height of the plot
    palette
        The palette to use. By default (None),
        the palette will be automatically chosen based on different visualization types.

    Returns
    -------
    Figure
        The bokeh Figure instance.
    """
    if itmdt.visual_type is None:
        visual_elem = Figure()
    elif itmdt.visual_type == "correlation_impact":
        visual_elem = render_correlation_impact(itmdt, plot_width, plot_height,
                                                palette or RDBU)
    elif itmdt.visual_type == "correlation_heatmaps":
        visual_elem = render_correlation_heatmaps(itmdt, plot_width,
                                                  plot_height, palette or RDBU)
    elif itmdt.visual_type == "correlation_single_heatmaps":
        visual_elem = render_correlation_single_heatmaps(
            itmdt, plot_width, plot_height, palette or RDBU)
    elif itmdt.visual_type == "correlation_scatter":
        visual_elem = render_scatter(itmdt, plot_width, plot_height, palette
                                     or BRG)
    elif itmdt.visual_type == "correlation_crossfilter":
        visual_elem = render_crossfilter(itmdt, plot_width, plot_height)
    else:
        raise NotImplementedError(f"Unknown visual type {itmdt.visual_type}")

    return visual_elem
Esempio n. 9
0
    def make_plot(source, title):
        print("make plot")
        plot = Figure(x_axis_type="datetime",
                      plot_width=1000,
                      tools="",
                      toolbar_location=None)
        plot.title = title
        colors = Blues4[0:3]

        plot.quad(top='record_max_temp',
                  bottom='record_min_temp',
                  left='left',
                  right='right',
                  color=colors[2],
                  source=source,
                  legend="Record")
        plot.quad(top='average_max_temp',
                  bottom='average_min_temp',
                  left='left',
                  right='right',
                  color=colors[1],
                  source=source,
                  legend="Average")
        plot.quad(top='actual_max_temp',
                  bottom='actual_min_temp',
                  left='left',
                  right='right',
                  color=colors[0],
                  alpha=0.5,
                  line_color="black",
                  source=source,
                  legend="Actual")

        # fixed attributes
        plot.border_fill_color = "whitesmoke"
        plot.xaxis.axis_label = None
        plot.yaxis.axis_label = "Temperature (F)"
        plot.axis.major_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_style = "bold"
        plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
        plot.grid.grid_line_alpha = 0.3
        plot.grid[0].ticker.desired_num_ticks = 12

        return plot
Esempio n. 10
0
    def create_fig(self, sources):
        """
        Class implementation of :class:`.LivePlot.create_fig`.

        """

        self._sample_rate = 32000 #<-- just a default sample rate to use until something is read from the get_spectrum callable
        self._freq=0
        fig = Figure(logo=None, **self._fig_args)

        fig.line(source=sources['freq'], x='x', y = 'y')
        fig.xaxis.axis_label = "Frequency (MHz)"
        if self._fig_title is not None:
            fig.title.text = self._fig_title

        fig.x_range.range_padding = 0

        return(fig)
Esempio n. 11
0
    def __init__(self,
                 environment: Environment,
                 statistics: [dict],
                 snapshot_interval=100):
        self.environment = environment
        self.statistics = statistics
        self.number_of_statistics = len(statistics)

        self.data_sources = []
        self.graph = Figure(plot_width=600, plot_height=200)
        self.set_up_graph_lines()

        self.graph.x_range.follow = "end"
        self.graph.x_range.follow_interval = 50

        self.snapshot_interval = snapshot_interval

        self.environment.add_data_callback(self.upload_iteration)
Esempio n. 12
0
    def empty_figure() -> Figure:
        # If no data to render in the heatmap, i.e. no missing values
        # we render a blank heatmap
        fig = Figure(
            x_range=[],
            y_range=[],
            plot_width=plot_width,
            plot_height=plot_height,
            x_axis_location="below",
            tools="hover",
            toolbar_location=None,
            background_fill_color="#fafafa",
        )

        # Add at least one renderer to fig, otherwise bokeh
        # gives us error -1000 (MISSING_RENDERERS): Plot has no renderers
        fig.rect(x=0, y=0, width=0, height=0)
        return fig
Esempio n. 13
0
def make_plot(src, city):
    plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None)
    plot.title = city
    colors = Blues4[0:3]
    plot.line(x='date', y='GDD',source=src)
#    plot.quad(top='max', bottom='min', left='left', right='right', color=colors[2], source=src, legend="Record")

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = None
    plot.yaxis.axis_label = "Accumulated GDD"
    plot.axis.major_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12

    return plot
Esempio n. 14
0
def create_arima_plot(
        df_history: pd.DataFrame,
        model_data: arima.MODEL_DATA
) -> Figure:
    """
    Plot the fitting data for the specified model

    :param df_history:
        The historical data that was fitted by the ARIMA model
    :param model_data:
        The MODEL_DATA instance to plot
    """

    results = model_data.results

    figure = Figure()
    figure.xaxis.axis_label = 'Year'
    figure.yaxis.axis_label = 'Temperature (Celsius)'

    df = df_history.sort_values(by='order')
    order = df['order']
    add_to_arima_plot(
        figure,
        order,
        df['temperature'].values,
        'Data',
        'blue'
    )

    add_to_arima_plot(
        figure,
        order,
        results.fittedvalues,
        'Model',
        'red'
    )

    figure.title = '({p}, {d}, {q}) RMSE: {rmse:0.4f}'.format(
        **model_data._asdict()
    )

    figure.legend.location = 'bottom_left'

    return figure
Esempio n. 15
0
def jwst_1d_flux(result_dict, plot=True, output_file='flux.html'):
    """Plot flux rate in e/s

    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo
        make sure to restructure the input as a list of dictionaries without they key words
        that run_pandexo assigns.
    plot : bool
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'flux.html'
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D flux rate in electrons/s

    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_noise, jwst_1d_snr, jwst_2d_det, jwst_2d_sat
    """
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    out = result_dict['PandeiaOutTrans']

    # Flux 1d
    x, y = out['1d']['extracted_flux']
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]

    plot_flux_1d1 = Figure(tools=TOOLS,
                           x_axis_label='Wavelength [microns]',
                           y_axis_label='Flux (e/s)',
                           title="Out of Transit Flux Rate",
                           plot_width=800,
                           plot_height=300)
    plot_flux_1d1.line(x, y, line_width=4, alpha=.7)

    if plot:
        outputfile(output_file)
        show(plot_flux_1d1)
    return x, y
Esempio n. 16
0
def multi_plot(figure_info, source):

    fig = Figure(plot_width=figure_info["plot_width"],
                 plot_height=figure_info["plot_height"],
                 title=figure_info["title"],
                 x_axis_type="datetime")

    fig.extra_y_ranges = {
        "foo": Range1d(start=0, end=figure_info["max_unemployment"])
    }
    fig.add_layout(LinearAxis(y_range_name="foo"), 'right')

    for idx in range(1, len(figure_info["names"])):
        legend_name = str(figure_info["legends"][idx - 1]) + " "

        if "Unem" not in figure_info["names"][idx]:

            fig.vbar(source=source,
                     x=figure_info["names"][0],
                     top=figure_info["names"][idx],
                     bottom=0,
                     width=1000000000,
                     color=figure_info["colors"][idx - 1],
                     fill_alpha=0.2,
                     line_alpha=0.1,
                     legend=legend_name)

        else:

            fig.line(source=source,
                     x=figure_info["names"][0],
                     y=figure_info["names"][idx],
                     line_width=figure_info["line_widths"][idx - 1],
                     alpha=figure_info["alphas"][idx - 1],
                     color=figure_info["colors"][idx - 1],
                     legend=legend_name,
                     y_range_name="foo")

    fig.legend.location = figure_info["legend_location"]
    fig.xaxis.axis_label = figure_info["xaxis_label"]
    fig.yaxis.axis_label = figure_info["yaxis_label"]
    fig.title.align = figure_info["title_align"]

    return fig
Esempio n. 17
0
def pie_viz(
    df: pd.DataFrame,
    col: str,
    miss_pct: float,
    plot_width: int,
    plot_height: int,
) -> Panel:
    """
    Render a pie chart
    """
    title = f"{col} ({miss_pct}% missing)" if miss_pct > 0 else f"{col}"
    tooltips = [(f"{col}", "@col"), ("Count", "@cnt"),
                ("Percent", "@pct{0.2f}%")]
    df["angle"] = df["cnt"] / df["cnt"].sum() * 2 * pi
    fig = Figure(
        title=title,
        plot_width=plot_width,
        plot_height=plot_height,
        tools="hover",
        toolbar_location=None,
        tooltips=tooltips,
    )
    color_list = PALETTE * (len(df) // len(PALETTE) + 1)
    df["colour"] = color_list[0:len(df)]
    if df.iloc[-1]["cnt"] == 0:  # no "Others" group
        df = df[:-1]
    pie = fig.wedge(
        x=0,
        y=1,
        radius=0.9,
        start_angle=cumsum("angle", include_zero=True),
        end_angle=cumsum("angle"),
        line_color="white",
        fill_color="colour",
        source=df,
    )
    legend = Legend(
        items=[LegendItem(label=dict(field="col"), renderers=[pie])])
    legend.label_text_font_size = "8pt"
    fig.add_layout(legend, "right")
    tweak_figure(fig, "pie")
    fig.axis.major_label_text_font_size = "0pt"
    fig.axis.major_tick_line_color = None
    return Panel(child=fig, title="pie chart")
Esempio n. 18
0
def render_dist(
    df: pd.DataFrame,
    x: str,
    typ: str,
    plot_width: int,
    plot_height: int,
) -> Figure:
    """
    Render a distribution, CDF or PDF
    """
    assert typ in ["pdf", "cdf"]
    tooltips = [
        (x, "@x"),
        (typ.upper(), f"@{{{typ}}}"),
        ("Label", "@label"),
    ]
    y_range = Range1d(0, df[typ].max() * 1.01)
    x_range = Range1d(0, df["x"].max() * 1.01)

    fig = tweak_figure(
        Figure(
            x_range=x_range,
            y_range=y_range,
            plot_width=plot_width,
            plot_height=plot_height,
            tools="hover",
            toolbar_location=None,
            tooltips=tooltips,
        )
    )
    for idx, label in enumerate(LABELS):
        group = df[df["label"] == label]
        fig.line(
            x="x",
            y=typ,
            source=group,
            color=CATEGORY10[idx],
            legend_label=label,
        )

    relocate_legend(fig, "left")

    return fig
Esempio n. 19
0
def jwst_2d_det(result_dict, plot=True, output_file='det2d.html'):
    """Plot 2d detector image

    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo
        make sure to restructure the input as a list of dictionaries without they key words
        that run_pandexo assigns.

    plot : bool
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'det2d.html'

    Return
    ------
    numpy array
        2D array of out of transit detector simulation
    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_1d_flux, jwst_1d_snr, jwst_noise, jwst_2d_sat

    """
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    out = result_dict['PandeiaOutTrans']
    data = out['2d']['detector']


    xr, yr = data.shape

    plot_detector_2d = Figure(tools="pan,wheel_zoom,box_zoom,reset,hover,save",
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="2D Detector Image",
                        plot_width=800, plot_height=300)

    plot_detector_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")
    if plot:
        outputfile(output_file)
        show(plot_detector_2d)
    return data
Esempio n. 20
0
def main():
    state_xs, state_ys = get_us_state_outline()
    left, right = minmax(state_xs)
    bottom, top = minmax(state_ys)
    plot = Figure(title=TITLE, plot_width=1000,
                  plot_height=700,
                  tools="pan, wheel_zoom, box_zoom, reset",
                  x_range=Range1d(left, right),
                  y_range=Range1d(bottom, top),
                  x_axis_label='Longitude',
                  y_axis_label='Latitude')

    plot_state_outline(plot, state_xs, state_ys)

    density_overlay = DensityOverlay(plot, left, right, bottom, top)
    density_overlay.draw()

    grid_slider = Slider(title="Details", value=density_overlay.gridcount,
                         start=10, end=100, step=10)
    grid_slider.on_change("value", density_overlay.grid_change_listener)

    radiance_slider = Slider(title="Min. Radiance",
                             value=density_overlay.radiance,
                             start=np.min(density_overlay.rad),
                             end=np.max(density_overlay.rad), step=10)
    radiance_slider.on_change("value", density_overlay.radiance_change_listener)

    listener = ViewListener(plot, density_overlay, name="viewport")

    plot.x_range.on_change("start", listener)
    plot.x_range.on_change("end", listener)
    plot.y_range.on_change("start", listener)
    plot.y_range.on_change("end", listener)

    backends = ["CPU", "HSA"]
    default_value = backends[kde.USE_HSA]
    backend_select = Select(name="backend", value=default_value,
                            options=backends)
    backend_select.on_change('value', density_overlay.backend_change_listener)

    doc = curdoc()
    doc.add(VBox(children=[plot, grid_slider, radiance_slider, backend_select]))
    doc.add_periodic_callback(density_overlay.periodic_callback, 0.5)
    def _replacement_plot(self, source):
        start = self.now - datetime.timedelta(days=self.RECOATING_PERIOD)
        start_timestamp = datetime.datetime(start.year, start.month, start.day, 0, 0, 0, 0).timestamp()
        end_timestamp = datetime.datetime(self.now.year, self.now.month, self.now.day, 0, 0, 0, 0).timestamp()
        x_range = DataRange1d(start=1000 * start_timestamp, end=1000 * end_timestamp)
        y_range = DataRange1d(start=0, end=120)
        plot = Figure(x_axis_type='datetime',
                      x_range=x_range,
                      y_range=y_range,
                      tools=['tap'],
                      toolbar_location=None)

        # required recoated segments
        plot.line(x=[start, self.now],
                  y=[0, 91],
                  legend='required recoated segments',
                  line_width=2,
                  line_color='blue')

        # recoated segments
        plot.line(x='ReplacementDate',
                  y='RecoatingsSinceYearStart',
                  source=source,
                  legend='recoated segments',
                  line_width=2,
                  color='orange')
        plot.circle(x='ReplacementDate',
                    y='RecoatingsSinceYearStart',
                    source=source,
                    legend='recoated segments',
                    size=6,
                    color='orange')

        date_format = '%d %b %Y'
        formats = dict(hours=[date_format], days=[date_format], months=[date_format], years=[date_format])
        plot.xaxis[0].formatter = DatetimeTickFormatter(formats=formats)

        plot.legend.location = 'top_left'

        plot.min_border_top = 20
        plot.min_border_bottom = 30

        return plot
Esempio n. 22
0
File: main.py Progetto: zlxs23/bokeh
def create_plot():
    axis_range = [-10000000, 10000000]
    x_range = Range1d(start=axis_range[0], end=axis_range[1], bounds=None)
    y_range = Range1d(start=axis_range[0], end=axis_range[1], bounds=None)
    p = Figure(tools='pan,wheel_zoom',
               x_range=x_range,
               y_range=y_range,
               plot_height=800,
               plot_width=800)
    p.axis.visible = False
    tile_source = RandomTileSource()
    tile_source.urls = []
    tile_source.attribution = STAMEN_TONER.attribution
    tile_source.urls.append(STAMEN_TONER.url)
    tile_source.urls.append('http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png')
    tile_source.urls.append(
        'http://otile1.mqcdn.com/tiles/1.0.0/sat/{Z}/{X}/{Y}.jpg')
    p.add_tile(tile_source)
    return p
Esempio n. 23
0
    def make_plot(source, title):
        plot = Figure(plot_width=800,
                      plot_height=600,
                      tools="",
                      toolbar_location=None)
        plot.title.text = title
        colors = Blues4[0:3]

        plot.scatter(x=x, y=y, source=source)
        plot.multi_line('ci_x', 'ci', source=source)

        # fixed attributes
        plot.xaxis.axis_label = xlabel
        plot.yaxis.axis_label = ylabel
        plot.axis.major_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_style = "bold"

        return plot
Esempio n. 24
0
def jwst_1d_snr(result_dict, plot=True, output_file='snr.html'):
    """Plot SNR

    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo
        make sure to restructure the input as a list of dictionaries without they key words
        that run_pandexo assigns.
    plot : bool
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'snr.html'

    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D SNR

    See Also
    --------
    jwst_1d_bkg, jwst_noise, jwst_1d_flux, jwst_1d_spec, jwst_2d_det, jwst_2d_sat
    """
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    # Flux 1d
    x = result_dict['RawData']['wave']
    electrons_out = result_dict['RawData']['electrons_out']
    y = electrons_out / np.sqrt(result_dict['RawData']['var_out'])
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]
    plot_snr_1d1 = Figure(tools=TOOLS,
                          x_axis_label='Wavelength (micron)',
                          y_axis_label='SNR',
                          title="SNR Out of Trans",
                          plot_width=800,
                          plot_height=300)
    plot_snr_1d1.line(x, y, line_width=4, alpha=.7)
    if plot:
        outputfile(output_file)
        show(plot_snr_1d1)
    return x, y
Esempio n. 25
0
def create_dual_light_curve_figure(fluxes0, times0, name0, fluxes1, times1, name1, title, x_axis_label='Time (days)',
                                  y_axis_label='Relative flux') -> Figure:
    """
    Plots two light curves together. Mostly for comparing a light curve cleaned by two different methods.

    :param fluxes0: The fluxes of the first plot.
    :param times0: The times of the first plot.
    :param name0: The name of the first plot.
    :param fluxes1: The fluxes of the second plot.
    :param times1: The times of the second plot.
    :param name1: The name of the second plot.
    :param title: The title of the figure.
    :param x_axis_label: The label of the x axis.
    :param y_axis_label: The label of the y axis.
    :return: The resulting figure.
    """
    figure = Figure(title=title, x_axis_label=x_axis_label, y_axis_label=y_axis_label, active_drag='box_zoom')
    add_light_curve(figure, times0, fluxes0, name0, 'firebrick')
    add_light_curve(figure, times1, fluxes1, name1, 'mediumblue')
    return figure
Esempio n. 26
0
    def _create_title_fig(self):
        fig = Figure(sizing_mode='scale_width',
                     x_range=[0, 1], y_range=[0, 1], plot_height=50, tools="")

        # Remove existing axes and grid
        fig.xgrid.grid_line_color = None
        fig.ygrid.grid_line_color = None
        fig.axis.visible = False
        fig.background_fill_color = None
        fig.toolbar_location = None

        text = Label(x=0.5, y=0.5,
                     text=self._title_text, render_mode='css',
                     background_fill_color='white', background_fill_alpha=1.0,
                     text_font_size='28pt', text_align='center', text_baseline='middle'
                     )

        fig.add_layout(text)

        return (fig)
Esempio n. 27
0
def render(df: pd.DataFrame) -> Figure:
    from bokeh.models import HoverTool
    from bokeh.palettes import Category10_10
    from bokeh.plotting import ColumnDataSource
    p = Figure(plot_width=1200, plot_height=600, x_axis_type='datetime')
    names = [x for x in df.columns.tolist() if x not in ('date', 'zeros')]
    source = ColumnDataSource(df)
    p.varea_stack(stackers=names,
                  x='date',
                  color=Category10_10[:len(names)],
                  legend_label=names,
                  source=source)
    p.line(x='date', y='zeros', line_alpha=0, source=source)
    p.legend.location = 'top_left'
    p.add_tools(
        HoverTool(tooltips=[('date', '@date{%Y-%m-%d}')] + [(x, f'@{x}')
                                                            for x in names],
                  formatters={'@date': 'datetime'},
                  mode='vline'))
    return p
    def construct_best_odds_figure(self, x, y, z, t, trade_id, sticker):
        # workaround to format date in the hover tool at the moment bokeh does not supported in the tool tips
        source_back_odds = ColumnDataSource(data=dict(x=x, y=y, time=[e.strftime('%d-%m-%Y %H:%M:%S') for e in x]))

        hover = HoverTool(
            tooltips=[
                ("index", "$index"),
                ("x", "@time"),
                ("y", "@y"),
            ],
            active=False
        )

        # create a new plot with a a datetime axis type
        p2 = Figure(plot_width=1000, plot_height=600, title=sticker, toolbar_location="above", x_axis_type="datetime",
                    tools=[hover, 'box_zoom, box_select, crosshair, resize, reset, save,  wheel_zoom'])
        orders = self.map_trade_id_to_orders[trade_id, sticker]
        for order in orders:
            a = [order.placed_dt]
            b = [order.price]
            source_placed = ColumnDataSource(data=dict(a=a, b=b, time=[a[0].strftime('%d-%m-%Y %H:%M:%S')]))
            p2.square(a, b, legend="placed", fill_color="red", line_color="red", size=8, source=source_placed)

        p2.circle(x, y, size=8, color='navy', alpha=0.2, legend="best back odds", source=source_back_odds)
        p2.line(x, y, color='navy', legend="best back odds", source=source_back_odds)

        # lay odds
        source_lay_odds = ColumnDataSource(data=dict(z=z, t=t, time=[e.strftime('%d-%m-%Y %H:%M:%S') for e in z]))
        p2.triangle(z, t, size=8, color='green', alpha=0.2, legend="best lay odds", source=source_lay_odds)
        p2.line(z, t, color='green', legend="best lay odds", source=source_lay_odds)

        # NEW: customize by setting attributes
        # p2.title = sticker
        p2.legend.location = "top_left"
        p2.grid.grid_line_alpha = 0
        p2.xaxis.axis_label = 'Date'
        p2.yaxis.axis_label = "Best odds"
        p2.ygrid.band_fill_color = "olive"
        p2.ygrid.band_fill_alpha = 0.1

        return p2
Esempio n. 29
0
def dataViewer_4():
    # dataset_name = session('dataset_name')
    dataset_name = None

    if dataset_name == None:
        dataset_name = 'Aids2'

    if type(data(dataset_name)) != pd.core.frame.DataFrame:
        return ('Bad dataset name:{dataset_name}')

    # get dframe by name
    df = data(dataset_name)
    # Create a ColumnDataSource object

    bp_df = ColumnDataSource(df)
    # Create plot as a bokeh.figure object
    plot = Figure(height=400, width=400, title=dataset_name)

    x_ax = [str(i) for i in range(df.shape[0])]
    palette_ = Spectral11[0:len(df.columns)]

    for n, cname in enumerate(df.columns):
        plot.line(x=x_ax,
                  y=list(df[cname].values),
                  color=palette_[n],
                  legend='line')

    # grab the static resources
    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    # render template
    script, div = components(plot)
    html = render_template(
        'index_.html',
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
    )
    return encode_utf8(html)
Esempio n. 30
0
def make_plot(source,AverageTemp,Parcentile_5_Min,Parcentile_5_Max,Parcentile_25_Min,Parcentile_25_Max,MinTemp,MaxTemp,plotDate,cityName):
    plot = Figure(title='Optional Task # 1 : Growing Degree-day for '+cityName, x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools="", toolbar_location=None)
    colors = Blues4[0:3]
    
    plot.circle(MaxTemp,MinTemp, alpha=0.9, color="#66ff33", fill_alpha=0.2, size=10,source=source,legend ='2015')
    plot.quad(top=Parcentile_5_Max, bottom=Parcentile_5_Min, left='left',right='right',
              source=source,color="#e67300", legend="Percentile 5-95")
    plot.quad(top=Parcentile_25_Max, bottom=Parcentile_25_Min,left='left',right='right',
              source=source,color="#66ccff",legend="percentile 25-75")
    plot.line(plotDate,AverageTemp,source=source,line_color='Red', line_width=0.75, legend='AverageTemp')

    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Temperature (C)"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12
    return plot