Ejemplo n.º 1
0
def gen_bokeh_plot():
    # retrieve current active symbol and data source
    data_source = DATA_STORE['data_source']
    title_source = DATA_STORE['title_source']

    # calculate mean absolute deviation (MAD)
    title = Title(text='Predicted vs Actual Market Open Price')

    plot = Plot(title=title,
                plot_width=1200,
                plot_height=800,
                h_symmetry=False,
                v_symmetry=False,
                min_border=0,
                toolbar_location='right')

    val_glyph = Line(x='date',
                     y='val_open',
                     line_color='black',
                     line_width=1.5)
    pred_glyph = Line(x='date',
                      y='pred_open',
                      line_color='blue',
                      line_width=1.5,
                      line_dash='dashed')
    plot.add_glyph(data_source, val_glyph)  # renderer 0
    plot.add_glyph(data_source, pred_glyph)  # renderer 1

    text_glyph = Text(x='x', y='y', text='text')
    plot.add_glyph(title_source, text_glyph)

    # Format plot
    li1 = LegendItem(label='actual', renderers=[plot.renderers[0]])
    li2 = LegendItem(label='predicted', renderers=[plot.renderers[1]])
    legend1 = Legend(items=[li1, li2], location='top_right')
    plot.add_layout(legend1)

    xaxis = DatetimeAxis()
    xaxis.formatter = DatetimeTickFormatter(years=['%Y'],
                                            months=['%m/%Y'],
                                            days=['%d/%m/%Y'])
    xaxis.major_label_orientation = np.pi / 4
    plot.add_layout(xaxis, 'below')

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

    return plot
Ejemplo n.º 2
0
    def __init__(self,**kwargs):
        super(WeatherPlot,self).__init__(**kwargs)

    # def __init__(self,
    #              data,
    #              column_names=cs.column_names_weewx,
    #              column_time=cs.time_column_name_weewx,
    #              plot_height=300,
    #              plot_width=800,
    #              border_left=150,
    #              **kwargs):
    #     if "tool_events" not in kwargs:
    #         kwargs["tool_events"] = ToolEvents()
    #     super(WeatherPlot,self).__init__(x_range=DataRange1d(),
    #                                      y_range=DataRange1d(),
    #                                      plot_width=800,
    #                                      plot_height=500,
    #                                      min_border_left=150,
    #                                      **kwargs)

        time_int = 3600
        t_max = int(time.time())
        t_min = t_max - 3600 * 24
        data = sql_con.get_data_ws(time_int=time_int,
                                           t_max=t_max,
                                           t_min=t_min)
        self._data = data
        column_names=cs.column_names_weewx
        column_time=cs.time_column_name_weewx
        data_seconds = data
        data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000
        add_glyphs_to_plot(column_names, column_time, data_seconds, self)
        self.add_layout(DatetimeAxis(), 'below')
        self.add_tools(PanTool(), WheelZoomTool(), ResizeTool(), CrosshairTool())
Ejemplo n.º 3
0
def make_plot():
    xdr = DataRange1d()
    ydr = DataRange1d()

    plot = Plot(title="Product downloads",
                x_range=xdr,
                y_range=ydr,
                plot_width=400,
                plot_height=400)

    line = Line(x="dates", y="downloads", line_color="blue")
    plot.add_glyph(source, line)

    circle = Circle(x="dates", y="downloads", fill_color="red")
    plot.add_glyph(source, circle)

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

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

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    plot.add_tools(HoverTool(tooltips=dict(downloads="@downloads")))

    return plot, source
def pages_queried_timeseries(df, plot_width=600, plot_height=200, rule='1T'):
    ts = df[['url']].resample(rule, how='count').cumsum()
    ts.index = ts.index.tz_convert(tzlocal())
    #Bokeh=0.10.0 misencodes timestamps, so we have to shift by
    ts.index = ts.index.shift(ts.index[0].utcoffset().total_seconds(), freq="S")
    ts = pd.concat([ts[:1], ts]) # prepend 0-value for Line chart compat
    ts.iloc[0]['url'] = 0

    formatter = DatetimeTickFormatter(formats=DATETIME_FORMAT)
    ticker = DatetimeTicker(desired_num_ticks=3)

    source = ColumnDataSource(ts)

    plot = Plot(plot_width=plot_width, plot_height=plot_height,
                x_range=DataRange1d(range_padding=0.1),
                y_range=DataRange1d(start=0),
                **PLOT_FORMATS)
    plot.add_glyph(
        source,
        Line(x='retrieved', y='url', **LINE_FORMATS)
    )
    plot.add_layout(
        DatetimeAxis(axis_label="Date Retrieved", formatter=formatter,
                     ticker=ticker, **AXIS_FORMATS),
        'below')
    plot.add_layout(LinearAxis(axis_label="Total Pages", **AXIS_FORMATS), 'left')

    return plot
Ejemplo n.º 5
0
def plot_choiceset_links(linkfile_df,cost="sim_cost",paths=False):
    
    linkfile_df["color"]= map(assignColorByMode, linkfile_df["mode"])
    if paths:
        linkfile_df["annotation"]= map(createLinkPathAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"], linkfile_df["probability"])
    else:
        linkfile_df["annotation"]=map(createLinkAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"])
    

    linkfile_df["yloc"]= map(yloc, linkfile_df["pathnum"],linkfile_df["linknum"])
    pathnums = list(set(list(linkfile_df["pathnum"])))
    plots = {}
    for p in pathnums:
        data_df = linkfile_df[linkfile_df["pathnum"]==p]
        linksource = ColumnDataSource(data_df)

        xdr2 = DataRange1d()
        ydr2 = DataRange1d()

        plots[p] = Plot(
            title="Path Number: %d    Probability: %4.2f Percent" % (p,100*data_df["probability"].max()), x_range=xdr2, y_range=ydr2, plot_width=800, plot_height=150,
            h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

        glyph = Segment(y0="yloc", x0="new_A_time", y1="yloc", x1="new_B_time", line_color="color", line_width=cost)
        plots[p].add_glyph(linksource, glyph)

        choicexaxis = DatetimeAxis()
        plots[p].add_layout(choicexaxis, 'below')

        xaxis = DatetimeAxis()
        yaxis = LinearAxis()

        plots[p].add_layout(Grid(dimension=0, ticker=xaxis.ticker))
        plots[p].add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        choice_labels = LabelSet(x="new_A_time", y="yloc", text="annotation", y_offset=-5,x_offset=10,
                          text_font_size="8pt", text_color="#555555",
                          source=linksource, text_align='left')
        plots[p].add_layout(choice_labels)

    return plots.values()
Ejemplo n.º 6
0
def plot_choice_links(linkfile_df,cost="sim_cost",paths=False):
    
    linkfile_df["color"]= map(assignColorByMode, linkfile_df["mode"])
    if paths:
        linkfile_df["annotation"]= map(createLinkPathAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"], linkfile_df["probability"])
    else:
        linkfile_df["annotation"]=map(createLinkAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"])
    

    linkfile_df["yloc"]= map(yloc, linkfile_df["pathnum"],linkfile_df["linknum"])

    linksource = ColumnDataSource(linkfile_df)
    #linkfile_df

    xdr2 = DataRange1d()
    ydr2 = DataRange1d()

    choiceplot = Plot(
        title=None, x_range=xdr2, y_range=ydr2, plot_width=800, plot_height=300,
        h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

    glyph = Segment(y0="yloc", x0="new_A_time", y1="yloc", x1="new_B_time", line_color="color", line_width=cost)
    choiceplot.add_glyph(linksource, glyph)

    choicexaxis = DatetimeAxis()
    choiceplot.add_layout(choicexaxis, 'below')

    xaxis = DatetimeAxis()
    yaxis = LinearAxis()

    choiceplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    choiceplot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    choice_labels = LabelSet(x="new_A_time", y="yloc", text="annotation", y_offset=-5,x_offset=10,
                      text_font_size="8pt", text_color="#555555",
                      source=linksource, text_align='left')
    choiceplot.add_layout(choice_labels)

    return choiceplot
Ejemplo n.º 7
0
def get_weather_plot(time_int=None, t_min=None, t_max=None):
    plot_height = cs.plot_height
    plot_width = cs.plot_width
    border_left = cs.border_left
    column_names = cs.column_names_weewx
    column_time = cs.time_column_name_weewx
    if t_max == None or t_min == None:
        t_max, t_min = get_first_time_interval()
    t_span = t_max - t_min
    if time_int == None:
        time_int = cs.time_int
    data_seconds = sql_con.get_data_ws(time_int=time_int,
                                       t_min=t_min,
                                       t_max=t_max)
    data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000

    plot = Plot(
        x_range=DataRange1d(start=(t_min - t_span * .1) * 1000,
                            end=(t_max + t_span * .1) * 1000),
        y_range=DataRange1d(),
        plot_width=plot_width,
        plot_height=plot_height,
        # x_axis_type="datetime",
        min_border_left=border_left,
        toolbar_location="right")

    add_glyphs_to_plot(column_names, column_time, data_seconds, plot,
                       'source_weather')

    plot.add_layout(DatetimeAxis(name="date_time_axis"), 'below')

    plot.add_tools(
        PanTool(),
        WheelZoomTool(),
        # ResizeTool(),
        CrosshairTool(),
        PreviewSaveTool())
    Grid(plot=plot,
         dimension=0,
         ticker=plot.select('date_time_axis')[0].ticker)

    Grid(plot=plot,
         dimension=1,
         ticker=plot.select(type=LinearAxis, name=column_names[0])[0].ticker)

    set_legends(plot)

    plot.title = cs.plot_title_weewx + ' averaged to {} seconds'.format(
        time_int)

    return plot
Ejemplo n.º 8
0
    def make_axis(self, dim, location, scale, label):
        """Create linear, date or categorical axis depending on the location,
        scale and with the proper labels.

        Args:
            location(str): the space localization of the axis. It can be
                ``left``, ``right``, ``above`` or ``below``.
            scale (str): the scale on the axis. It can be ``linear``, ``datetime``
                or ``categorical``.
            label (str): the label on the axis.

        Return:
            Axis: Axis instance
        """

        # ToDo: revisit how to handle multiple ranges
        # set the last range to the chart's range
        if len(self._ranges[dim]) == 0:
            raise ValueError('Ranges must be added to derive axis type.')

        data_range = self._ranges[dim][-1]
        setattr(self, dim + '_range', data_range)

        if scale == "auto":
            if isinstance(data_range, FactorRange):
                scale = 'categorical'
            else:
                scale = 'linear'

        if scale == "linear":
            axis = LinearAxis(axis_label=label)
        elif scale == "datetime":
            axis = DatetimeAxis(axis_label=label)
        elif scale == "categorical":
            axis = CategoricalAxis(
                major_label_orientation=np.pi / 4, axis_label=label
            )
        else:
            axis = LinearAxis(axis_label=label)

        self.add_layout(axis, location)
        return axis
Ejemplo n.º 9
0
def large_plot():
    source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1]))

    xdr = Range1d(start=0, end=1)
    xdr.tags.append("foo")
    xdr.tags.append("bar")

    ydr = Range1d(start=10, end=20)
    ydr.tags.append("foo")
    ydr.tags.append(11)

    plot = Plot(x_range=xdr, y_range=ydr)

    ydr2 = Range1d(start=0, end=100)
    plot.extra_y_ranges = {"liny": ydr2}

    circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black")
    plot.add_glyph(source, circle, name="mycircle")

    line = Line(x="x", y="y")
    plot.add_glyph(source, line, name="myline")

    rect = Rect(x="x", y="y", width=1, height=1, fill_color="green")
    plot.add_glyph(source, rect, name="myrect")

    plot.add_layout(DatetimeAxis(), 'below')
    plot.add_layout(LogAxis(), 'left')
    plot.add_layout(LinearAxis(y_range_name="liny"), 'left')

    plot.add_layout(Grid(dimension=0), 'left')
    plot.add_layout(Grid(dimension=1), 'left')

    plot.add_tools(
        BoxZoomTool(),
        PanTool(),
        SaveTool(),
        ResetTool(),
        ResizeTool(),
        WheelZoomTool(),
    )

    return plot
Ejemplo n.º 10
0
def _make_base_plot(dfs, activities, x_range, plot_width=900):
    plot = Plot(
        x_range=x_range,
        y_range=Range1d(0, 11),
        outline_line_color=None,
        background_fill=COLOR_PRIMARY,
        border_fill=COLOR_PRIMARY,
        plot_width=plot_width,
        plot_height=150,
        min_border_top=0,
        toolbar_location=None,
    )

    yticker = BasicTicker(min_interval=3)
    close_ticker = DatetimeTicker(desired_num_ticks=8)
    close_ticks = DatetimeTickFormatter(
        formats={
            'years': ["%b"],
            'months': ["%b"],
            'days': ["%a %d %b"],
            'hours': ["%I%p %d %b"]
        }
    )

    plot.add_layout(LinearAxis(ticker=yticker, **AXIS_PROPERTIES), 'left')
    plot.add_layout(DatetimeAxis(formatter=close_ticks, ticker=close_ticker, **AXIS_PROPERTIES), 'below')
    plot.add_layout(Grid(dimension=1, ticker=yticker, grid_line_alpha=0.3))

    palette = get_palette(activities)

    for i, activity in enumerate(activities):
        source = dfs[activity]
        line = Line(
            line_color=palette[i],
            line_join='round', line_cap='round', line_width=5, line_alpha=0.75,
            x='timestamp', y='cumsum_hrs'
        )
        plot.add_glyph(source, line)

    return plot
Ejemplo n.º 11
0
def get_ws_plot(data,
                plot_height=300,
                plot_width=800,
                column_names=cs.column_names_weewx,
                column_time=cs.time_column_name_weewx,
                border_left=200):
    data_seconds = data
    data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000

    plot = Plot(x_range=DataRange1d(),
                y_range=DataRange1d(),
                plot_width=plot_width,
                plot_height=plot_height,
                min_border_left=border_left,
                **kwargs)

    add_glyphs_to_plot(column_names, column_time, data_seconds, plot)

    plot.add_layout(DatetimeAxis(), 'below')

    plot.add_tools(PanTool(), WheelZoomTool(), ResizeTool(), CrosshairTool())
    return plot
Ejemplo n.º 12
0
    def __init__(self, face_cascade):
        self.face_cascade = face_cascade
        self.t0 = time.mktime(dt.now().timetuple()) * 1000

        ### Image Plot
        self.image_source = ColumnDataSource({"image": []})
        self.rect_source = ColumnDataSource({
            "x": [],
            "y": [],
            "w": [],
            "h": []
        })

        self.image_plot = Plot(name="image",
                               width=CAMERA_WIDTH // 2,
                               height=CAMERA_HEIGHT // 2,
                               x_range=Range1d(0, CAMERA_WIDTH),
                               y_range=Range1d(0, CAMERA_HEIGHT))
        self.image_plot.add_glyph(
            self.image_source,
            Image(image='image', x=0, y=0, dw=CAMERA_WIDTH, dh=CAMERA_HEIGHT))
        self.image_plot.add_glyph(self.rect_source,
                                  Rect(x='x', y='y', width='w', height='h'))

        ### Timeseries Plot
        self.ts_source = ColumnDataSource({"x": [], "y": []})

        self.ts_plot = Plot(name="ts",
                            x_range=DataRange1d(),
                            y_range=DataRange1d(),
                            width=CAMERA_WIDTH // 2,
                            height=150)
        self.ts_plot.add_layout(DatetimeAxis(axis_label="time"), "below")
        self.ts_plot.add_layout(
            LinearAxis(axis_label="num faces", ticker=SITicker()), "left")
        self.ts_plot.add_glyph(self.ts_source, Step(x="x", y="y"))
Ejemplo n.º 13
0
def la_rate_plot(data, names, region, rolling_days=7):
    data = (data["cases_norm"].resample(date="1D").nearest(
        tolerance="1D").ffill("date").fillna(0).diff("date")[:, :-4].rolling(
            date=rolling_days, center=True).sum().dropna("date"))

    palette = [
        (0, "#f1f1f1"),
        (5, "#fef0d9"),
        (10, "#fdd49e"),
        (25, "#fdbb84"),
        (50, "#fc8d59"),
        (100, "#e34a33"),
        (100000, "#b30000"),
    ]

    def colour_val(cases):
        for threshold, colour in palette:
            if cases <= threshold:
                return colour
        return palette[-1][1]

    colours = []
    y_range = []
    yname = []
    xname = []
    for la in names.index:
        if la not in data["gss_code"]:
            continue
        name = names[la]
        y_range.append(name)
        xname += list(data["date"].values)
        for val in data.sel(gss_code=la).values * 100000 * (7 / rolling_days):
            yname.append(name)
            colours.append(colour_val(val))

    x_range = [data["date"].min().values, data["date"].max().values]
    height = len(y_range) * 12 + 100
    fig = bokeh_figure(
        y_range=y_range,
        x_range=x_range,
        width=1200,
        height=height,
        title=region,
        sizing_mode="scale_width",
        tools="",
        toolbar_location=None,
    )

    data_source = {"y": yname, "x": xname, "colours": colours}
    fig.rect(
        "x",
        "y",
        1.01 * (60 * 60 * 24 * 1000),
        0.85,
        source=data_source,
        color="colours",
        line_color=None,
        dilate=True,
    )
    fig.axis.axis_line_color = None
    fig.grid.grid_line_color = None
    fig.yaxis.major_tick_line_color = None
    fig.add_layout(DatetimeAxis(), "above")
    fig.xaxis.formatter = DatetimeTickFormatter(days="%d %b", months="%d %b")
    return fig
Ejemplo n.º 14
0
    def __init__(self, **kwargs):
        self.source = ColumnDataSource(
            data={
                'time': [],
                'cpu': [],
                'memory_percent': [],
                'network-send': [],
                'network-recv': []
            })

        x_range = DataRange1d(follow='end',
                              follow_interval=30000,
                              range_padding=0)

        resource_plot = Plot(x_range=x_range,
                             y_range=Range1d(start=0, end=1),
                             toolbar_location=None,
                             min_border_bottom=10,
                             **kwargs)

        line_opts = dict(line_width=2, line_alpha=0.8)
        g1 = resource_plot.add_glyph(
            self.source,
            Line(x='time',
                 y='memory_percent',
                 line_color="#33a02c",
                 **line_opts))
        g2 = resource_plot.add_glyph(
            self.source,
            Line(x='time', y='cpu', line_color="#1f78b4", **line_opts))

        resource_plot.add_layout(
            LinearAxis(formatter=NumeralTickFormatter(format="0 %")), 'left')

        legend_opts = dict(location='top_left',
                           orientation='horizontal',
                           padding=5,
                           margin=5,
                           label_height=5)

        resource_plot.add_layout(
            Legend(items=[('Memory', [g1]), ('CPU', [g2])], **legend_opts))

        network_plot = Plot(x_range=x_range,
                            y_range=DataRange1d(start=0),
                            toolbar_location=None,
                            **kwargs)
        g1 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-send', line_color="#a6cee3",
                 **line_opts))
        g2 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-recv', line_color="#b2df8a",
                 **line_opts))

        network_plot.add_layout(DatetimeAxis(axis_label="Time"), "below")
        network_plot.add_layout(LinearAxis(axis_label="MB/s"), 'left')
        network_plot.add_layout(
            Legend(items=[('Network Send', [g1]), ('Network Recv', [g2])],
                   **legend_opts))

        tools = [
            PanTool(dimensions='width'),
            WheelZoomTool(dimensions='width'),
            BoxZoomTool(),
            ResetTool()
        ]

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        combo_toolbar = ToolbarBox(tools=tools,
                                   logo=None,
                                   toolbar_location='right',
                                   **sizing_mode)

        self.root = row(column(resource_plot, network_plot, **sizing_mode),
                        column(combo_toolbar, **sizing_mode),
                        id='bk-resource-profiles-plot',
                        **sizing_mode)

        # Required for update callback
        self.resource_index = [0]
Ejemplo n.º 15
0
def create_bk_fig(x=None, xlab=None, x_min=None, x_max=None,
                  ylab=None, fh=None, fw=None,
                  title=None, pw=None, ph=None, x_axis_type="linear",
                  y_axis_type="linear", x_name=None, y_name=None, **kwargs):
    """ Generates a bokeh figure

    Parameters
    ----------
    x :obj:`DataArray`
        Contains x-axis data
    xlab : :obj:`str`
        X-axis label
    x_min : :obj:`float`
        Min x value
    x_max : :obj:`float`
        Max x value
    ylab : :obj:`str`
        Y-axis label
    fh: :obj:`int`
        True height of figure without legends, axes titles etc
    fw: :obj:`int`
        True width of figure without legends, axes etc
    title: :obj:`str`
        Title of plot
    pw: :obj:`int`
        Plot width including legends, axes etc
    ph: :obj:`int`
        Plot height including legends, axes etc
    x_axis_type: :obj:`str`
        Type of x-axis can be linear, log, or datetime
    y_axis_type: :obj:`str`
        Can be linear, log or datetime
    x_name: :obj:`str`
        Name of the column used for the x-axis. Mostly used to form tooltips
    y_name: :obj:`str`
        Name of the column used for the y-axis. Also used for tooltips
    add_grid: :obj:`bool`
        Whether or not to add grid
    add_title: :obj:`bool`
        Whether or not to add title to plot
    add_xaxis: :obj:`bool`
        Whether or not to add x-axis and tick marks
    add_yaxis: :obj:`bool`
        Add y-axis or not
    fix_plotsize: :obj:`bool`
        Enforce certain dimensions on plot. This is useful for ensuring a plot
        is not obscure by axes and other things. If activated, plot's
        dimensions will not be responsive. It utilises fw and fh.

    Returns
    -------
    p : :obj:`Plot`
        A bokeh Plot object

    """

    add_grid = kwargs.pop("add_grid", False)
    add_title = kwargs.pop("add_title", True)
    add_xaxis = kwargs.pop("add_xaxis", False)
    add_yaxis = kwargs.pop("add_yaxis", False)
    fix_plotsize = kwargs.pop("fix_plotsize", True)
    # addition plot specs
    pl_specs = kwargs.pop("pl_specs", {})
    # additional axis specs
    ax_specs = kwargs.pop("ax_specs", {})
    # ticker specs
    ti_specs = kwargs.pop("ti_specs", {})

    plot_specs = dict(background="white", border_fill_alpha=0.1,
                      border_fill_color="white", min_border=3,
                      name="plot", outline_line_dash="solid",
                      outline_line_width=2, outline_line_color="#017afe",
                      outline_line_alpha=0.4, output_backend="canvas",
                      sizing_mode="stretch_width", title_location="above",
                      toolbar_location="above")
    plot_specs.update(pl_specs)

    axis_specs = dict(minor_tick_line_alpha=0, axis_label_text_align="center",
                      axis_label_text_font="monospace",
                      axis_label_text_font_size="10px",
                      axis_label_text_font_style="normal",
                      major_label_orientation="horizontal")
    axis_specs.update(ax_specs)

    tick_specs = dict(desired_num_ticks=5)
    tick_specs.update(ti_specs)

    # Define frame width and height
    # This is the actual size of the plot without the titles et al
    if fix_plotsize and not(fh or fw):
        fw = int(0.98 * pw)
        fh = int(0.93 * ph)

    # define the axes ranges
    x_range = DataRange1d(name="p_x_range", only_visible=True)

    y_range = DataRange1d(name="p_y_range", only_visible=True)

    if x_min is not None and x_max is not None and x_name.lower() in ["channel", "frequency"]:
        x_range = Range1d(name="p_x_range", start=x_min, end=x_max)
        y_range.only_visible = False

    # define items to add on the plot
    p_htool = HoverTool(tooltips=[(x_name, "$x"),
                                  (y_name, "$y")],
                        name="p_htool", point_policy="snap_to_data")

    if x_name.lower() == "time":
        p_htool.tooltips[0] = (x_name, "$x{%d-%m-%Y %H:%M}")
        p_htool.formatters = {"$x": "datetime"}

    p_toolbar = Toolbar(name="p_toolbar",
                        tools=[p_htool, BoxSelectTool(), BoxZoomTool(),
                               # EditTool(), # BoxEditTool(), # RangeTool(),
                               LassoSelectTool(), PanTool(), ResetTool(),
                               SaveTool(), UndoTool(), WheelZoomTool()])
    p_ticker = BasicTicker(name="p_ticker", **tick_specs)

    # select the axis scales for x and y
    if x_axis_type == "linear":
        x_scale = LinearScale(name="p_x_scale")
        # define the axes and tickers
        p_x_axis = LinearAxis(axis_label=xlab, name="p_x_axis",
                              ticker=p_ticker, **axis_specs)
    elif x_axis_type == "datetime":
        x_scale = LinearScale(name="p_x_scale")
        # define the axes and tickers
        p_x_axis = DatetimeAxis(axis_label=xlab, name="p_x_axis",
                                ticker=p_ticker, **axis_specs)
    elif x_axis_type == "log":
        x_scale = LogScale(name="p_x_scale")
        p_x_axis = LogAxis(axis_label=xlab, name="p_x_axis",
                           ticker=p_ticker, **axis_specs)

    if y_axis_type == "linear":
        y_scale = LinearScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = LinearAxis(axis_label=ylab, name="p_y_axis",
                              ticker=p_ticker, **axis_specs)
    elif x_axis_type == "datetime":
        y_scale = LinearScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = DatetimeAxis(axis_label=xlab, name="p_y_axis",
                                ticker=p_ticker, **axis_specs)
    elif y_axis_type == "log":
        y_scale = LogScale(name="p_y_scale")
        # define the axes and tickers
        p_y_axis = LogAxis(axis_label=ylab, name="p_y_axis",
                           ticker=p_ticker, **axis_specs)

    # Create the plot object
    p = Plot(plot_width=pw, plot_height=ph, frame_height=fh, frame_width=fw,
             toolbar=p_toolbar, x_range=x_range, x_scale=x_scale,
             y_range=y_range, y_scale=y_scale, **plot_specs)

    if add_title:
        p_title = Title(align="center", name="p_title", text=title,
                        text_font_size="24px",
                        text_font="monospace", text_font_style="bold",)
        p.add_layout(p_title, "above")

    if add_xaxis:
        p.add_layout(p_x_axis, "below")

    if add_yaxis:
        p.add_layout(p_y_axis, "left")

    if add_grid:
        p_x_grid = Grid(dimension=0, ticker=p_ticker)
        p_y_grid = Grid(dimension=1, ticker=p_ticker)
        p.add_layout(p_x_grid)
        p.add_layout(p_y_grid)

    return p
Ejemplo n.º 16
0
y = sin(x)

# Create an array of times, starting at the current time, and extending
# for len(x) number of hours.
times = np.arange(len(x)) * 3600000 + time.time()

source = ColumnDataSource(data=dict(x=x, y=y, times=times))

xdr = DataRange1d(sources=[source.columns("times")])
ydr = DataRange1d(sources=[source.columns("y")])

plot = Plot(x_range=xdr, y_range=ydr, min_border=80)

circle = Circle(x="times", y="y", fill_color="red", size=5, line_color="black")
plot.add_glyph(source, circle)

plot.add_layout(DatetimeAxis(), 'below')
plot.add_layout(DatetimeAxis(), 'left')

plot.add_tools(PanTool(), WheelZoomTool())

doc = Document()
doc.add(plot)

if __name__ == "__main__":
    filename = "dateaxis.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Date Axis Example"))
    print("Wrote %s" % filename)
    view(filename)
Ejemplo n.º 17
0
                    line_width=2,
                    label=value("sunrise"))
sunrise_line_renderer = plot.add_glyph(source, sunrise_line)

sunset_line = Line(x="dates",
                   y="sunsets",
                   line_color="red",
                   line_width=2,
                   label=value("sunset"))
sunset_line_renderer = plot.add_glyph(source, sunset_line)

text = Text(x="dates", y="times", text="texts", text_align="center")
plot.add_glyph(text_source, text)

xformatter = DatetimeTickFormatter(months="%b %Y")
xaxis = DatetimeAxis(formatter=xformatter)
plot.add_layout(xaxis, 'below')

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

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

legend = Legend(legends=[sunrise_line_renderer, sunset_line_renderer])
plot.add_layout(legend)

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
Ejemplo n.º 18
0
sunrise_line = Line(x="dates", y="sunrises", line_color="orange", line_width=4)
sunrise_line_renderer = plot.add_glyph(source, sunrise_line)

sunset_line = Line(x="dates", y="sunsets", line_color="crimson", line_width=4)
sunset_line_renderer = plot.add_glyph(source, sunset_line)

text = Text(x="dates", y="times", text="texts", text_align="center", text_color="grey")
plot.add_glyph(text_source, text)

xformatter = DatetimeTickFormatter(months="%b %d %Y")
min_time = dt.datetime.min.time()
xticker = FixedTicker(ticks=[
    mktime(dt.datetime.combine(summer_start, min_time).timetuple()) * 1000,
    mktime(dt.datetime.combine(summer_end, min_time).timetuple()) * 1000
])
xaxis = DatetimeAxis(formatter=xformatter, ticker=xticker)
plot.add_layout(xaxis, 'below')

yaxis = DatetimeAxis()
yaxis.formatter.hours = ['%H:%M']
plot.add_layout(yaxis, 'left')

legend = Legend(items=[
    LegendItem(label=value('sunset'), renderers=[sunset_line_renderer]),
    LegendItem(label=value('sunrise'), renderers=[sunrise_line_renderer]),
])
plot.add_layout(legend)

doc = Document()
doc.add_root(plot)
Ejemplo n.º 19
0
def outlet_vis(df,
               forcing,
               out_name,
               scale=5,
               y_range=(0.008, 0.023),
               extra_y_range=0.14):
    df = df / scale  # scale m³/5min to m³/min
    date = df.index.values
    color = itertools.cycle(palette['Category10'][10])

    p = figure(plot_width=960,
               plot_height=600,
               x_range=(date[0], date[-1]),
               y_range=y_range,
               x_axis_type='datetime',
               x_axis_label='Date',
               y_axis_label='Catchment Outlet Discharge [m³/min]')
    legend_it = []

    for i in range(0, df.shape[1]):
        if df.columns.values[i] == 'Original':
            pl = p.line(df.index.values,
                        df.iloc[:, i],
                        line_color='#666666',
                        line_width=2)
        else:
            c = next(color)
            pl = p.line(df.index.values,
                        df.iloc[:, i],
                        line_color=c,
                        line_width=2)
        legend_it.append((df.columns.values[i], [pl]))

    p.xaxis.major_label_text_font_size = "16pt"
    p.xaxis.axis_label_text_font_size = "16pt"
    p.yaxis.formatter = BasicTickFormatter(use_scientific=True,
                                           power_limit_low=1,
                                           power_limit_high=2,
                                           precision=1)

    df_forcing = pd.DataFrame(forcing[0:date.shape[0]], columns=['forcing'])
    df_forcing = df_forcing.set_index(date)
    df_forcing = df_forcing / scale  # scale mm/5min to mm/min

    # Setting the second axis range name and range
    p.extra_y_ranges = {"foo": Range1d(start=extra_y_range, end=0.0)}
    p.extra_x_ranges = {"faa": Range1d(date[0], date[-1])}

    # Adding the second axis to the plot
    p.add_layout(
        LinearAxis(y_range_name="foo", axis_label="Rainfall [mm/min]"),
        'right')
    p.add_layout(
        DatetimeAxis(x_range_name="faa",
                     axis_label="",
                     major_tick_line_color=None,
                     major_label_text_font_size='0pt'), 'above')

    pl = p.vbar(x=df_forcing.index.values,
                top=df_forcing['forcing'],
                x_range_name='faa',
                y_range_name='foo',
                line_color='#00BFFF',
                fill_color='#00BFFF',
                width=240000)
    legend_it.append(('Rainfall', [pl]))
    legend_it = sorted(legend_it, key=itemgetter(0))

    # turn off y-axis minor ticks
    p.yaxis.minor_tick_line_color = None

    legend = Legend(items=legend_it, location="center")
    p.add_layout(legend, 'above')
    p.legend.orientation = "horizontal"

    p.legend.label_text_font_size = "16pt"
    p.yaxis.major_label_text_font_size = "16pt"
    p.yaxis.axis_label_text_font_size = "16pt"

    p.xgrid.visible = False
    p.ygrid.visible = False

    p.output_backend = "svg"
    export_svgs(p, filename=out_name)
Ejemplo n.º 20
0
def get_plot(raw, today):

    dfs, cats = get_sources_and_categories(raw)

    # Some times

    first_day = raw.loc[0, 'timestamp']
    one_week_ago = today - datetime.timedelta(weeks=1)
    two_weeks_ago = today - datetime.timedelta(weeks=2)
    one_week_forward = today + datetime.timedelta(weeks=1)

    # The ranges
    all_range = Range1d(start=first_day, end=today)
    month_range = Range1d(start=two_weeks_ago, end=one_week_forward)
    week_range = Range1d(start=one_week_ago, end=today)

    # Selection indicators
    highlight = Quad(
        left='start', right='end', bottom=0, top=12,
        fill_color='white', line_color=COLOR_PRIMARY_CONTRAST, fill_alpha=0.2,
    )
    lowlight = Quad(
        left='start', right='end', bottom=0, top=12,
        fill_color=COLOR_PRIMARY, line_color=COLOR_PRIMARY_CONTRAST, fill_alpha=0.5,
    )

    # Make the complete timeline plot
    all_plot = _make_base_plot(dfs, cats, all_range)
    detail_selection_source = ColumnDataSource({
        'start': [all_range.start, month_range.end],
        'end': [month_range.start, all_range.end]
    })
    all_plot.add_glyph(detail_selection_source, lowlight)
    # add a second axis to all_layout plot for presentation
    year_ticker = DatetimeTicker(desired_num_ticks=4)
    year_ticks = DatetimeTickFormatter(
        formats={
            'years': ["%Y"],
            'months': ["%Y"],
            'days': ["%Y"],
            'hours': ["%Y"]
        }
    )
    all_plot.add_layout(
        DatetimeAxis(formatter=year_ticks, ticker=year_ticker, **AXIS_PROPERTIES),
        'below'
    )

    # Make the detail plot
    detail_plot = _make_base_plot(dfs, cats, month_range)
    detail_plot.add_tools(PanTool(dimensions=['width']))
    detail_plot.add_tools(WheelZoomTool(dimensions=['width']))
    detail_plot.add_tools(ResetTool())

    week_selection_source = ColumnDataSource({'start': [week_range.start], 'end': [week_range.end]})
    detail_plot.add_glyph(week_selection_source, highlight)

    detail_code = """
        // Update the month selection box on the all_data plot when month pans
        var detail_selection_data = detail_selection_source.get('data');
        var detail_start = cb_obj.get('frame').get('x_range').get('start');
        var detail_end = cb_obj.get('frame').get('x_range').get('end');
        new_detail_selection = {
            'start': [detail_selection_data['start'][0], detail_end],
            'end': [detail_start, detail_selection_data['end'][1]]
        };
        detail_selection_source.set('data', new_detail_selection);

        // Always make sure the week highlight box on detail is visible and centered
        var x = moment.duration(detail_end - detail_start).asWeeks() / 2.4;
        var start = moment(detail_start);

        var week_end = start.add(x, 'weeks').format('x');
        $("#one_week_before").text(start.format('ddd, DD MMM YYYY'));
        var newStart = start.format('YYYY-MM-DD');
        var week_start = start.add(6, 'days').format('x');
        $("#today").text(start.format('ddd, DD MMM YYYY'));

        new_week_selection = {
            'start': [week_start, ],
            'end': [week_end, ]
        };
        week_selection_source.set('data', new_week_selection);

        var url = '/timesheet/?start=' + newStart;
        $("#timesheet_submit").attr('href', url).addClass("mdl-button--colored");
    """

    detail_xrange_callback = CustomJS(args={}, code=detail_code)
    detail_xrange_callback.args['detail_selection_source'] = detail_selection_source
    detail_xrange_callback.args['week_selection_source'] = week_selection_source
    detail_plot.x_range.callback = detail_xrange_callback

    return all_plot, detail_plot
Ejemplo n.º 21
0
    def __init__(self, n_rectangles=1000, clear_interval=20000, **kwargs):
        """
        kwargs are applied to the bokeh.models.plots.Plot constructor
        """
        self.n_rectangles = n_rectangles
        self.clear_interval = clear_interval
        self.last = 0

        self.source = ColumnDataSource(data=dict(start=[],
                                                 duration=[],
                                                 key=[],
                                                 name=[],
                                                 color=[],
                                                 worker=[],
                                                 y=[],
                                                 worker_thread=[],
                                                 alpha=[]))

        x_range = DataRange1d(range_padding=0)
        y_range = DataRange1d(range_padding=0)

        self.root = Plot(title=Title(text="Task Stream"),
                         id='bk-task-stream-plot',
                         x_range=x_range,
                         y_range=y_range,
                         toolbar_location="above",
                         min_border_right=35,
                         **kwargs)

        self.root.add_glyph(
            self.source,
            Rect(x="start",
                 y="y",
                 width="duration",
                 height=0.4,
                 fill_color="color",
                 line_color="color",
                 line_alpha=0.6,
                 fill_alpha="alpha",
                 line_width=3))

        self.root.add_layout(DatetimeAxis(axis_label="Time"), "below")

        ticker = BasicTicker(num_minor_ticks=0)
        self.root.add_layout(
            LinearAxis(axis_label="Worker Core", ticker=ticker), "left")
        self.root.add_layout(
            Grid(dimension=1, grid_line_alpha=0.4, ticker=ticker))

        self.root.yaxis.major_label_text_alpha = 0

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                    <span style="font-size: 12px; font-weight: bold;">@name:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span>
                    <span style="font-size: 10px;">ms</span>&nbsp;
                </div>
                """)

        self.root.add_tools(hover, BoxZoomTool(), ResetTool(reset_size=False),
                            PanTool(dimensions="width"),
                            WheelZoomTool(dimensions="width"))
        if ExportTool:
            export = ExportTool()
            export.register_plot(self.root)
            self.root.add_tools(export)

        # Required for update callback
        self.task_stream_index = [0]
Ejemplo n.º 22
0
 def _setxaxis(self):
     xaxis1 = DatetimeAxis(major_label_text_font_size='0pt', formatter=dttf)
     xaxis1.visible = False
     self.fig.add_layout(xaxis1, 'above')
Ejemplo n.º 23
0
    def __init__(self,
                 nplots,
                 plot_height=200,
                 plot_width=1000,
                 rollover=10800,
                 mode="time"):
        """Initialize stream graph plots.

        Args:
            nplots (int): Number of stream plots that will share common controls.
            plot_height (int, optional): Height of plot area in screen pixels. Defaults to 200.
            plot_width (int, optional): Width of plot area in screen pixels. Defaults to 1000.
            rollover (int, optional): A maximum number of points, above which data from the start
                begins to be discarded. If None, then graph will grow unbounded. Defaults to 10800.
            mode (str, optional): stream update mode, 'time' - uses the local wall time,
                'number' - uses a image number counter. Defaults to 'time'.
        """
        self.rollover = rollover
        self.mode = mode
        self._stream_t = 0
        self._buffers = []
        self._window = 30

        # Custom tick formatter for displaying large numbers
        tick_formatter = BasicTickFormatter(precision=1)

        # Stream graphs
        self.plots = []
        self.glyphs = []
        self._sources = []
        for ind in range(nplots):
            # share x_range between plots
            if ind == 0:
                x_range = DataRange1d()

            plot = Plot(
                x_range=x_range,
                y_range=DataRange1d(),
                plot_height=plot_height,
                plot_width=plot_width,
            )

            # ---- tools
            plot.toolbar.logo = None
            plot.add_tools(PanTool(), BoxZoomTool(),
                           WheelZoomTool(dimensions="width"), ResetTool())

            # ---- axes
            plot.add_layout(LinearAxis(formatter=tick_formatter), place="left")
            if mode == "time":
                plot.add_layout(DatetimeAxis(), place="below")
            elif mode == "number":
                plot.add_layout(LinearAxis(), place="below")
            else:
                pass

            # ---- grid lines
            plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
            plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

            # ---- line glyph
            source = ColumnDataSource(dict(x=[], y=[], x_avg=[], y_avg=[]))
            line = Line(x="x", y="y", line_color="gray")
            line_avg = Line(x="x_avg", y="y_avg", line_color="red")
            line_renderer = plot.add_glyph(source, line)
            line_avg_renderer = plot.add_glyph(source, line_avg)

            # ---- legend
            plot.add_layout(
                Legend(
                    items=[("per frame", [line_renderer]),
                           ("moving average", [line_avg_renderer])],
                    location="top_left",
                ))
            plot.legend.click_policy = "hide"

            self.plots.append(plot)
            self.glyphs.append(line)
            self._sources.append(source)
            self._buffers.append(deque(maxlen=MAXLEN))

        # Moving average spinner
        def moving_average_spinner_callback(_attr, _old_value, new_value):
            if moving_average_spinner.low <= new_value <= moving_average_spinner.high:
                self._window = new_value

        moving_average_spinner = Spinner(title="Moving Average Window:",
                                         value=self._window,
                                         low=1,
                                         high=MAXLEN,
                                         default_size=145)
        moving_average_spinner.on_change("value",
                                         moving_average_spinner_callback)
        self.moving_average_spinner = moving_average_spinner

        # Reset button
        def reset_button_callback():
            # keep the latest point in order to prevent a full axis reset
            if mode == "time":
                pass  # update with the lastest time
            elif mode == "number":
                self._stream_t = 1

            for source in self._sources:
                if source.data["x"]:
                    source.data.update(
                        x=[self._stream_t],
                        y=[source.data["y"][-1]],
                        x_avg=[self._stream_t],
                        y_avg=[source.data["y_avg"][-1]],
                    )

        reset_button = Button(label="Reset",
                              button_type="default",
                              default_size=145)
        reset_button.on_click(reset_button_callback)
        self.reset_button = reset_button