Ejemplo n.º 1
0
    def __init__(self,
                 x_range=(0, 0),
                 y_range=None,
                 width=450,
                 height=300,
                 x_label=None,
                 y_label=None,
                 x_axis_type='auto',
                 y_axis_type='auto'):

        output_notebook(resources=INLINE, hide_banner=True)
        self.fig = figure(x_range=x_range,
                          y_range=y_range,
                          width=width,
                          height=height,
                          x_axis_type=x_axis_type,
                          y_axis_type=y_axis_type)

        if x_label is not None:
            self.fig.xaxis.axis_label = x_label
        if y_label is not None:
            self.fig.yaxis.axis_label = y_label
        self.fig.xaxis.visible = True
        self.fig.yaxis.visible = True
        self.fig.xgrid.visible = False
        self.fig.ygrid.visible = False
        if x_axis_type == 'log':
            self.fig.xaxis[0].formatter = FuncTickFormatter(
                code=modify_exposant)
        if y_axis_type == 'log':
            self.fig.yaxis[0].formatter = FuncTickFormatter(
                code=modify_exposant)
Ejemplo n.º 2
0
def tweak_figure(fig: Figure) -> Figure:
    """
    Set some common attributes for a figure
    """
    # fig.grid.grid_line_color = None
    # fig.axis.axis_line_color = None
    fig.axis.major_tick_line_color = None
    fig.axis.major_label_text_font_size = "9pt"
    fig.axis.major_label_standoff = 0
    fig.xaxis.major_label_orientation = np.pi / 3
    # truncate axis tick values
    format_js = """
        if (tick.toString().length > 15) {
            if (typeof tick === 'string') {
                return tick.toString().substring(0, 13) + '...';
            } else {
                return tick.toPrecision(1);
            }
        } else {
            return tick;
        }
    """
    fig.xaxis.formatter = FuncTickFormatter(code=format_js)
    fig.yaxis.formatter = FuncTickFormatter(code=format_js)

    return fig
Ejemplo n.º 3
0
    def __init__(self, source):
        plot = figure(plot_width=900,
                      plot_height=900,
                      x_minor_ticks=None,
                      y_minor_ticks=None,
                      x_axis_location='above',
                      tools='save')
        plot.y_range = Range1d(-73.5, 0.5)
        plot.x_range = Range1d(-0.5, 73.5)
        plot.xaxis.axis_label = 'Winning Score'
        plot.yaxis.axis_label = 'Losing Score'
        plot.xaxis.axis_label_text_font_size = '18pt'
        plot.yaxis.axis_label_text_font_size = '18pt'
        plot.xaxis.axis_label_text_font_style = 'bold'
        plot.yaxis.axis_label_text_font_style = 'bold'

        plot.yaxis.formatter = FuncTickFormatter(code='return -tick')

        plot.background_fill_color = '#cccccc'
        plot.grid.grid_line_color = None
        plot.xaxis.ticker = range(0, 74, 7)
        plot.yaxis.ticker = range(0, -74, -7)
        plot.axis.major_tick_in = 1
        plot.axis.major_tick_out = -1
        plot.axis.major_label_text_font_size = '8pt'
        plot.outline_line_width = 1
        plot.outline_line_color = 'black'
        self.plot = plot

        self.gridlines = self.set_up_gridlines()
        self.set_up_quad(source)
Ejemplo n.º 4
0
    def initialize(self,
                   legend_list=utils.default_labels_f,
                   update_time=100,
                   values_range=(-200, 10),
                   time_per_sample=0.1,
                   number_of_samples=200,
                   palette='Inferno'):
        self.nrows = number_of_samples
        self.time_per_sample = time_per_sample

        self.plot = figure(
            tools=['save', 'reset'],
            y_range=[0, self.nrows],
            x_range=[self.frequency_range[0], self.frequency_range[-1]],
            output_backend="webgl")
        self.plot.yaxis.formatter = FuncTickFormatter(code="""
                           return (%s - tick)*%s
                           """ % (self.nrows, time_per_sample))

        self.waterfall_renderer = []
        for i in range(self.nconnections):
            self.waterfall_renderer.append(
                WaterfallRenderer(palette=utils.PALETTES[palette],
                                  time_length=self.nrows,
                                  fft_length=self.size,
                                  min_value=values_range[0],
                                  max_value=values_range[-1]))
            self.plot.renderers.append(self.waterfall_renderer[i])

        self.plot_lst.append(self)

        if self.name:
            self.set_title(self.name)

        self.doc.add_periodic_callback(self.update, update_time)
Ejemplo n.º 5
0
def graph_bgp(label_dict, redundancy_counts, x_ticks):
    """ graph bgp
    the main graphing function used to graph the given dataset
    we will be graphing this two ways - full and downsampled
    for computers that cannot handle the full graph, please use the downsampled
    data set in order to see the graph without hassle """

    # define output html file
    output_file("bgpgraph.html")

    # define the figure initial parameters
    p = figure(
        title="INTERNET'S REDUNDANCY", # title
        toolbar_location="above",  # toolbar location
        sizing_mode='stretch_both',  # sizing parameters of the graph
        output_backend="webgl", # allows us to utilize webgl to reduce load
        )

    # draw circles with size 1, color navy, and semi transparent for each datapoint
    p.circle(x_ticks, redundancy_counts, size=1, color="navy", alpha=0.5)

    # x axis label
    p.xaxis.axis_label = 'IPv4 Routes'

    # y axis label
    p.yaxis.axis_label = 'AVAILABLE REDUNDANT PATHS'

    # this allows us to replace our x_ticks with real labels - ip routes
    p.xaxis.formatter = FuncTickFormatter(code="""
        var labels = %s;
        return labels[tick];
        """ % label_dict)

    # displays graph on default browser
    show(p)
Ejemplo n.º 6
0
def extrapolate_logistic(df, country="US", days_in_future=100, logy=True):
    dates = df.index
    y = df.loc[:, country].values
    x = (dates - np.datetime64(dates[0])).days

    p0 = np.log([2.3, 46, 2000])
    x0, cov = curve_fit(logistic_model, x, y, p0=p0, maxfev=10000)
    sds = np.sqrt(np.diag(cov))
    dts = np.arange(len(dates) + days_in_future)

    if logy:
        p = plotting.figure(y_axis_type="log", x_axis_type="datetime")
        p.yaxis.formatter = FuncTickFormatter(code=code)
    else:
        p = plotting.figure(y_axis_type="log", x_axis_type="datetime")

    plt_dates = [
        dates[0] + datetime.timedelta(days=x) for x in range(0, dts[-1])
    ]
    p.line(
        plt_dates,
        logistic_model(dts, *x0),
        color=colors[0],
        line_width=2.0,
        line_dash="dashed",
    )
    ln = p.line(dates, logistic_model(x, *x0), color=colors[0], line_width=2)
    p.circle(x=dates, y=y, color=colors[0])
    legend_it = [(country, [ln])]
    legend = Legend(
        items=legend_it, location="top_right", orientation="horizontal"
    )
    legend.spacing = 17
    legend.click_policy = "hide"
    p.add_layout(legend, "above")

    label_opts = dict(
        x=plt_dates[-1],
        y=np.min(logistic_model(dts, *x0)),
        text_align="right",
        text_font_size="9pt",
    )

    caption = Label(
        text=f'Created by Tom Barclay on {datetime.datetime.now().strftime("%b %d, %Y")}',
        **label_opts,
    )

    p.add_layout(caption, "below")

    script, div = components(p)
    embedfile = f"_includes/{country.replace(' ', '')}_infections_embed.html"
    with open(embedfile, "w") as ff:
        ff.write(div)
        ff.write(script)

    return [
        f'{(dates[0] + datetime.timedelta(days=np.exp(x0[1]))).strftime("%b %d, %Y")}',
        np.exp(x0[2]),
    ]
Ejemplo n.º 7
0
def plot_sleepiness_vs_exercise():
    # TODO strenght exercise
    from .data import cardio_dataframe as CDF

    c = CDF()
    c['dt'] = unlocalize(c['start_time'])
    c = c.set_index('dt').sort_index()
    c = c[c['error'].isna()]
    # FIXME error handling
    # todo for error handling, would be nice to have unused variable detection?

    s = _sleepy_df()
    c = c[c.index >= min(
        s.index)]  # clip till the time we started collecting it

    deltas = [timedelta(hours=h) for h in range(-200, 200)]
    # we want to find out what predicts sleepiness..
    # so sleepiness is y and kcal is x
    ldf = lag_df(x=c['kcal'], y=s['sleepy'], deltas=deltas)

    # todo maybe rolling is a somewhat misleading name?
    f = rolling(x='lag', y='value', df=ldf, avgs=[]).figure
    f.xaxis.formatter = FuncTickFormatter(code=hhmm_formatter(
        unit=ldf.index.dtype))
    return f
Ejemplo n.º 8
0
    def update(self):
        output_items = self.process.get_plot_data()
        if len(output_items[0]) != 0:
            fc = self.process.get_center_freq()
            bw = self.process.get_bandwidth()
            fftsize = self.process.get_size()
            if self.fc != fc or self.bw != bw or self.size != fftsize:
                self.size = fftsize
                self.set_frequency_range(fc, bw, notify_process=False)

            if not self.is_message:
                for i in range(self.nconnections):
                    if self.waterfall_renderer[i].latest != list(
                            output_items[i]):
                        self.waterfall_renderer[i].latest = list(
                            output_items[i])
                    else:
                        self.waterfall_renderer[0].update = \
                            not self.waterfall_renderer[0].update

            else:
                self.time_per_sample = self.process.get_time_per_fft()
                self.plot.xaxis.formatter = FuncTickFormatter(code="""
                                   return tick*%s
                                   """ % self.time_per_sample)

                for i in range(self.nrows):
                    if self.waterfall_renderer[i].latest != list(
                            output_items[i]):
                        self.waterfall_renderer[0].latest = output_items[i]
                    else:
                        self.waterfall_renderer[0].update = \
                            not self.waterfall_renderer[0].update
        return
Ejemplo n.º 9
0
def set_hhmm_axis(axis, *, mint: int, maxt: int, period: int = 30) -> None:
    from bokeh.models import FixedTicker
    # FIXME infer mint/maxt
    ticks = list(range(mint, maxt, period))
    axis.ticker = FixedTicker(ticks=ticks)
    from bokeh.models import FuncTickFormatter
    axis.formatter = FuncTickFormatter(code=hhmm_formatter(unit=int))
Ejemplo n.º 10
0
def plotForecast(ForecastTable, counterNumber):

    dayNames = []
    for i in range(ForecastTable.shape[0]):
        dayNames.append(WeekdayNames[ForecastTable.index[i].weekday()])

    output_file("ForecastBarPlot.html")

    p = figure(plot_width=600,
               plot_height=400,
               title="7 Day Bicycle Count Forecast for " +
               counterNames[counterNumber])
    p.vbar(x=[0, 1, 2, 3, 4, 5, 6],
           width=0.5,
           bottom=0,
           top=ForecastTable.iloc[:, counterNumber],
           color="DeepSkyBlue")

    label_dict = {}
    for i, s in enumerate(dayNames):
        label_dict[i] = s

    p.xaxis.formatter = FuncTickFormatter(code="""
        var labels = %s;
        return labels[tick];
    """ % label_dict)

    #show(p)

    return p
Ejemplo n.º 11
0
def plot_sleepiness_vs_sleep():
    from .data import sleep_dataframe as DF
    sdf = DF()

    sdf = sdf[sdf['error'].isna()]
    # todo not sure... maybe sleep start/end would be better? or just median??
    sdf = sdf.set_index('date')
    # sdf.index = unlocalize(sdf.index)

    s = _sleepy_df()
    sdf = sdf[sdf.index >= min(s.index)]

    deltas = [timedelta(hours=h) for h in range(-24 * 5, 24 * 5, 4)]
    # TODO need something similar to scatter matrix, but instead of scatter, covariance??
    # TODO unhardcode
    ress = []
    for col in [
            'bed_time', 'coverage', 'avg_hr', 'hrv_morning', 'hrv_evening'
    ]:
        ldf = lag_df(x=sdf[col], y=s['sleepy'], deltas=deltas)
        # TODO wtf?? so
        r = rolling(x='lag', y='value', df=ldf, avgs=[])
        r.figure.title.text = f'lag plot: sleepiness vs {col}'
        r.figure.xaxis.formatter = FuncTickFormatter(code=hhmm_formatter(
            unit=ldf.index.dtype))
        ress.append(r)
    # TODO maybe allow to yield plots? then just assume column layout
    return column([r.layout for r in ress])
Ejemplo n.º 12
0
    def initialize(self, doc, plot_lst):

        plot = figure(tools = utils.default_tools(),
                           y_range = [0, self.nrows],
                           x_range = [self.frequency_range[0],
                                      self.frequency_range[-1]],
                                      output_backend="webgl")
        plot.yaxis.formatter = FuncTickFormatter(code = """
                           return (%s - tick)*%s
                           """ % (self.nrows, self.time_per_sample))

        self.waterfall_renderer = []
        for i in range(self.nconnections):
            self.waterfall_renderer.append(
                WaterfallRenderer(palette = utils.PALETTES[self.palette],
                                  time_length = self.nrows,
                                  fft_length = self.size,
                                  min_value = self.values_range[0],
                                  max_value = self.values_range[-1]))
            plot.renderers.append(self.waterfall_renderer[i])

        self.plot = plot
        plot_lst.append(self)

        def callback():
            self.update( )

        doc.add_periodic_callback(callback, self.update_time)
Ejemplo n.º 13
0
def tweak_figure(
    fig: Figure,
    ptype: Optional[str] = None,
    show_yaxis: bool = False,
    max_lbl_len: int = 15,
) -> None:
    """
    Set some common attributes for a figure
    """
    fig.axis.major_label_text_font_size = "9pt"
    fig.xaxis.major_label_orientation = pi / 3
    fig.title.text_font_size = "10pt"
    if ptype in ["bar", "pie", "hist", "kde", "qq", "box", "hex", "heatmap"]:
        fig.grid.grid_line_color = None
        fig.axis.minor_tick_line_color = None
    if ptype in ["bar", "hist"] and not show_yaxis:
        fig.yaxis.major_label_text_font_size = "0pt"
        fig.yaxis.major_tick_line_color = None
    if ptype in ["bar", "nested", "stacked", "heatmap", "box"]:
        fig.xaxis.formatter = FuncTickFormatter(code="""
            if (tick.length > %d) return tick.substring(0, %d-2) + '...';
            else return tick;
        """ % (max_lbl_len, max_lbl_len))
    if ptype in ["nested", "stacked"]:
        fig.y_range.start = 0
        fig.x_range.range_padding = 0.03
        fig.xgrid.grid_line_color = None
Ejemplo n.º 14
0
    def specific_set(self, x_offers, firing_rate, percents_B, y_range=None,
                     title='', size=SIZE):
        """Figure 4C, 4G, 4K"""
        fig = ubkh.figure(title=title, plot_width=size, plot_height=size,
                         tools=TOOLS,
                         y_range=(y_range[0] - 0.05 * (y_range[1] - y_range[0]), y_range[1]))

        self.set_x_ticks(fig, list(range(len(x_offers))))
        fig.xaxis.formatter = FuncTickFormatter(code="""
            var labels = {};
            return labels[tick];
        """.format({i: '{}B:{}A'.format(x_B, x_A) for i, (x_A, x_B) in enumerate(x_offers)}))
        fig.xaxis.major_label_orientation = np.pi / 2

        y_min, y_max = y_range
        K = 0.94 * (y_max - y_min) + y_min
        xs = [x_offers.index(key) for key in percents_B.keys()]
        ys = [y * 0.94 * (y_max - y_min) + y_min for y in percents_B.values()]

        fig.line(x=(min(xs), max(xs)), y=(K, K), color="black", line_dash='dashed')
        fig.circle(x=xs, y=ys, color="black", size=15)

        r_A, r_B = firing_rate
        xs_A = [x_offers.index(key) for key in r_A.keys()]
        xs_B = [x_offers.index(key) for key in r_B.keys()]

        fig.diamond(x=xs_A, y=list(r_A.values()), size=15, color=A_color, alpha=0.75)
        fig.circle( x=xs_B, y=list(r_B.values()), size=10, color=B_color, alpha=0.75)

        self.save_and_show(fig, title)
Ejemplo n.º 15
0
def plot_bokeh(topics, eigenvalues):
    top_words = get_top_words(topics)
    topic_num = len(topics.keys())
    word_num = len(top_words)

    X, Y, S, C = [], [], [], []
    for x in topics:
        for item in topics[x]:
            word = item[1]
            radi = item[0]
            X.append(x)
            Y.append(top_words.index(word))
            S.append(abs(radi)**2 * 40)
            C.append(eigenvalues[x])

    p = figure(title="Reduce Dimension")
    p.circle(X, Y, fill_color='blue', fill_alpha=0.2, size=S)
    p.x_range = Range1d(-1, topic_num)
    p.xaxis.ticker = FixedTicker(ticks=range(topic_num))
    p.xgrid.minor_grid_line_color = 'grey'
    p.xgrid.minor_grid_line_alpha = 0.2
    p.ygrid.minor_grid_line_color = 'grey'
    p.ygrid.minor_grid_line_alpha = 0.2
    p.y_range = Range1d(word_num, -1)
    data = {}
    for i in range(word_num):
        data[i] = str(top_words[i])
    p.yaxis.ticker = FixedTicker(ticks=range(word_num))
    p.yaxis.formatter = FuncTickFormatter(code="""
        var data = %s;
        return data[tick];
        """ % data)
    return p
Ejemplo n.º 16
0
def show_p2():
    p2 = figure(title='p3: Sales of 5 best selling products',
               x_axis_label='date',
               y_axis_label='daily sales')
    output_file('p3.html')
    lx_orig,ly = get_lists()
    lx = lx_orig
    
    colors_list=['blue','yellow','green','red','purple']
    legends_list = []
    labels = best5.ix[:,0]
    labels1 = ['ID '+str(labels[n]) for n in best5.index]
    
    for i in np.arange(5):
        legends_list.append(labels1[i])
    
    
    for (c,l,x,y) in zip(colors_list, legends_list, lx, ly):
        p2.line(x,y,color=c, legend=l, line_width=3)
        
    from bokeh.models import FuncTickFormatter
    p2.legend.location = 'bottom_right'
    
    # Change the xaxis label
    kk = best5_1.ix[1:-1].keys()
    kk_noyear = [d[0:-5] for d in kk] # Remove years (e.g. '/2013')
    kk_js = [str(s) for s in kk_noyear] # Remove u prefix (e.g. u'...') from strings.

    p2.xaxis[0].formatter = FuncTickFormatter(code="""
        var tlabels = %s;
        return tlabels[tick];
"""%repr(kk_js))    
    show(p2)
Ejemplo n.º 17
0
def apply_axis_formatter(plot, element):
    plot.handles['xaxis'].formatter = bokeh.models.DatetimeTickFormatter(hourmin = '%H:%M', 
                                                                         minutes='%H:%M', 
                                                                         minsec='%H:%M:%S',
                                                                         seconds='%H:%M:%S')
    plot.handles['yaxis'].formatter = FuncTickFormatter(code="""return Math.abs(tick)""")
    plot.handles['xaxis'].axis_label = "UTC time [min]"
    plot.handles['yaxis'].axis_label = "Distance [km]"
Ejemplo n.º 18
0
def tweak_figure(fig: Figure) -> None:
    """
    Set some common attributes for a figure
    """
    fig.grid.grid_line_color = None
    fig.axis.axis_line_color = None
    fig.axis.major_tick_line_color = None
    fig.axis.major_label_text_font_size = "9pt"
    fig.axis.major_label_standoff = 0
    fig.xaxis.major_label_orientation = np.pi / 3
    # truncate axis tick values
    format_js = """
        if (tick.length > 15) return tick.substring(0, 13) + '...';
        else return tick;
    """
    fig.xaxis.formatter = FuncTickFormatter(code=format_js)
    fig.yaxis.formatter = FuncTickFormatter(code=format_js)
Ejemplo n.º 19
0
    def update_plot_after_montage_change(self):

        self.fig.title.text = self.title
        goto_sample = int(self.fs * self.loc_sec)
        page_width_samples = int(self.page_width_secs * self.fs)

        hw = half_width_epoch_sample = int(page_width_samples / 2)
        s0 = limit_sample_check(goto_sample - hw, self.signals)
        s1 = limit_sample_check(goto_sample + hw, self.signals)

        window_samples = s1 - s0
        signal_view = self.signals[:, s0:s1]
        inmontage_view = np.dot(self.current_montage_instance.V.data,
                                signal_view)
        self.ch_start = 0
        self.ch_stop = inmontage_view.shape[0]

        numRows = inmontage_view.shape[0]  # ???
        # print('numRows: ', numRows)

        data = inmontage_view[self.ch_start:self.ch_stop, :]  # note transposed
        # really just need to reset the labels

        ticklocs = []

        ## xlim(*xlm)
        # xticks(np.linspace(xlm, 10))
        dmin = data.min()
        dmax = data.max()
        dr = (dmax - dmin) * 0.7  # Crowd them a bit.
        y0 = dmin
        y1 = (numRows - 1) * dr + dmax
        ## ylim(y0, y1)

        ticklocs = [ii * dr for ii in range(numRows)]
        ticklocs.reverse()  # inplace
        bottom = -dr / 0.7
        top = (numRows - 1) * dr + dr / 0.7
        self.y_range.start = bottom
        self.y_range.end = top
        # self.fig.y_range = Range1d(bottom, top)

        # print("ticklocs:", ticklocs)

        offsets = np.zeros((numRows, 2), dtype=float)
        offsets[:, 1] = ticklocs
        self.ticklocs = ticklocs
        # self.time = t

        ylabels = self.current_montage_instance.montage_labels
        ylabel_dict = dict(zip(ticklocs, ylabels))
        # print('ylabel_dict:', ylabel_dict)
        self.fig.yaxis.ticker = FixedTicker(
            ticks=ticklocs)  # can also short cut to give list directly
        self.fig.yaxis.formatter = FuncTickFormatter(code="""
            var labels = %s;
            return labels[tick];
        """ % ylabel_dict)
Ejemplo n.º 20
0
    def _init_figure(self):
        # plot height will be set later
        f = figure(tools=Figure._tools, plot_width=self._scheme.plot_width, logo=None, sizing_mode='scale_width', x_axis_type='linear')
        # TODO: backend webgl (output_backend="webgl") removed due to this bug:
        # https://github.com/bokeh/bokeh/issues/7568

        f.border_fill_color = convert_color(self._scheme.border_fill)

        f.xaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.yaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.xaxis.minor_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.yaxis.minor_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.xaxis.major_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.yaxis.major_tick_line_color = convert_color(self._scheme.tick_line_color)

        f.xaxis.major_label_text_color = convert_color(self._scheme.axis_label_text_color)
        f.yaxis.major_label_text_color = convert_color(self._scheme.axis_label_text_color)

        f.xgrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.ygrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.title.text_color = convert_color(self._scheme.plot_title_text_color)

        f.left[0].formatter.use_scientific = False
        f.background_fill_color = convert_color(self._scheme.background_fill)

        # mechanism for proper date axis without gaps, thanks!
        # https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/t3HkalO4TGA
        f.xaxis.formatter = FuncTickFormatter(
            args=dict(
                axis=f.xaxis[0],
                formatter=DatetimeTickFormatter(days=['%d %b', '%a %d'],
                                                months=['%m/%Y', "%b %y"]),
                source=self._cds,
            ),
            code="""
                axis.formatter.doFormat = function (ticks) {
                    const dates = ticks.map(i => source.data.datetime[i]),
                          valid = t => t !== undefined,
                          labels = formatter.doFormat(dates.filter(valid));
                    let i = 0;
                    return dates.map(t => valid(t) ? labels[i++] : '');
                };
                const axisticks = axis.tick_coords.major[0],
                      labels = axis.formatter.doFormat(ticks);
                return labels[axisticks.indexOf(tick)];
        """)

        ch = CrosshairTool(line_color=self._scheme.crosshair_line_color)
        f.tools.append(ch)

        h = HoverTool(tooltips=[('Time', '@datetime{%x %X}')],
                      mode="vline",
                      formatters={'datetime': 'datetime'}
                      )
        f.tools.append(h)

        self._hover = h
        self.figure = f
Ejemplo n.º 21
0
    def _setup_plot(self):
        plots_width = self._config['plot_width']
        plots_height = self.plot_height
        p = self._p

        p.plot_width = plots_width
        p.plot_height = plots_height

        # -> other attributes are set via theme.yaml

        # disable x grid lines
        p.xgrid.grid_line_color = None

        p.ygrid.grid_line_color = 'navy'
        p.ygrid.grid_line_alpha = 0.13
        p.ygrid.minor_grid_line_color = 'navy'
        p.ygrid.minor_grid_line_alpha = 0.05

        p.toolbar.logo = None  # hide the bokeh logo (we give credit at the
        # bottom of the page)

        #p.lod_threshold=None # turn off level-of-detail

        # axis labels: format time
        if self._use_time_formatter:
            p.xaxis[0].formatter = FuncTickFormatter(
                code='''
                    //func arguments: ticks, x_range
                    // assume us ticks
                    ms = Math.round(tick / 1000)
                    sec = Math.floor(ms / 1000)
                    minutes = Math.floor(sec / 60)
                    hours = Math.floor(minutes / 60)
                    ms = ms % 1000
                    sec = sec % 60
                    minutes = minutes % 60

                    function pad(num, size) {
                        var s = num+"";
                        while (s.length < size) s = "0" + s;
                        return s;
                    }

                    if (hours > 0) {
                        var ret_val = hours + ":" + pad(minutes, 2) + ":" + pad(sec,2)
                    } else {
                        var ret_val = minutes + ":" + pad(sec,2);
                    }
                    if (x_range.end - x_range.start < 4e6) {
                        ret_val = ret_val + "." + pad(ms, 3);
                    }
                    return ret_val;
                ''',
                args={'x_range': p.x_range})

        # make it possible to hide graphs by clicking on the label
        p.legend.click_policy = "hide"
Ejemplo n.º 22
0
def clock_ms_tick_formatter() -> TickFormatter:
    milliseconds_since_epoch = 0
    return FuncTickFormatter(
        code="""
        var d = new Date(initial + tick);
        return "" + d.getHours() + ":" + ("00" + d.getMinutes()).slice(-2) + ":" + ("00" + d.getSeconds()).slice(-2);
        """,
        args={"initial": milliseconds_since_epoch},
    )
Ejemplo n.º 23
0
def callback4(attr, old, new):
    column4plot = p4_widget.value
    if int(column4plot[-2:]) > 9:
        num = column4plot[-2:]
    else:
        num = column4plot[-1:]
    data_4.data = {'x': days, 'y': list(bike_days_tot_perc[num])}
    p4.line('x', 'y', source=data_4, color='red', line_width=2)
    p4.xaxis.formatter = FuncTickFormatter(code="""
    var labels = %s;
    return labels[tick];
""" % label_dict)
Ejemplo n.º 24
0
def callback5(attr, old, new):
    column5plot = p5_widget.value
    if int(column5plot[-2:]) > 9:
        num = column5plot[-2:]
    else:
        num = column5plot[-1:]
    data_5.data = {'x': months, 'y': list(bike_months_tot_perc[num])}
    p5.line('x', 'y', source=data_5, color='red', line_width=2)
    p5.xaxis.formatter = FuncTickFormatter(code="""
    var labels = %s;
    return labels[tick];
""" % label_dict_m)
Ejemplo n.º 25
0
def _generate_users_weekly_graph(users, append_report_name):
    """Generate a chart showing days & times users comment most frequently.

       users    - a dictionary of users & their data {'user_name':rows}
       append_report_name   - help name the report appropriately
    """

    output_file(
        os.path.join(
            working_dir, './output/users_{append_report_name}.html'.format(
                append_report_name=append_report_name)))

    time_24h = [i for i in range(1, 25)]

    plots = list()
    for user, rows in users.items():
        p = figure(y_range=(0,8), x_range=(0,25),
                width=800,
                height=500,
                title='/u/{user} posting schedule'.format(user = user),
                y_axis_label='Day',
                x_axis_label='Hour ({tz})'.format(tz = \
                        time.tzname[0] + '/' + time.tzname[1]))
        # ^^^ assumes your sql server is set to same timezone
        # as the computer running this script
        # TODO: allow orientation to time zone by modifying
        #   the SQL queries w/ "AT TIME ZONE 'UTC'"

        for i, row in enumerate(rows, start=1):
            x = [i] * 24
            p.circle(time_24h, x, size=row[1:], fill_alpha=0.6)

        labels = {
            0: '',
            1: 'Sunday',
            2: 'Monday',
            3: 'Tues',
            4: 'Wed',
            5: 'Thu',
            6: 'Fri',
            7: 'Sat',
            8: ''
        }
        p.yaxis.formatter = FuncTickFormatter(code="""
            var labels = {};
            return labels[tick];
        """.format(labels))

        plots.append(p)

    document = column(plots)
    save(document)
Ejemplo n.º 26
0
def get_plot(name='spectrogram'):
    data = ColumnDataSource(
        data=dict(spectrogram=[]),
        name=name,
    )
    variables = ColumnDataSource(
        data=dict(fc=[2e9], bw=[20e6], size=[512]),
        name=name + '_vars',
    )
    plot = figure(
        plot_height=300,
        plot_width=400,
        title="Spectrum Waterfall",
        # tools="crosshair,pan,reset,save,wheel_zoom",
        tools="",
        toolbar_location=None,
        x_range=(0, 1000),
        y_range=(0, 500),
        output_backend="webgl",
    )
    usrp_image = plot.image(
        image='spectrogram',
        source=data,
        x=0,
        y=0,
        dw=1000,
        dh=500,
        palette="Viridis256",
    )

    plot.xaxis.axis_label = "Time [sample]"
    plot.yaxis.axis_label = "Frequency [GHz]"
    plot.yaxis[0].formatter = FuncTickFormatter(args=dict(conf=variables),
                                                code="""
        var fc = conf.data.fc[0];
        var bw = conf.data.bw[0];
        var size = conf.data.size[0];
        var result = fc - bw / 2 + (tick + 1) * bw / 500;
        return (result / 1e9).toPrecision(4);
    """)
    usrp_txt = Title(text='', text_font_size='12px', align='right')
    usrp_callback = CustomJS(args=dict(source=usrp_txt),
                             code="""
        var fc = (cb_obj.data.fc[0] / 1e9).toPrecision(4);
        var bw = (cb_obj.data.bw[0] / 1e6).toPrecision(2);
        var size = cb_obj.data.size[0];
        source.text = "Center frequency: " + fc
            + " GHz, Bandwidth: " + bw + " MHz, FFT size: " + size;
    """)
    variables.js_on_change('data', usrp_callback)
    plot.add_layout(usrp_txt, "below")
    return plot
Ejemplo n.º 27
0
def callback2(attr, old, new):
    column3plot = p3_widget.value
    if int(column3plot[-2:]) > 9:
        num = column3plot[-2:]
    else:
        num = column3plot[-1:]
    data_m.data = {'x': months, 'y': list(bike_months_med[num])}
    p3.vbar(x='x', top='y', source=data_m, width=0.9, line_color='white')
    p3.line('x', 'y', source=data_m, color='blue', line_width=2)
    p3.xaxis.formatter = FuncTickFormatter(code="""
    var labels = %s;
    return labels[tick];
""" % label_dict_m)
Ejemplo n.º 28
0
        def callback():
            with self.measure("rendering seeds"):
                # render ambiguous regions on top and left
                self.seed_plot.ambiguous_regions.data = read_ambiguous_reg_dict

                # render seeds on top and left
                self.seed_plot.seeds.data = read_dict
                if self.seed_plot.left_plot.x_range.start == 0 and self.seed_plot.left_plot.x_range.end == 0:
                    self.seed_plot.left_plot.x_range.start = -1
                    self.seed_plot.left_plot.x_range.end = category_counter

                if len(self.read_ids) <= self.do_compressed_seeds:
                    self.seed_plot.left_plot.xaxis.ticker = FixedTicker(ticks=col_ids)
                    self.seed_plot.bottom_plot.yaxis.ticker = FixedTicker(ticks=col_ids)
                    self.seed_plot.left_plot.xaxis.formatter = FuncTickFormatter(
                        args={"read_id_n_cols": read_id_n_cols},
                        code="""
                                if(!tick in read_id_n_cols)
                                    return "";
                                return read_id_n_cols[tick];
                            """)
                    self.seed_plot.bottom_plot.yaxis.formatter = FuncTickFormatter(
                        args={"read_id_n_cols": read_id_n_cols},
                        code="""
                                if(!tick in read_id_n_cols)
                                    return "";
                                return read_id_n_cols[tick];
                            """)
                    self.seed_plot.left_plot.xaxis.axis_label = "Read Id"
                    self.seed_plot.bottom_plot.yaxis.axis_label = "Read Id"
                else:
                    self.seed_plot.left_plot.xaxis.ticker = []
                    self.seed_plot.left_plot.xaxis.axis_label = "compressed seeds"
                    self.seed_plot.bottom_plot.yaxis.ticker = []
                    self.seed_plot.bottom_plot.yaxis.axis_label = "compressed seeds"
                self.seed_plot.left_plot.xgrid.ticker = FixedTicker(ticks=all_col_ids)
                self.seed_plot.bottom_plot.ygrid.ticker = FixedTicker(ticks=all_col_ids)

                self.seed_plot.update_selection(self)
Ejemplo n.º 29
0
def callback(attr, old, new):
    column2plot = p2_widget.value
    if int(column2plot[-2:]) > 9:
        num = column2plot[-2:]
    else:
        num = column2plot[-1:]
    data.data = {'x': days, 'y': list(bike_days_med[num])}
    p2.vbar(x='x', top='y', source=data, width=0.9, line_color='white')
    p2.line('x', 'y', source=data, color='blue', line_width=2)
    p2.xaxis.formatter = FuncTickFormatter(code="""
    var labels = %s;
    return labels[tick];
""" % label_dict)
Ejemplo n.º 30
0
    def get_bar_chart(cls):
        tooltip_fields = [
            ('Tr. code', '@tr_code'),
            ('Survey', '@survey_id (@survey_name)'),
            ('Form Type', '@form_type'),
            ('Text', '@text')
        ]

        for col in ANALYSED_COLS:
            bar_char_title = col.replace('_', ' ').title()
            tooltip_fields.append((bar_char_title, '@{}'.format(col)))

        hover = HoverTool(tooltips=App.format_tooltip_fields(tooltip_fields))

        bc = figure(
            plot_height=400,
            plot_width=PAGE_WIDTH // 2 - 50,
            toolbar_location=None,
            tools=[hover],
            title="Select question",
            y_range=Range1d(0, 1)
        )

        src = ColumnDataSource(Data.bar_chart_df)
        bc.vbar(
            x="index",
            top="similarity",
            bottom=0,
            width=0.5,
            fill_color="color",
            source=src
        )

        bc.xaxis[0].ticker.desired_num_ticks = MAX_BARS
        bc.yaxis.axis_label = 'similarity'
        bc.xaxis.axis_label = 'question'
        bc.xaxis.major_label_orientation = 1

        tr_code = Data.res_df.iloc[Data.selected_result_index].name
        bc.title.text = 'Top {} similar questions for question {}'.format(MAX_BARS, tr_code)

        labels = dict([(i, Data.bar_chart_df.iloc[i]['tr_code']) for i in range(len(Data.bar_chart_df))])
        bc.xaxis.formatter = FuncTickFormatter(code="""var labels = {}; return labels[tick]; """.format(labels))

        def on_tap(event):
            index = round(event.x)
            cls.select_bar_handler(index)

        bc.on_event(Tap, on_tap)

        return components(bc)