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 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.º 5
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.º 6
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.º 7
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.º 8
0
    def trip_fare_init(self, width=310, height=350, webgl=True):
        def ticker():
            labels = {
                0: '0~5',
                1: '5~10',
                2: '10~25',
                3: '25~50',
                4: '50~100',
                5: '>100'
            }
            return labels[tick]

        self.trip_fare = figure(webgl=webgl,
                                toolbar_location=None,
                                width=width,
                                height=height,
                                title='Fare (US dolloars)')
        self.trip_fare_source = ColumnDataSource(
            data=dict(x=range(6), fare=self.data.get_fare()))
        vbar = self.trip_fare.vbar(width=1,
                                   bottom=0,
                                   x='x',
                                   top='fare',
                                   source=self.trip_fare_source,
                                   fill_alpha=0.7,
                                   line_color="white",
                                   color='#ffcc5c')
        self.trip_fare.y_range.start = 0
        self.trip_fare.xaxis.major_tick_line_color = None
        self.trip_fare.xaxis.minor_tick_line_color = None
        self.trip_fare.xaxis.formatter = FuncTickFormatter.from_py_func(ticker)

        self.trip_fare.select(dict(type=GlyphRenderer))
        self.trip_fare.add_tools(
            HoverTool(renderers=[vbar], tooltips=[("Trips", "@fare")]))
Ejemplo n.º 9
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.º 10
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.º 11
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.º 12
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.º 13
0
def systemEvolutionBarPlot(df, yLabel, values):
    with Timer(key='systemEvolutionBarPlot', verbose=True):
        p = Bar(df, label='snapshot', values=values, agg='sum', stack='software',
            legend='bottom_left', bar_width=0.5, xlabel="Snapshots", ylabel=yLabel, responsive=True, height=200,tools='hover')

        glyph_renderers = p.select(GlyphRenderer)
        bar_source = [glyph_renderers[i].data_source for i in range(len(glyph_renderers))]
        hover = p.select(HoverTool)
        hover.tooltips = [
            ('software',' @software'),
            ('value', '@height'),
        ]
        p.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        p.axis.minor_tick_line_color = None

        p.background_fill_color = "#fafafa"
        p.legend.location = "top_left"
        p.toolbar.logo = None
        p.toolbar_location = None

        legend=p.legend[0].legends
        p.legend[0].legends=[]
        l = Legend( location=(0, -30))
        l.items=legend
        p.add_layout(l, 'right')

        return p
Ejemplo n.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
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.º 23
0
    def _axis_properties(self,
                         axis,
                         key,
                         plot,
                         dimension,
                         ax_mapping={
                             'x': 0,
                             'y': 1
                         }):
        """
        Returns a dictionary of axis properties depending
        on the specified axis.
        """
        axis_props = {}
        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])):
            axis_props['axis_label'] = ''
            axis_props['major_label_text_font_size'] = '0pt'
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    pass
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        if FuncTickFormatter is not None and ax_mapping and dimension:
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                try:
                    formatter = FuncTickFormatter.from_py_func(formatter)
                except RuntimeError:
                    self.warning(msg + 'Ensure Flexx is installed '
                                 '("conda install -c bokeh flexx" or '
                                 '"pip install flexx")')
                except Exception as e:
                    error = 'Pyscript raised an error: {0}'.format(e)
                    error = error.replace('%', '%%')
                    self.warning(msg + error)
                else:
                    axis_props['formatter'] = formatter
        return axis_props
Ejemplo n.º 24
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.º 25
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.º 26
0
def test_functickformatter_from_coffeescript_with_args():
    coffee_code = "return slider.get('value') + tick"
    js_code = "\n  return slider.get('value') + tick;\n"

    slider = Slider()
    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code, args={"slider": slider})

    function_wrapper = formatter.code.replace(js_code, "")
    assert function_wrapper == "var formatter;\n\nformatter = function() {};\n\nreturn formatter()"
    assert formatter.args == {"slider": slider}
Ejemplo n.º 27
0
def test_functickformatter_from_py_func():
    def convert_to_minutes(seconds):
        return seconds * 60

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "function (seconds) {return formatter(seconds)};"
Ejemplo n.º 28
0
def test_functickformatter_from_py_func_no_args():
    def convert_to_minutes():
        return tick * 60  # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "return formatter();\n"
Ejemplo n.º 29
0
def test_functickformatter_from_py_func_no_args():

    def convert_to_minutes():
        return tick * 60 # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "formatter();\n"
Ejemplo n.º 30
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.º 31
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.º 32
0
def test_functickformatter_from_coffeescript_with_args():
    coffee_code = dedent("""
         return slider.get("value") // 2 + tick
         """)

    slider = Slider()
    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code, args={"slider": slider})

    assert formatter.code == dedent("""\
        return Math.floor(slider.get("value") / 2) + tick;
        """)
    assert formatter.args == {"slider": slider}
Ejemplo n.º 33
0
def test_functickformatter_from_py_func():

    def convert_to_minutes(seconds):
        return seconds * 60

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "function (seconds) {return formatter(seconds)};"
    assert formatter.lang == "javascript"
Ejemplo n.º 34
0
def evolutionCharts(df):


    df['week']= df['snapshot'].apply(getWeekString)
    df = df[df['end'].notnull()]
    df=df.sort(['snapshot'], ascending=[1])
    df['snapshotId']= range(1, len(df) + 1)

    source = ColumnDataSource(df)




    plots={'size':evolSize(source,df)}

    last=None
    for q in qa:
        pt = figure(   plot_width=600, plot_height=200
                , min_border=10, min_border_left=50
                , toolbar_location="above",responsive=True)
        pt.background_fill_color = "#fafafa"
        pt.legend.location = "top_left"
        pt.toolbar.logo = None
        pt.toolbar_location = None
        hit_renderers = []
        legends=[]
        for m,v in q['metrics'].items():
            l=pt.line(x='snapshotId',y=m.lower(), line_width=2,source=source, color=v['color'])
            c=pt.circle(x='snapshotId',y=m.lower(), line_width=2,source=source, color=v['color'])
            # invisible circle used for hovering
            hit_target =Circle(x='snapshotId',y=m.lower(), size=10,line_color=None, fill_color=None)
            hit_renderer = pt.add_glyph(source, hit_target)

            legends.append((v['label']+" ["+m.lower()+"]",[l,c]))

            pt.add_tools(HoverTool(renderers=[hit_renderer], tooltips={'Metric':v['label'], "Week": "@week", 'Value':"@"+m.lower()}))
            pt.xaxis[0].ticker.desired_num_ticks = df.shape[0]/2


        pt.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        pt.axis.minor_tick_line_color = None

        legend = Legend(location=(0, -30))
        legend.items=legends
        pt.add_layout(legend, 'right')

        pt.xaxis[0].axis_label = 'Snapshot'
        pt.yaxis[0].axis_label = 'Average quality'

        plots[q['dimension']]=pt
        last=pt

    return plots
Ejemplo n.º 35
0
def test_functickformatter_from_coffeescript_no_arg():
    coffee_code = """
    square = (x) -> x * x
    return square(tick)
    """

    js_code = "\n  var square;\n  square = function(x) {\n    return x * x;\n  };\n  return square(tick);\n"

    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code)
    function_wrapper = formatter.code.replace(js_code, "")

    assert function_wrapper == "var formatter;\n\nformatter = function() {};\n\nreturn formatter()"
    assert formatter.args == {}
Ejemplo n.º 36
0
def test_functickformatter_from_coffeescript_with_args():
    coffee_code = dedent("""
         return slider.get("value") // 2 + tick
         """)

    slider = Slider()
    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code, args={"slider": slider})

    assert formatter.code == dedent("""\
        "use strict";
        Object.defineProperty(exports, "__esModule", { value: true });
        return Math.floor(slider.get("value") / 2) + tick;
        """)
    assert formatter.args == {"slider": slider}
Ejemplo n.º 37
0
    def _axis_properties(self, axis, key, plot, dimension,
                         ax_mapping={'x': 0, 'y': 1}):
        """
        Returns a dictionary of axis properties depending
        on the specified axis.
        """
        axis_props = {}
        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])):
            axis_props['axis_label'] = ''
            axis_props['major_label_text_font_size'] = '0pt'
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    pass
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        if FuncTickFormatter is not None and ax_mapping and dimension:
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                try:
                    formatter = FuncTickFormatter.from_py_func(formatter)
                except RuntimeError:
                    self.warning(msg+'Ensure Flexx is installed '
                                 '("conda install -c bokeh flexx" or '
                                 '"pip install flexx")')
                except Exception as e:
                    error = 'Pyscript raised an error: {0}'.format(e)
                    error = error.replace('%', '%%')
                    self.warning(msg+error)
                else:
                    axis_props['formatter'] = formatter
        return axis_props
Ejemplo n.º 38
0
def test_functickformatter_from_py_func_with_args():

    slider = Slider()

    def convert_to_minutes(x=slider):
        return tick * 60 # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "formatter(x);\n"
    assert formatter.args['x'] is slider
Ejemplo n.º 39
0
def test_functickformatter_from_coffeescript_no_arg():
    coffee_code = dedent("""
        square = (x) -> x * x
        return square(tick)
        """)

    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code)

    assert formatter.code == dedent("""\
        var square;
        square = function (x) {
            return x * x;
        };
        return square(tick);
        """)
    assert formatter.args == {}
Ejemplo n.º 40
0
def test_functickformatter_from_coffeescript_no_arg():
    coffee_code = dedent("""
        square = (x) -> x * x
        return square(tick)
        """)

    formatter = FuncTickFormatter.from_coffeescript(code=coffee_code)

    assert formatter.code == dedent("""\
        "use strict";
        Object.defineProperty(exports, "__esModule", { value: true });
        var square;
        square = function (x) {
            return x * x;
        };
        return square(tick);
        """)
    assert formatter.args == {}
Ejemplo n.º 41
0
def test_functickformatter_bad_pyfunc_formats():
    def has_positional_arg(x):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg)

    def has_positional_arg_with_kwargs(y, x=5):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg_with_kwargs)

    def has_non_Model_keyword_argument(x=10):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_non_Model_keyword_argument)
    df['Gun_Seconds'] = map(lambda i: time_to_seconds(i),df['Gun Tim'])
    df['Pace'] = map(lambda i: time_to_seconds(i),df['Pace'])

    #df['Net Tim']= map(lambda i: if (str(i).split(':')),df['Div/Tot'])
together = pd.concat(dfs)
together['Rank'] = together['Net_Seconds'].rank()
gun_color_women ="#ff3399"
gun_color_men ='#0000ff'
net_color_women ="#9900cc"
net_color_men = "#006666"


####PLOT ONE#### DATA DISTRIBUTIONS - GUN TIME

plot_one = figure(plot_width=900,plot_height=500)
plot_one.xaxis.formatter = FuncTickFormatter.from_py_func(seconds_formatted)
#hover_one =HoverTool(
#        tooltips=[
#            ("index", "$index"),
#            ("(x,y)", "($x, $y)"),
#            ("desc", "@desc"),
#        ]
#    )


plot_one.add_tools(HoverTool())
#WOMEN
density = stats.kde.gaussian_kde(females['Gun_Seconds'].dropna())
x = np.arange(0.,max(females['Gun_Seconds'].dropna()), 1)
y = [density(y) for y in x]