Beispiel #1
0
def prepare_fig(fig,
                grid=False,
                tight=True,
                minimalist=True,
                xgridlines=None,
                ygridlines=None,
                **kwargs):
    if fig is None:
        if 'tools' not in kwargs:
            kwargs['tools'] = TOOLS
        if 'title_text_font_size' not in kwargs:
            kwargs['title_text_font_size'] = value('6pt')

        fig = plotting.figure(**kwargs)
        if minimalist:
            three_ticks(fig)
            disable_minor_ticks(fig)
        if tight:
            tight_layout(fig)
        if not grid:
            disable_grid(fig)
        else:
            if xgridlines is not None:
                fig.xgrid.ticker = FixedTicker(ticks=xgridlines)
            if ygridlines is not None:
                fig.ygrid.ticker = FixedTicker(ticks=ygridlines)

    return fig
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
Beispiel #3
0
 def plot_constellation(self,fig=None):
     '''
     Plot a constellation diagram representing the modulation scheme.
     '''
     from .sigproc import NOTEBOOK_SESSION
     if not NOTEBOOK_SESSION:
         raise Exception("This function is only available in a notebook session")
     from .sigproc import bkp
     from bokeh.models import ColumnDataSource,FixedTicker,LabelSet
     x,y,bits = zip(*self.constellation)
     source = ColumnDataSource(data=dict(x=x,y=y,bits=bits))
     bound = ceil(max(abs(v) for v in x+y)) + 0.5
     fig_created = False
     if fig is None:
         fig_created = True
         fig = bkp.figure(
                 height=300,
                 width=400,
                 x_range=(-bound,bound),
                 y_range=(-bound,bound),
                 )
     fig.segment(-bound,0,bound,0,color="green",line_width=2)
     fig.segment(0,-bound,0,bound,color="green",line_width=2)
     fig.scatter(x="x",y="y",size=10,source=source,line_color="black",fill_color="red")
     set_aspect(fig,(-bound,bound),(-bound,bound))
     fig.xaxis[0].ticker = FixedTicker(ticks=np.arange(-bound,bound+0.5,0.5))
     fig.xgrid[0].ticker = FixedTicker(ticks=np.arange(-bound,bound+0.5,0.1))
     fig.yaxis[0].ticker = FixedTicker(ticks=np.arange(-bound,bound+0.5,0.5))
     fig.ygrid[0].ticker = FixedTicker(ticks=np.arange(-bound,bound+0.5,0.1))
     fig.add_layout(LabelSet(x="x",y="y",text="bits",x_offset=5,y_offset=5,text_font_size="8pt",source=source))
     if fig_created:
         bkp.show(fig)
     else:
         return fig
Beispiel #4
0
def three_ticks(fig):
    x_min, x_max = fig.x_range.start, fig.x_range.end
    y_min, y_max = fig.y_range.start, fig.y_range.end
    x_ticks = [x_min, 0, x_max]
    y_ticks = [x_min, 0, x_max]

    fig.xaxis[0].ticker = FixedTicker(ticks=x_ticks)
    fig.yaxis[0].ticker = FixedTicker(ticks=y_ticks)
Beispiel #5
0
def generateNavigatorFigure(dataframe, i, title):

    global pixelsForTitle;
    global pixelsPerHeightUnit;
    global plotWidth;

    # Generate the colors, such that the current interval is shown in a
    # different color than the rest.
    #
    numIntervals = dataframe['intervalnumber'].size;
    color = ["white" for x in range(numIntervals)];
    color[i] = "salmon";
    dataframe['color'] = color;

    cds = ColumnDataSource(dataframe);

    title = title + " CLICK TO NAVIGATE";

    hover = HoverTool(tooltips = [
        ("interval #", "@intervalnumber"),
        ("interval start", "@intervalbegin{0,0}"),
        ("interval end", "@intervalend{0,0}")]);

    TOOLS = [hover, "tap"];

    p = figure(title = title, plot_width = plotWidth,
               x_range = (0, numIntervals),
               plot_height =  2 * pixelsPerHeightUnit + pixelsForTitle,
               x_axis_label = "",
               y_axis_label = "", tools = TOOLS,
               toolbar_location="above");

    # No minor ticks or labels on the y-axis
    p.yaxis.major_tick_line_color = None;
    p.yaxis.minor_tick_line_color = None;
    p.yaxis.major_label_text_font_size = '0pt';
    p.yaxis.ticker = FixedTicker(ticks = range(0, 1));
    p.ygrid.ticker = FixedTicker(ticks = range(0, 1));

    p.xaxis.formatter = NumeralTickFormatter(format="0,");

    p.title.align = "center";
    p.title.text_font_style = "normal";

    p.quad(left = 'intervalnumber', right = 'intervalnumbernext',
           bottom = 0, top = 2, color = 'color', source = cds,
           nonselection_fill_color='color',
           nonselection_fill_alpha = 1.0,
           line_color = "aliceblue",
           selection_fill_color = "white",
           selection_line_color="lightgrey"
    );

    url = "@bucketfiles";
    taptool = p.select(type=TapTool);
    taptool.callback = OpenURL(url=url);

    return p;
Beispiel #6
0
    def set_tick_marks(self):
        """Set custom locations for the tick marks.
        """
        from bokeh.models import FixedTicker

        if self.xticks:
            self._plot.xaxis[0].ticker = FixedTicker(ticks=self.xticks)
        if self.yticks:
            self._plot.yaxis[0].ticker = FixedTicker(ticks=self.yticks)

        if self.xticklabels_hide:
            self._plot.xaxis.major_label_text_font_size = '0pt'
        if self.yticklabels_hide:
            self._plot.yaxis.major_label_text_font_size = '0pt'
Beispiel #7
0
def three_ticks(fig):
    x_min, x_max = fig.x_range.start, fig.x_range.end
    y_min, y_max = fig.y_range.start, fig.y_range.end
    x_ticks = [x_min, (x_min + x_max) / 2.0, x_max]
    if x_min < 0 < x_max and 0.0 not in x_ticks:
        x_ticks.append(0)
        x_ticks.sort()
    y_ticks = [y_min, (y_min + y_max) / 2.0, y_max]
    if y_min < 0 < y_max and 0.0 not in y_ticks:
        y_ticks.append(0)
        y_ticks.sort()

    fig.xaxis[0].ticker = FixedTicker(ticks=x_ticks)
    fig.yaxis[0].ticker = FixedTicker(ticks=y_ticks)
    def create_legend():
        cm_orient = LinearColorMapper(palette=DARK_COLOURS,
                                      low=-np.pi,
                                      high=np.pi)
        cm_class = LinearColorMapper(
            palette=[hpluv_to_hex((0, 0, 60)),
                     hpluv_to_hex((0, 0, 80))],
            low=0,
            high=2)

        plot = figure(width=200, height=250)
        plot.toolbar_location = None
        plot.border_fill_color = "#FFFFFF"
        plot.outline_line_alpha = 0
        cb_orient = ColorBar(
            title="Orientation",
            major_label_text_font_size="10pt",
            title_text_font_style="bold",
            color_mapper=cm_orient,
            orientation="horizontal",
            ticker=FixedTicker(ticks=[-np.pi, 0, np.pi]),
            major_label_overrides={
                -np.pi: "-π",
                0: "0",
                np.pi: "π"
            },
            width=100,
            major_tick_line_color=None,
            location=(0, 120),
        )
        cb_class = ColorBar(
            color_mapper=cm_class,
            title="Classification",
            major_label_text_font_size="10pt",
            title_text_font_style="bold",
            orientation="vertical",
            ticker=FixedTicker(ticks=[0.5, 1.5]),
            major_label_overrides={
                0.5: "Crystal",
                1.5: "Liquid"
            },
            label_standoff=15,
            major_tick_line_color=None,
            width=20,
            height=80,
            location=(0, 0),
        )
        plot.add_layout(cb_orient)
        plot.add_layout(cb_class)
        return plot
Beispiel #9
0
def plot_spectrogram():
    # Spectrogram image
    plt = figure(plot_width=WIDTHS[0],
                 plot_height=HEIGHTS[0],
                 toolbar_location=None,
                 tools="",
                 x_range=[0, SPEC_WIDTH],
                 y_range=[0, SPEC_HEIGHT])

    plt.image('value',
              x=0,
              y=0,
              dw=SPEC_WIDTH,
              dh=SPEC_HEIGHT,
              name='spectrogram',
              color_mapper=LinearColorMapper(SPEC_PALETTE, low=0, high=100),
              source=SPECTROGRAM)

    # X ticks
    plt.xaxis[0].ticker = FixedTicker(ticks=[])

    # X axis
    plt.xaxis.axis_line_color = None

    # Y ticks
    plt.yaxis[0].ticker = FixedTicker(ticks=[])
    plt.yaxis.major_label_text_font_size = '0pt'
    plt.yaxis.major_tick_line_color = None

    # Y axis
    plt.yaxis.axis_line_color = None
    plt.yaxis.axis_label = 'Mel bands'
    plt.yaxis.axis_label_text_font = TEXT_FONT
    plt.yaxis.axis_label_text_font_size = '8pt'
    plt.yaxis.axis_label_text_font_style = 'normal'

    # Plot fill/border
    plt.background_fill_color = GRID_COLOR
    plt.outline_line_color = GRID_COLOR
    plt.min_border = 10

    # Plot title
    plt.title.text = 'Mel-scaled power spectrogram (perceptually weighted):'
    plt.title.align = 'left'
    plt.title.text_color = TEXT_COLOR
    plt.title.text_font = TEXT_FONT
    plt.title.text_font_size = '9pt'
    plt.title.text_font_style = 'normal'

    return plt
Beispiel #10
0
def make_choropleth(data_source):
    # converts data to right format
    geo_source = GeoJSONDataSource(geojson=data_source)
    # plots countries with colors
    TOOLS = "pan,wheel_zoom,reset,hover,save"
    p = figure(
        title="Grain prices 2015 in USD",
        x_axis_location=None,
        y_axis_location=None,
        width=1200,
        height=700,
        tools=TOOLS,
    )
    p.grid.grid_line_color = None
    p.title.align = "center"
    p.title.text_color = "#084594"
    p.title.text_font_size = "25px"
    p.background_fill_color = '#f7fbff'
    p.background_fill_alpha = 0.5

    p.patches(xs='xs',
              ys='ys',
              fill_color="fill",
              line_color='black',
              line_width=0.5,
              source=geo_source)
    palette = Blues8
    palette.reverse()
    mapper = LinearColorMapper(palette=palette, low=0, high=8 / 6)
    ticker = FixedTicker()
    ticker.ticks = [x / 6 for x in range(1, 8)]
    color_bar = ColorBar(color_mapper=mapper,
                         ticker=ticker,
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0),
                         orientation="horizontal")

    p.add_layout(color_bar, 'below')

    # sets properties of hovertool
    hover = p.select_one(HoverTool)
    hover.point_policy = "follow_mouse"
    hover.tooltips = [("Country:", "@name"), ("Grain price:", "@price"),
                      ("Population:", "@pop"), ("GDP (USD):", "@bbp")]

    output_file("plots/choropleth_grain2015.html", title="World map Bokeh")
    show(p)
def update_graph():
    global numRep, repoNames
    p = figure(plot_width=400,
               plot_height=400,
               title=text.value,
               x_range=usernameList,
               y_range=[0, biggestNumRep + 1],
               toolbar_location=None,
               tools="")
    if response.status_code == 404:
        t = Title()
        t.text = "USER NOT FOUND"
        p.title = t
    p.vbar(x=usernameList,
           width=0.8,
           bottom=0,
           top=numRepList,
           color="firebrick")
    p.yaxis.ticker = FixedTicker(ticks=list(range(0, biggestNumRep + 2)))
    p.yaxis.axis_label = "No. of repositories"

    if response.status_code != 404:
        repoDict = json.loads(response.text)
        repoNames = []
        for entry in repoDict:
            repoNames.append(entry["name"])
        radio = RadioButtonGroup(labels=repoNames, active=0)
        #radio.on_click(specific_repo)
        specific_repo(0)
    else:
        radio = RadioButtonGroup(labels=[])

    newGraph = column(text, radio, row(p, pie), width=1000)
    graphs.children = newGraph.children
Beispiel #12
0
    def specific_set(self, x_offers, firing_rate, percents_B, y_range=None,
                     title='', size=SIZE):
        """Figure 4C, 4G, 4K"""
        fig = bpl.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]))
        utils_bokeh.tweak_fig(fig)

        fig.xaxis[0].ticker = FixedTicker(ticks=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_fig(fig, title)
        bpl.show(fig)
Beispiel #13
0
    def _setup_wind(self, p, x_range, y_range):
        """Setup wind intensity background image and arrow"""
        img_data_source = ColumnDataSource(data={"wind_intensity": []})
        wind_data_source = ColumnDataSource(data={"wind_xy": [], "wind_ys": []})

        a = p.image(
            image="wind_intensity",
            x=p.x_range.start,
            y=p.y_range.start,
            dw=(p.x_range.end - p.x_range.start),
            dh=(p.y_range.end - p.y_range.start),
            global_alpha=0.6,
            palette="Turbo256",
            source=img_data_source,
        )
        a.glyph.color_mapper.low = 0.0
        a.glyph.color_mapper.high = (
            self.boat_velocity_table.velocity_table()[0]
            .wind_velocity_to_boat_velocity.x_space()
            .stop()
            .t
        )
        p.patches(
            xs="wind_xs", ys="wind_ys", source=wind_data_source,
        )

        color_bar = ColorBar(
            color_mapper=a.glyph.color_mapper,
            ticker=FixedTicker(ticks=np.arange(0.0, a.glyph.color_mapper.high, 1.0)),
            location=(0, 0),
        )
        p.add_layout(color_bar, "left")

        self.img_data_source = img_data_source
        self.wind_data_source = wind_data_source
Beispiel #14
0
    def means_chosen_choice(self, mean_chosen_choice, title='Figure 4E',
                            y_range=(0, 25), y_ticks=(0, 5, 10, 15, 20, 25),
                            colors=[grey_low, grey_high], line_width=4,
                            size=SIZE, legends=None):
        fig = bpl.figure(title=title, plot_width=size, plot_height=size,
                         tools=TOOLS, x_range=self.x_range, y_range=y_range)
        utils_bokeh.tweak_fig(fig)
        self.fix_x_ticks(fig)
        fig.yaxis[0].ticker = FixedTicker(ticks=y_ticks)
        fig.line(x=(0, 0), y=y_range, color="black", line_dash='dashed')

        if legends is None:
            legends = len(mean_chosen_choice) * (None,)

        for i, mean_y in enumerate(mean_chosen_choice):
            fig.line(self.x_axis, mean_y[:len(self.x_axis)], color=colors[i], legend=legends[i],
                     line_width=line_width, line_cap='round')

        fig.legend.location = 'top_left'

        # fig.multi_line([self.x_axis, self.x_axis], mean_chosen_choice,
        #                color=colors, line_width=line_width, line_cap='round', legend=legends)
        #
        self.save_fig(fig, title)
        bpl.show(fig)
def make_plot():
    # prepare data stuff - take the keys from the data in order of likelihood
    categories = list(reversed(probly.keys()))
    palette = [cc.rainbow[i * 15] for i in range(17)]
    x = linspace(-20, 110, 500)
    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=categories, plot_width=900, x_range=(-5, 105), toolbar_location=None)

    for i, cat in enumerate(reversed(categories)):
        pdf = gaussian_kde(probly[cat])
        y = ridge(cat, pdf(x))
        source.add(y, cat)
        p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))
    p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "#dddddd"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.12

    return p
Beispiel #16
0
def get_colormapper_add_colorbar(plot, high):
    from bokeh.models import (
        FixedTicker,
        ColorBar,
        NumeralTickFormatter,
        LinearColorMapper,
    )
    from bokeh.palettes import viridis
    PALETTE_N = 10
    palette = viridis(PALETTE_N)
    palette.reverse()

    color_mapper = LinearColorMapper(palette=palette, low=0, high=high)

    ticker = FixedTicker(ticks=[0, high])
    formatter = NumeralTickFormatter(format='0 a')
    color_bar = ColorBar(
        color_mapper=color_mapper,
        ticker=ticker,
        formatter=formatter,
        location=(0, 0),
        label_standoff=2,
        height=PALETTE_N * 5,
        width=10,
        major_tick_line_color=None,
        major_label_text_align='left',
        major_label_text_font=FONT,
    )
    plot.add_layout(color_bar, 'right')
    return color_mapper
Beispiel #17
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))
def figure_filter(filt, title, minimum, maximum, context, nfilters, frate=.01):
    filt_2d = filt.reshape(2 * context + 1, nfilters)
    width, height = (2 * context + 1), nfilters
    ticks = np.linspace(-frate * context, frate * context, XAXIS_NTICKS)

    fig = figure(title=title,
                 x_range=(-frate * context, frate * context),
                 y_range=(0, nfilters),
                 x_axis_label='time (s)',
                 y_axis_label='filter index')
    fig.xaxis.ticker = FixedTicker(ticks=ticks)

    # Plot the image.
    cmap = LinearColorMapper(palette=cc.rainbow, low=minimum, high=maximum)
    fig.image(image=[filt_2d.T],
              x=-frate * context,
              y=0,
              dw=frate * width,
              dh=height,
              color_mapper=cmap)

    # Add a color bar to the figure.
    color_bar = ColorBar(color_mapper=cmap, label_standoff=7, location=(0, 0))
    fig.add_layout(color_bar, 'right')

    return fig
Beispiel #19
0
def generate_teammate_comparison_line_plot(positions_source,
                                           constructor_results, yd_results,
                                           driver_id):
    """
    Plot finish position along with teammate finish position vs time, see
    driverconstructor.generate_teammate_comparison_line_plot
    :param positions_source: Positions source
    :param constructor_results: Constructor results
    :param yd_results: YD results
    :param driver_id: Driver ID
    :return: Teammate comparison line plot layout, source
    """
    kwargs = dict(return_components_and_source=True,
                  default_alpha=0.5,
                  mute_smoothed=True)
    slider, teammate_fp_plot, source = driverconstructor.generate_teammate_comparison_line_plot(
        positions_source, constructor_results, driver_id, **kwargs)

    mark_teammate_team_changes(yd_results, positions_source, driver_id,
                               teammate_fp_plot)

    # x axis override
    x_min = positions_source["x"].min() - 0.001
    x_max = positions_source["x"].max() + 0.001
    teammate_fp_plot.x_range = Range1d(x_min, x_max, bounds=(x_min, x_max))
    teammate_fp_plot.xaxis.ticker = FixedTicker(ticks=positions_source["x"])
    teammate_fp_plot.xaxis.major_label_overrides = {
        row["x"]: row["roundName"]
        for idx, row in positions_source.iterrows()
    }
    teammate_fp_plot.xaxis.major_label_orientation = 0.8 * math.pi / 2
    teammate_fp_plot.xaxis.axis_label = ""

    return column([slider, teammate_fp_plot],
                  sizing_mode="stretch_width"), source
Beispiel #20
0
def generate_positions_plot(yc_constructor_standings, yc_results, yc_fastest_lap_data, year_id, constructor_id):
    """
    Generates a plot of WCC position (both rounds and full season), quali, fastest lap, and finishing position rank vs
    time all on the same graph.
    :return:
    :param yc_constructor_standings: YC constructor standings
    :param yc_results: YC results
    :param yc_fastest_lap_data: YC fastest lap data
    :param year_id: Year
    :param constructor_id: Constructor ID
    :return: Positions plot layout, positions source
    """
    constructor_years = np.array([year_id])
    kwargs = dict(
        return_components_and_source=True,
        smoothing_alpha=0.2,
        smoothing_muted=True,
        show_driver_changes=True,
    )
    positions_plot, positions_source = constructor.generate_positions_plot(constructor_years, yc_constructor_standings,
                                                                           yc_results, yc_fastest_lap_data,
                                                                           constructor_id, **kwargs)

    # Add the axis overrides
    x_min = positions_source["x"].min() - 0.001
    x_max = positions_source["x"].max() + 0.001
    positions_plot.x_range = Range1d(x_min, x_max, bounds=(x_min, x_max))
    positions_plot.xaxis.ticker = FixedTicker(ticks=positions_source["x"])
    positions_source["roundName"] = positions_source["roundName"].fillna("")
    positions_plot.xaxis.major_label_overrides = {row["x"]: row["roundName"] for idx, row in
                                                  positions_source.iterrows()}
    positions_plot.xaxis.major_label_orientation = 0.8 * math.pi / 2
    positions_plot.xaxis.axis_label = ""

    return positions_plot, positions_source
Beispiel #21
0
def three_ticks(fig):
    x_min, x_max = fig.x_range.start, fig.x_range.end
    y_min, y_max = fig.y_range.start, fig.y_range.end
    if x_min == y_min and x_max == y_max:
        if x_min <= -10 < 10 <= x_max:
            x_ticks = [-10, 0, 10]
            y_ticks = [-10, 0, 10]
        elif x_min <= -2 < 2 <= x_max:
            x_ticks = [-2, 0, 2]
            y_ticks = [-2, 0, 2]
        else:
            x_ticks = [-1, 0, 1]
            y_ticks = [-1, 0, 1]

        fig.xaxis[0].ticker = FixedTicker(ticks=x_ticks)
        fig.yaxis[0].ticker = FixedTicker(ticks=y_ticks)
Beispiel #22
0
 def construct_colorbars(self, orientation='horizontal'):
     color_mappers = self._construct_color_mappers()
     if len(color_mappers) > 0:
         from bokeh.models import Plot, ColorBar, FixedTicker
         if orientation == 'horizontal':
             cbs = []
             for color_mapper in color_mappers:
                 ticks = np.linspace(color_mapper.low, color_mapper.high, 5)
                 cbs.append(
                     ColorBar(color_mapper=color_mapper,
                              title=color_mapper.name,
                              ticker=FixedTicker(ticks=ticks),
                              label_standoff=5,
                              background_fill_alpha=0,
                              orientation='horizontal',
                              location=(0, 0)))
             plot = Plot(toolbar_location=None,
                         frame_height=0,
                         sizing_mode='stretch_width',
                         outline_line_width=0)
             [plot.add_layout(cb, 'below') for cb in cbs]
             return plot
         else:
             raise ValueError('orientation can only be horizontal')
     else:
         return None
Beispiel #23
0
def get_trains_week(stat_code):
    sbn.set_style("white")
    stat_vals = dis_trains[dis_trains.code == stat_code]
    all_trains = stat_vals.times.values
    xx = all_trains
    days = np.array(xx[0]) / 1440
    tot_mins = np.array(xx[0]) % 1440
    hour = tot_mins / 60
    mins = tot_mins % 60
    train_time = zip(days, hour, mins)
    hist, edges = np.histogram(xx[0], bins=range(0, 10081, 120))
    fig = figure(x_range=(0, 10080), y_range=(0, max(hist + 1)))
    d = np.sin(3 * gradient)
    fig.image(image=[d], x=0, y=0, dw=10080, dh=max(hist) + 1)
    fig.quad(top=hist,
             bottom=0,
             left=edges[:-1],
             right=edges[1:],
             fill_color="#036564",
             line_color="#033649")
    fig.xaxis[0].ticker = FixedTicker(ticks=[])
    fig.xaxis.major_label_orientation = "vertical"
    output_file("test_bg_image.html", title="Background image")
    show(fig)
    return hist, edges
Beispiel #24
0
 def construct_colorbars(self, orientation='horizontal'):
     if self._legend is None:
         try:
             from .vtkjs_serializer import construct_palettes
             self._legend = construct_palettes(self.object)
         except Exception:
             self._legend = {}
     if self._legend:
         from bokeh.models import Plot, LinearColorMapper, ColorBar, FixedTicker
         if orientation == 'horizontal':
             cbs = []
             for k, v in self._legend.items():
                 ticks = np.linspace(v['low'], v['high'], 5)
                 cbs.append(
                     ColorBar(color_mapper=LinearColorMapper(
                         low=v['low'], high=v['high'],
                         palette=v['palette']),
                              title=k,
                              ticker=FixedTicker(ticks=ticks),
                              label_standoff=5,
                              background_fill_alpha=0,
                              orientation='horizontal',
                              location=(0, 0)))
             plot = Plot(toolbar_location=None,
                         frame_height=0,
                         sizing_mode='stretch_width',
                         outline_line_width=0)
             [plot.add_layout(cb, 'below') for cb in cbs]
             return plot
         else:
             raise ValueError('orientation can only be horizontal')
     else:
         return None
Beispiel #25
0
def create_heatmap(df):

    products=['Debit Card',
              'Personal Credit Card',
              'Business Credit Card',
              'Home Mortgage Loan',
              'Auto Loan',
              'Brokerage Account',
              'Roth IRA',
              '401k',
              'Home Insurance',
              'Automobile Insurance',
              'Medical Insurance',
              'Life Insurance',
              'Cell Phone',
              'Landline'
              ]

    def rename_columns(df):
        df = df.copy()
        df.columns = [products[i] for i in df.columns]
        return df

    # create an artificial dataset with 3 clusters
    X, Y = make_classification(n_samples=100, n_classes=4, n_features=12, n_redundant=0, n_informative=12,
                               scale=1000, n_clusters_per_class=1)
    df2 = pd.DataFrame(X)
    # ensure all values are positive (this is needed for our customer 360 use-case)
    df2 = df2.abs()
    # rename X columns
    df2 = rename_columns(df2)
    # and add the Y
    df2['y'] = Y
    #df
    # split df into cluster groups
    grouped = df2.groupby(['y'], sort=True)

    # compute sums for every column in every group
    sums = grouped.sum()

    score = []
    for x in sums.apply(tuple):
        score.extend(x)

    data=dict(
        persona=list(sums.index) * len(sums.columns),
        product=[item for item in list(sums.columns) for i in range(len(sums.index))],
        score=score
    )

    hm = HeatMap(data, x='product', y='persona', values='score', title='Customer Profiles', xlabel='Product', ylabel='Persona', legend=False, stat=None,  tools=["save"], height=400, width=900, toolbar_location=None)
    hm.yaxis.ticker=FixedTicker(ticks=[0,1,2,3])
    hm_source = ColumnDataSource(data=sums)

    hm_data_table = DataTable(
        source=hm_source,
        columns=[TableColumn(field=c, title=c) for c in sums.columns], width=900, height=150)

    return hm
Beispiel #26
0
def ridge_plots(model_df):
    models = list(model_df.keys())
    models.reverse()
    for i, model in enumerate(models):
        if 'name' in model:
            models.pop(i)

    palette = [cc.rainbow[i * 15] for i in range(len(models))]

    x = np.linspace(-20, 110, 500)

    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=models,
               plot_width=900,
               x_range=(0, 5),
               toolbar_location=None)

    for i, model in enumerate(models):
        if 'name' in model:
            continue
        pdf = gaussian_kde(model_df[model].dropna())
        y = ridge(model, pdf(x))
        source.add(y, model)
        p.patch('x',
                model,
                color=palette[i],
                alpha=0.6,
                line_color="black",
                source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.xaxis.ticker = FixedTicker(
        ticks=list(range(int(model_df.min().min()), 5, 1)))
    # p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "#dddddd"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 2

    base = Span(location=1,
                dimension='height',
                line_color='black',
                line_dash='dashed',
                line_width=3)
    p.add_layout(base)

    st.bokeh_chart(p)
    return
Beispiel #27
0
 def _colorbar_opts(self):
     if self.colormap_delta.value <= 0:
         return {}
     ticks = self._color_levels()
     if len(ticks) > 8:
         ticks = ticks[::len(ticks) // 8] + [ticks[-1]]
     # Add 0 to the ticks
     if self.colormap_min.value * self.colormap_max.value < 0:  # Either side of 0
         ticks = numpy.insert(ticks, numpy.searchsorted(ticks, 0), 0)
     return {"ticker": FixedTicker(ticks=ticks)}
Beispiel #28
0
def createEnergySaveGraph(width, height):
    # Define base figure for energy savings
    fig = figure(width=width, height=height, x_range=(6,18), y_range=(0, 100), toolbar_location=None, tools=[])
    fig.xaxis[0].ticker=FixedTicker(ticks=range(25))#[0, 3, 6, 9, 12, 15, 18, 21, 24])
    fig.xgrid.grid_line_color = None

    # Set axis labels
    fig.xaxis.axis_label = 'Hour'
    fig.yaxis.axis_label = 'Energy save percentage'

    return fig
Beispiel #29
0
    def firing_choice(self, tunnig_cjb, title='Figure 4H', size=SIZE):
        """Figure 4H"""
        fig = bpl.figure(title=title, plot_width=size, plot_height=size,
                         tools=TOOLS, x_range=[0.75, 2.25], y_range=[0, 18])

        utils_bokeh.tweak_fig(fig)
        fig.xaxis[0].ticker = FixedTicker(ticks=[1, 2])
        fig.yaxis[0].ticker = FixedTicker(ticks=[0, 5, 10, 15])
        fig.xaxis.formatter = FuncTickFormatter(code="""
            var labels = {};
            return labels[tick];
        """.format({1: 'A chosen', 2: 'B chosen'}))

        y_A = [r_cjb for x_A, x_B, r_cjb, choice in tunnig_cjb if choice == 'A']
        y_B = [r_cjb for x_A, x_B, r_cjb, choice in tunnig_cjb if choice == 'B']
        fig.diamond(x=len(y_A)*[1], y=y_A, size=15, fill_color=None, line_color=A_color, line_alpha=0.5)
        fig.circle (x=len(y_B)*[2], y=y_B, size=10, fill_color=None, line_color=B_color, line_alpha=0.501)

        self.save_fig(fig, title)
        bpl.show(fig)
Beispiel #30
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)