def make_plot(source, title_text, league):

    hover = HoverTool(tooltips=[(
        "Team",
        "@team"), ("Expected Runs",
                   "@expected_runs"), ("Actual Runs",
                                       "@actual_runs"), ("League", "@league")])

    p = figure(plot_width=400,
               plot_height=400,
               tools=[hover],
               title=title_text)
    p.x_range = Range1d(3, 7)
    p.y_range = Range1d(3, 7)

    p.xaxis.axis_label = "Expected Runs Per Game"
    p.yaxis.axis_label = "Actual Runs Per Game"

    p.circle(x="expected_runs",
             y="actual_runs",
             size=10,
             line_color="black",
             fill_color="firebrick",
             fill_alpha=0.5,
             source=source)
    p.line(x=[3, 9], y=[3, 9], line_width=4, line_color="navy", alpha=0.7)
    p.line(x=[3, 9], y=[3, 9], line_width=175, line_color="navy", alpha=0.05)

    print(league)
    if 1 == 7:
        print("hello world")
        p.add_layout(
            Label(x=6.638,
                  y=5.42,
                  x_offset=-17,
                  y_offset=10,
                  text="BOS",
                  text_color="black"))
        p.add_layout(
            Label(x=5.121,
                  y=3.77,
                  x_offset=-15,
                  y_offset=-30,
                  text="PHI",
                  text_color="black"))
        p.add_layout(
            Label(x=4.705,
                  y=4.030,
                  x_offset=-17,
                  y_offset=-30,
                  text="OAK",
                  text_color="black"))
        p.add_layout(
            Label(x=5.917,
                  y=4.14,
                  x_offset=-12,
                  y_offset=-30,
                  text="MIL",
                  text_color="black"))
    return p  # show the results
Exemple #2
0
    def error_graph(self):
        """plotting error graph in case of misspelling to avoid errors breaking
        the program"""

        p = figure(title='Uh oh!',
                   x_range=(0, 1),
                   y_range=(0, 2),
                   tools="wheel_zoom,reset",
                   match_aspect=True,
                   name='plot')

        text1 = 'Uh oh! It looks like you misspelled a word. If you are searching for'
        text2 = 'a player make sure that their full name is spelled correctly. If you'
        text3 = 'are looking for a team make sure that their 3 letter, NBA specific'
        text4 = 'abbreviation is correct.'

        mytext1 = Label(x=0.1, y=1.4, text=text1)
        mytext2 = Label(x=0.1, y=1.2, text=text2)
        mytext3 = Label(x=0.1, y=1, text=text3)
        mytext4 = Label(x=0.35, y=.8, text=text4)

        p.add_layout(mytext1)
        p.add_layout(mytext2)
        p.add_layout(mytext3)
        p.add_layout(mytext4)

        p.grid.visible = False
        p.axis.visible = False
        p.toolbar.logo = None
        p.toolbar_location = None
        return p
Exemple #3
0
def f11(city, title):
    df = city_bus_level_re[[
        '城市对', '发车城市', '到达城市', '最快到达时间', '总得分', '经度_x', '纬度_x', '经度_y', '纬度_y'
    ]]
    x = df[df['城市对'].str.contains(city) & (df['最快到达时间'] <= 120)]
    x['总得分'] = x['总得分'] * 10
    x['color'] = '待分类'
    x['color'][x['最快到达时间'] <= 60] = '#00A896'
    x['color'][(x['最快到达时间'] > 60) & (x['最快到达时间'] <= 120)] = '#457B9D'
    colors = x[x['发车城市'] != city]['color'].tolist() + x[
        x['到达城市'] != city]['color'].tolist()
    citys = x[x['发车城市'] != city]['发车城市'].tolist() + x[
        x['到达城市'] != city]['到达城市'].tolist()
    lng = x[x['发车城市'] != city]['经度_x'].tolist() + x[
        x['到达城市'] != city]['经度_y'].tolist()
    lat = x[x['发车城市'] != city]['纬度_x'].tolist() + x[
        x['到达城市'] != city]['纬度_y'].tolist()
    #time = x[x['发车城市'] != city]['最快到达时间'].tolist() + x[x['到达城市'] != city]['最快到达时间'].tolist()
    size = x[x['发车城市'] != city]['总得分'].tolist() + x[
        x['到达城市'] != city]['总得分'].tolist()
    p = figure(
        title=title,
        plot_width=800,
        plot_height=800,
        tools=['box_select,reset,xwheel_zoom,ywheel_zoom,pan,crosshair,save'])
    p.circle(x=lng,
             y=lat,
             size=size,
             color=colors,
             fill_alpha=0.8,
             line_width=0.8,
             line_color='#1C191D',
             legend='绿色(一小时圈)蓝色(两小时圈)')
    p.circle_cross(x=x[x['发车城市'] == city]['经度_x'].tolist(),
                   y=x[x['发车城市'] == city]['纬度_x'].tolist(),
                   size=26,
                   fill_alpha=0.8,
                   line_width=0.8,
                   line_color='#1C191D',
                   color='#F0374D',
                   legend='散点大小(%s与该市公交化得分)' % city)
    for i, j, k, m in zip(lng, lat, citys, size):
        label = Label(x=i - 0.09, y=j + 0.165, text=k, text_font_size='9pt')
        label2 = Label(x=i - 0.09,
                       y=j - 0.044,
                       text=str(m / 10)[:4],
                       text_font_size='9pt')
        p.add_layout(label)
        p.add_layout(label2)
    label3 = Label(x=x[x['发车城市'] == city]['经度_x'].tolist()[0] - 0.09,
                   y=x[x['发车城市'] == city]['纬度_x'].tolist()[0] + 0.165,
                   text=city,
                   text_font_size='9pt')
    p.add_layout(label3)
    p.legend.location = "bottom_right"
    p.legend.background_fill_alpha = 0.05
    p.legend.border_line_color = None
    p.background_fill_alpha = 0.05
    df_y = pd.DataFrame({'LNG': lng, 'lat': lat, 'city': citys})
    return show(p), df_y, x
Exemple #4
0
def infographic(items, **kwargs):
    """Create and infographic 'plot'.

    :param items: 3-tuples of (label, value, unit, icon); the label should be
        a one or two word description, the value the headline number, and the
        icon the name of a fontawesome icon. If `value` is  numeric, it
        will be normalised by use of an SI suffix for display after which
        `unit` will be appended. If `value` is a string it will be used as is.
    :param kwargs: kwargs for bokeh gridplot.

    ..note:: If `bootstrap_fontawesome` has not already been called, the
        function will load the required fonts, however they will not display
        the first time an Jupyter labs cell is run. If using the
        `InfoGraphItems` helper class, this wrinkle will be taken care of
        provided the helper is initiated in a previous cell.

    """
    plots = list()
    seen = set()
    for label, value, icon, unit in items:
        if label in seen:
            continue
        if not isinstance(value, str):
            value = si_format(value) + unit
        seen.add(label)
        width, height = 175, 100
        aspect = height / width
        p = figure(
            output_backend='webgl',
            plot_width=width, plot_height=height,
            title=None, toolbar_location=None)
        p.axis.visible = False
        p.grid.visible = False
        p.outline_line_color = None
        p.rect([0.5], [0.5], [1.0], [1.0], fill_color="#2171b5")
        p.x_range = Range1d(start=0.1, end=0.9, bounds=(0.1, 0.9))
        p.y_range = Range1d(start=0.1, end=0.9, bounds=(0.1, 0.9))
        p.add_layout(
            Label(
                x=0.15, y=0.45, text=value, text_color="#DEEBF7",
                text_font_size="24px"))
        p.add_layout(
            Label(
                x=0.15, y=0.2, text=label, text_color="#C6DBEF",
                text_font_size="16px"))
        image = fa_icons.rgba(icon, 75, color='#6BAED6')
        p.image_rgba(image=[image], x=0.6, y=0.4, dw=0.25, dh=0.25/aspect)
        plots.append(p)
    defaults = {'toolbar_location': None, "ncols": len(items)}
    defaults.update(kwargs)
    return gridplot(plots, **defaults)
def test_Label():
    label = Label()
    assert label.plot is None
    assert label.level == 'annotation'
    assert label.x is None
    assert label.y is None
    assert label.x_units == 'data'
    assert label.y_units == 'data'
    assert label.text == 'text'
    assert label.angle == 0
    assert label.x_offset == 0
    assert label.y_offset == 0
    assert label.render_mode == 'canvas'
    assert label.x_range_name == 'default'
    assert label.y_range_name == 'default'
    assert isinstance(label.source, ColumnDataSource)
    assert label.source.data == {}
    yield check_text, label
    yield check_background, label, None, 1.0
    yield check_border, label, None, 1.0, 1.0
    yield (check_props, label, [
        "plot", "level", "x", "y", "x_units", "y_units", "text", "angle",
        "x_offset", "y_offset", "render_mode", "x_range_name", "y_range_name",
        "source"
    ], TEXT, ANGLE, BORDER, BACKGROUND)
Exemple #6
0
    def __init__(self,
                 sim_data,
                 image=PendelWagenSystem(),
                 speed_factor=1,
                 fig=None,
                 state=1,
                 x_range=None,
                 wait=0.01):

        self.wait = wait

        self.set_sim_data(sim_data)
        self.set_image(image)

        self.figure = fig if fig else self.create_fig(state)

        self.k = int(self.x.shape[0] / (np.max(self.t) / self.wait))

        self.x = self.x[0:-1:self.k]
        self.t = self.t[0:-1:self.k]

        self.speed_factor = speed_factor

        self.time = Label(x=25,
                          y=self.figure.plot_height - 50,
                          x_units='screen',
                          y_units='screen')
        self.figure.add_layout(self.time)
        self.figure.renderers += self.image.glyphs
Exemple #7
0
def test_Label():
    label = Label()
    assert label.plot is None
    assert label.level == 'annotation'
    assert label.x is None
    assert label.y is None
    assert label.x_units == 'data'
    assert label.y_units == 'data'
    assert label.text == 'text'
    assert label.angle == 0
    assert label.x_offset == 0
    assert label.y_offset == 0
    assert label.render_mode == 'canvas'
    assert label.x_range_name == 'default'
    assert label.y_range_name == 'default'
    assert isinstance(label.source, ColumnDataSource)
    assert label.source.data == {}
    yield check_text, label
    yield check_fill, label, "background_", None, 1.0
    yield check_line, label, "border_", None, 1.0, 1.0
    yield (check_props, label, [
        "plot", "level", "x", "y", "x_units", "y_units", "text", "angle",
        "x_offset", "y_offset", "render_mode", "x_range_name", "y_range_name",
        "source"
    ], TEXT, ANGLE, prefix('border_', LINE), prefix('background_', FILL))
Exemple #8
0
def add_ascending_node_direction(plot):
    plot.add_layout(
        Arrow(
            end=VeeHead(
                size=10,
                fill_color=colors["ascending-node"],
                line_color=colors["ascending-node"],
            ),
            line_width=3,
            x_start=0,
            y_start=0,
            x_end=constants.PLOTS_RANGE,
            y_end=0,
            line_color=colors["ascending-node"],
        )
    )
    plot.add_layout(
        Label(
            text="Ascending Node",
            x=0.5 * constants.PLOTS_RANGE,
            y=-0.1 * constants.PLOTS_RANGE,
            text_font_size="8pt",
            text_color=colors["ascending-node"],
        )
    )
Exemple #9
0
def calibrate(current, reference, figure):
    r = scipy.stats.linregress(x=current, y=reference, alternative='two-sided')
    a, b = current[0], current[-1]
    ca, cb = (
        a * r.slope + r.intercept,
        b * r.slope + r.intercept,
    )
    figure.line(
        x=[a, b],
        y=[ca, cb],
        color="red",
    )

    rps = Label(x=min(current),
                y=(max(reference) - min(reference)) * .8 + min(reference),
                x_units="data",
                y_units="data",
                text=f"slope={r.slope}\nintercept={r.intercept}\n"
                f"rvalue={r.rvalue}\npvalue={r.pvalue}\n"
                f"stderr={r.stderr}\nintercept_stderr={r.intercept_stderr}",
                render_mode='css',
                border_line_color='black',
                border_line_alpha=1.0,
                background_fill_color='white',
                background_fill_alpha=1.0)
    figure.add_layout(rps)
    return dict(slope=r.slope, intercept=r.intercept)
Exemple #10
0
    def __init__(self,
                 dataf,
                 labels,
                 x,
                 y,
                 size=5,
                 alpha=0.5,
                 width=400,
                 height=400,
                 color=None):
        self.uuid = str(uuid.uuid4())[:10]
        self.x = x
        self.y = y
        self.plot = figure(width=width, height=height, title=f"{x} vs. {y}")
        self.color_column = labels if isinstance(labels, str) else color
        self._colors = ["red", "blue", "green", "purple", "cyan"]

        if isinstance(labels, str):
            self.labels = list(dataf[labels].unique())
            d = {k: col for k, col in zip(self.labels, self._colors)}
            dataf = dataf.assign(color=[d[lab] for lab in dataf[labels]])
            self.source = ColumnDataSource(data=dataf)
        else:
            if not self.color_column:
                dataf = dataf.assign(
                    color=["gray" for _ in range(dataf.shape[0])])
            else:
                color_labels = list(dataf[self.color_column].unique())
                d = {k: col for k, col in zip(color_labels, self._colors)}
                dataf = dataf.assign(
                    color=[d[lab] for lab in dataf[self.color_column]])
            self.source = ColumnDataSource(data=dataf)
            self.labels = labels

        if len(self.labels) > 5:
            raise ValueError("We currently only allow for 5 classes max.")
        self.plot.circle(x=x,
                         y=y,
                         color="color",
                         source=self.source,
                         size=size,
                         alpha=alpha)

        # Create all the tools for drawing
        self.poly_patches = {}
        self.poly_draw = {}
        for k, col in zip(self.labels, self._colors):
            self.poly_patches[k] = self.plot.patches([], [],
                                                     fill_color=col,
                                                     fill_alpha=0.4,
                                                     line_alpha=0.0)
            icon_path = resource_filename("hulearn", f"images/{col}.png")
            self.poly_draw[k] = PolyDrawTool(renderers=[self.poly_patches[k]],
                                             custom_icon=icon_path)
        c = self.plot.circle([], [], size=5, color="black")
        edit_tool = PolyEditTool(renderers=list(self.poly_patches.values()),
                                 vertex_renderer=c)
        self.plot.add_tools(*self.poly_draw.values(), edit_tool)
        self.plot.add_layout(Label(x=70, y=70, text="here your text"))
def plot_edge_performance(model):

    all_cuts = np.arange(0.001, 1., 0.02)
    results = {'eff': [], 'pur': [], 'score cut': all_cuts}
    model.to(device)
    test_data = model.testset[0].to(device)

    with torch.no_grad():
        test_results = model.shared_evaluation(test_data, 0, log=False)

        auc = roc_auc_score(test_results["truth"].cpu(),
                            test_results["score"].cpu())

        for cut in all_cuts:
            preds = test_results["score"] > cut
            edge_positive = preds.sum().float()
            edge_true = test_results["truth"].sum().float()
            edge_true_positive = ((test_results["truth"].bool()
                                   & preds).sum().float())

            results["eff"].append(
                (edge_true_positive / max(1, edge_true)).cpu().numpy())
            results["pur"].append(
                (edge_true_positive / max(1, edge_positive)).cpu().numpy())
    results = pd.DataFrame(results)

    source = ColumnDataSource(results)
    cmap = viridis(3)
    titles = ['Efficiency', 'Purity']
    figures = []
    x = 'score cut'
    for idx, y in enumerate(['eff', 'pur']):
        figures.append(
            figure(title=titles[idx], x_axis_label=x, y_axis_label=y))
        figures[-1].circle(y=y,
                           x=x,
                           source=source,
                           color=cmap[0],
                           legend_label=y)
        figures[-1].line(x=x,
                         y=y,
                         source=source,
                         color=cmap[0],
                         legend_label=y)
        y_val = results[y][(results[x] - 0.5).abs().idxmin()].item()
        label = Label(x=0.1,
                      y=y_val,
                      x_offset=10,
                      y_offset=-10,
                      text="@ score cut = 0.5, \n" + y + " = " +
                      str(round(y_val, 3)) + "\n AUC: " + str(auc),
                      border_line_color='black',
                      border_line_alpha=1.0,
                      background_fill_color='white',
                      background_fill_alpha=0.8)
        figures[-1].add_layout(label)

    show(row(figures))
Exemple #12
0
def add_equatorial_plane(plot):
    plot.add_layout(
        Label(
            text="Equatorial Plane",
            x=-0.7 * constants.PLOTS_RANGE,
            y=0.7 * constants.PLOTS_RANGE,
            text_align="center",
            text_color=colors["equator"],
            text_font_size="9pt",
            angle=pi / 4,
        )
    )
def plot_neighbor_performance(model):

    all_radius = np.arange(0.001, 0.15, 0.005)
    results = {'eff': [], 'pur': [], 'loss': [], 'radius': all_radius}
    model.to(device)
    test_data = model.testset[0].to(device)

    with torch.no_grad():
        for r in all_radius:
            test_results = model.shared_evaluation(test_data,
                                                   0,
                                                   r,
                                                   1000,
                                                   log=False)
            for key in results:
                if key not in test_results: continue
                results[key].append(test_results[key].cpu().numpy())
    results = pd.DataFrame(results)

    source = ColumnDataSource(results)
    cmap = viridis(3)
    titles = ['Efficiency', 'Purity', 'Loss']
    figures = []
    x = 'radius'
    for idx, y in enumerate(['eff', 'pur', 'loss']):
        figures.append(
            figure(title=titles[idx], x_axis_label=x, y_axis_label=y))
        figures[-1].circle(y=y,
                           x=x,
                           source=source,
                           color=cmap[0],
                           legend_label=y)
        figures[-1].line(x=x,
                         y=y,
                         source=source,
                         color=cmap[0],
                         legend_label=y)
        y_val = results[y][(results[x] -
                            model.hparams["r_test"]).abs().idxmin()].item()
        label = Label(x=model.hparams["r_test"],
                      y=y_val,
                      x_offset=10,
                      y_offset=-10,
                      text=f"@ radius = {model.hparams['r_test']}, \n" + y +
                      " = " + str(round(y_val, 3)),
                      border_line_color='black',
                      border_line_alpha=1.0,
                      background_fill_color='white',
                      background_fill_alpha=0.8)
        figures[-1].add_layout(label)

    show(row(figures))
Exemple #14
0
    def createMeasureJTool(self):
        source = ColumnDataSource(data=dict(x=[], y=[]))
        label = Label(x=0,
                      y=0,
                      text="",
                      text_color="#000000",
                      render_mode="css")
        self.plot.add_layout(label)

        measureJTool = MeasureJTool(label=label,
                                    frequency=getFrequency(self.udic),
                                    id="measureJTool")
        self.plot.add_tools(measureJTool)
Exemple #15
0
    def __init__(self, sim_data, image=PendelWagenSystem(), speed_factor=1, fig=None):

        self.sim_data = sim_data
        self.x, self.t = sim_data

        self.figure = fig if fig else self.create_fig()
        self.image = image

        k = int(self.x.shape[0] / (np.max(self.t)/0.01))

        self.x = self.x[0:-1:k]
        self.t = self.t[0:-1:k]

        self.speed_factor = speed_factor

        self.time = Label(x=25, y=self.figure.plot_height - 50, x_units='screen', y_units='screen')
        self.figure.add_layout(self.time)
        self.figure.renderers += self.image.glyphs
Exemple #16
0
def add_equator_line(plot):
    plot.add_layout(
        Span(
            location=0,
            dimension="width",
            line_color=colors["equator"],
            line_dash="dashed",
            line_width=1,
        )
    )
    plot.add_layout(
        Label(
            text="Equator",
            x=-0.9 * constants.PLOTS_RANGE,
            y=0.03 * constants.PLOTS_RANGE,
            text_font_size="8pt",
            text_color=colors["equator"],
        )
    )
Exemple #17
0
def plot_feature_cumsum(X, y, feature, cutoff, x_range=(-1, 4)):
    feature_data = get_feature_cumsum(X, y, feature)

    p = figure(x_range=x_range, )

    p.line(
        feature_data[feature],
        feature_data["0"],
        legend_label="0",
        line_color="navy",
    )

    p.line(
        feature_data[feature],
        feature_data["1"],
        legend_label="1",
        line_color="crimson",
    )

    span = Span(
        location=cutoff,
        dimension="height",
        line_color="gray",
        line_dash="dotted",
    )

    label = Label(
        text="limiar da árvore\nde decisão",
        text_align='right',
        x=cutoff - 0.1,
        y=0.9,
        x_units="data",
    )

    p.add_layout(span)
    p.add_layout(label)

    p.xaxis.axis_label = feature
    p.yaxis.axis_label = "soma cumulativa"

    p.legend.location = "top_left"

    show(p)
Exemple #18
0
def f9(df, col, hovers, titles, ax, label):  #
    df.columns = ['city', col]
    citys = df['city'].tolist()[::-1]
    source2 = ColumnDataSource(df)
    hover = HoverTool(tooltips=[('城市', '@city'), (hovers, '@%s' % col)])
    p2 = figure(
        title=titles,
        plot_width=400,
        plot_height=550,
        y_range=citys,
        tools=[hover, 'box_select,reset,xwheel_zoom,pan,crosshair,save'])
    p2.hbar(y='city',
            source=source2,
            color='#02C39A',
            height=0.2,
            left=1,
            right=col,
            alpha=0.6)
    p2.xgrid.grid_line_color = None
    p2.ygrid.grid_line_color = None
    p2.xaxis.minor_tick_line_color = None
    p2.yaxis.axis_line_color = None
    p2.outline_line_color = None
    p2.legend.location = "bottom_right"
    p2.legend.orientation = "horizontal"
    p2.xaxis.axis_label = label
    n = 19.2
    for k in df[col].tolist():
        if n > 0:
            label = Label(x=ax,
                          y=n - 0.05,
                          text=str(k)[:4],
                          text_font_size='9pt',
                          text_color='#898B8E')
            n = n - 1
            p2.add_layout(label)
    output_file('%s.html' % titles)
    return show(p2)
def test_Label():
    label = Label()
    assert label.plot is None
    assert label.level == 'annotation'
    assert label.x is None
    assert label.y is None
    assert label.x_units == 'data'
    assert label.y_units == 'data'
    assert label.text is None
    assert label.angle == 0
    assert label.angle_units == 'rad'
    assert label.x_offset == 0
    assert label.y_offset == 0
    assert label.render_mode == 'canvas'
    assert label.x_range_name == 'default'
    assert label.y_range_name == 'default'
    check_text_properties(label)
    check_fill_properties(label, "background_", None, 1.0)
    check_line_properties(label, "border_", None, 1.0, 1.0)
    check_properties_existence(label, [
        "plot",
        "level",
        "visible",
        "x",
        "y",
        "x_units",
        "y_units",
        "text",
        "angle",
        "angle_units",
        "x_offset",
        "y_offset",
        "render_mode",
        "x_range_name",
        "y_range_name"],
        TEXT,
        prefix('border_', LINE),
        prefix('background_', FILL))
Exemple #20
0
def add_north_direction(plot):
    plot.add_layout(
        Arrow(
            end=VeeHead(
                size=10, fill_color=colors["north"], line_color=colors["north"]
            ),
            line_width=3,
            x_start=0,
            y_start=0,
            x_end=0,
            y_end=constants.PLOTS_RANGE,
            line_color=colors["north"],
        )
    )
    plot.add_layout(
        Label(
            text="North",
            x=0.05 * constants.PLOTS_RANGE,
            y=0.8 * constants.PLOTS_RANGE,
            text_font_size="8pt",
            text_color=colors["north"],
        )
    )
Exemple #21
0
def add_vernal_direction(plot):
    plot.add_layout(
        Arrow(
            end=VeeHead(
                size=10, fill_color=colors["vernal"], line_color=colors["vernal"]
            ),
            line_width=3,
            x_start=0,
            y_start=0,
            x_end=constants.PLOTS_RANGE,
            y_end=0,
            line_color=colors["vernal"],
        )
    )
    plot.add_layout(
        Label(
            text="Vernal Equinox",
            x=0.5 * constants.PLOTS_RANGE,
            y=-0.1 * constants.PLOTS_RANGE,
            text_font_size="8pt",
            text_color=colors["vernal"],
        )
    )
Exemple #22
0
 def _label_plot(label, h, w, angle=angle, **kwargs):
     # a figure that simply holds a label
     p = figure(output_backend='webgl',
                plot_height=h,
                plot_width=w,
                title=None,
                toolbar_location=None)
     p.axis.visible = False
     p.grid.visible = False
     p.outline_line_color = None
     p.toolbar.active_drag = None
     p.x_range = Range1d(start=0.0, end=1.0)
     p.y_range = Range1d(start=0.0, end=1.0)
     if label is None:
         label = ""
     p.add_layout(
         Label(x=0.5,
               y=0.5,
               text=label,
               text_align='center',
               text_baseline='middle',
               angle=angle,
               **kwargs))
     return p
Exemple #23
0
x = Span(location=x_mean,
         dimension='height',
         line_color='green',
         line_alpha=0.7)
y = Span(location=y_mean,
         dimension='width',
         line_color='green',
         line_alpha=0.7)
p.add_layout(x)
p.add_layout(y)

bg1 = BoxAnnotation(bottom=y_mean,
                    right=x_mean,
                    fill_alpha=0.1,
                    fill_color='olive')
label1 = Label(x=0.1, y=0.8, text='少量少打折', text_font_size='10pt')
p.add_layout(bg1)
p.add_layout(label1)

bg2 = BoxAnnotation(bottom=y_mean,
                    left=x_mean,
                    fill_alpha=0.1,
                    fill_color='firebrick')
label2 = Label(x=0.7, y=0.8, text='大量少打折', text_font_size='10pt')
p.add_layout(bg2)
p.add_layout(label2)

bg3 = BoxAnnotation(top=y_mean,
                    right=x_mean,
                    fill_alpha=0.1,
                    fill_color='firebrick')
Exemple #24
0
         line_dash=[6, 4])
y = Span(location=y_mean,
         dimension='width',
         line_color='green',
         line_alpha=0.7,
         line_width=1.5,
         line_dash=[6, 4])
p4.add_layout(x)
p4.add_layout(y)
# 绘制辅助线

bg1 = BoxAnnotation(bottom=y_mean,
                    right=x_mean,
                    fill_alpha=0.1,
                    fill_color='olive')
label1 = Label(x=0.1, y=0.45, text="少量大打折", text_font_size="10pt")
p4.add_layout(bg1)
p4.add_layout(label1)
# 绘制第一象限

bg2 = BoxAnnotation(bottom=y_mean,
                    left=x_mean,
                    fill_alpha=0.1,
                    fill_color='firebrick')
label2 = Label(x=0.5, y=0.45, text="大量大打折", text_font_size="10pt")
p4.add_layout(bg2)
p4.add_layout(label2)
# 绘制第二象限

bg3 = BoxAnnotation(top=y_mean,
                    right=x_mean,
def test_Label_accepts_datetime_xy():
    obj = Label(x=datetime(2018, 8, 7, 0, 0), y=datetime(2018, 8, 7, 0, 0))
    assert obj.x == 1533600000000.0
    assert obj.y == 1533600000000.0
def plotOutlierHistogram(dataframe, maxOutliers, func,
                         statisticalOutlierThreshold, userLatencyThreshold,
                         averageDuration, maxDuration):

    global pixelsForTitle
    global pixelsPerHeightUnit
    global plotWidth
    global timeUnitString

    cds = ColumnDataSource(dataframe)

    figureTitle = "Occurrences of " + func + " that took longer than " \
                  + statisticalOutlierThreshold + "."

    hover = HoverTool(
        tooltips=[("interval start",
                   "@lowerbound{0,0}"), ("interval end", "@upperbound{0,0}")])

    TOOLS = [hover, "tap, reset"]

    p = figure(title = figureTitle, plot_width = plotWidth,
               plot_height = min(500, (max(5, (maxOutliers + 1)) \
                                       * pixelsPerHeightUnit + \
                                       pixelsForTitle)),
               x_axis_label = "Execution timeline (" + timeUnitString + ")",
               y_axis_label = "Number of outliers",
               tools = TOOLS, toolbar_location="above")

    y_ticker_max = p.plot_height // pixelsPerHeightUnit
    y_ticker_step = max(1, (maxOutliers + 1) // y_ticker_max)
    y_upper_bound = (maxOutliers // y_ticker_step + 2) * y_ticker_step

    p.yaxis.ticker = FixedTicker(
        ticks=list(range(0, y_upper_bound, y_ticker_step)))
    p.ygrid.ticker = FixedTicker(
        ticks=list(range(0, y_upper_bound, y_ticker_step)))
    p.xaxis.formatter = NumeralTickFormatter(format="0,")

    p.y_range = Range1d(0, y_upper_bound)

    p.quad(left='lowerbound',
           right='upperbound',
           bottom='bottom',
           top='height',
           color=funcToColor[func],
           source=cds,
           nonselection_fill_color=funcToColor[func],
           nonselection_fill_alpha=1.0,
           line_color="lightgrey",
           selection_fill_color=funcToColor[func],
           selection_line_color="grey")

    p.x(x='markerX',
        y='markerY',
        size='markersize',
        color='navy',
        line_width=1,
        source=cds)

    # Add an annotation to the chart
    #
    y_max = dataframe['height'].max()
    text = "Average duration: " + '{0:,.0f}'.format(averageDuration) + " " + \
           timeUnitString + \
           ". Maximum duration: " + '{0:,.0f}'.format(maxDuration) + " " + \
           timeUnitString + ". "
    if (userLatencyThreshold is not None):
        text = text + \
               "An \'x\' shows intervals with operations exceeding " + \
               "a user-defined threshold of " + \
               userLatencyThreshold + "."
    mytext = Label(x=0,
                   y=y_upper_bound - y_ticker_step,
                   text=text,
                   text_color="grey",
                   text_font="helvetica",
                   text_font_size="10pt",
                   text_font_style="italic")
    p.add_layout(mytext)

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

    return p
Exemple #27
0
from bokeh.io import output_file, show
from bokeh.models.annotations import Label, LabelSet
from bokeh.models import ColumnDataSource

#prepare the output
output_file("students.html")

#crate columndatasource
source=ColumnDataSource(dict(average_grades=["B+","A","D-"],
                             exam_grades=["A+","C","D"],
                             student_names=["Stephan","Helder","Riazudidn"]))

#create the figure
f = figure(x_range=["F","D-","D","D+","C-","C","C+","B-","B","B+","A-","A","A+"],
           y_range=["F","D-","D","D+","C-","C","C+","B-","B","B+","A-","A","A+"])

#add description label
description=Label(x=7,y=1,text="This graph shows average grades and exam grades for 3rd grade students",render_mode="css")
f.add_layout(description)

#add labels for glyphs
labels=LabelSet(x="average_grades",y="exam_grades",text="student_names",x_offset=5, y_offset=5, source=source)
f.add_layout(labels)

#create glyphs
f.circle(x="average_grades", y="exam_grades", source=source, size=8)

show(f)


                                line_width=2)
span_solid_average_boil = Span(location=solid_average_boil,
                               dimension='width',
                               line_color='red',
                               line_width=2)

# add the spans
# add the instance
f.add_layout(span_gas_average_boil)
f.add_layout(span_liquid_average_boil)
f.add_layout(span_solid_average_boil)

#Add labels to spans
label_span_gas_average_boil = Label(x=80,
                                    y=gas_average_boil,
                                    text="Gas average boiling point",
                                    render_mode="css",
                                    text_font_size="10px")
label_span_liquid_average_boil = Label(x=80,
                                       y=liquid_average_boil,
                                       text="Liquid average boiling point",
                                       render_mode="css",
                                       text_font_size="10px")
label_span_solid_average_boil = Label(x=80,
                                      y=solid_average_boil,
                                      text="Solid average boiling point",
                                      render_mode="css",
                                      text_font_size="10px")

#Add labels to figure
f.add_layout(label_span_gas_average_boil)
    top=mean_discount,
    left=mean_disper,  # 设置矩形四边位置
    fill_alpha=0.1,
    fill_color='olive'  # 设置透明度、颜色
)
p.add_layout(right_down)

## 添加注释
from bokeh.models.annotations import Label

# 设置四个注释的位置

label1 = Label(
    x=0.1,
    y=0.8,  # 标注注释位置
    #x_offset=12,    # x偏移,同理y_offset
    text="少量少打折",  # 注释内容
    text_font_size="12pt",  # 字体大小
)
p.add_layout(label1)

label2 = Label(
    x=0.5,
    y=0.8,  # 标注注释位置
    #x_offset=12,    # x偏移,同理y_offset
    text="少量少打折",  # 注释内容
    text_font_size="12pt",  # 字体大小
)
p.add_layout(label2)

label3 = Label(
    def ex_7_create_label_annotations_for_span(self):
        # Remove rows with NaN values and then map standard states to colors
        elements.dropna(
            inplace=True
        )  # if inplace is not set to True the changes are not written to the dataframe
        colormap = {'gas': 'yellow', 'liquid': 'orange', 'solid': 'red'}
        elements['color'] = [colormap[x] for x in elements['standard state']]
        elements['size'] = elements['van der Waals radius'] / 10

        # Create three ColumnDataSources for elements of unique standard states
        gas = ColumnDataSource(elements[elements['standard state'] == 'gas'])
        liquid = ColumnDataSource(
            elements[elements['standard state'] == 'liquid'])
        solid = ColumnDataSource(
            elements[elements['standard state'] == 'solid'])

        # Define the output file path
        output_file("elements_annotations.html")

        # Create the figure object
        f = figure()

        # adding glyphs
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Gas',
                 source=gas)
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Liquid',
                 source=liquid)
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Solid',
                 source=solid)

        # Add axis labels
        f.xaxis.axis_label = "Atomic radius"
        f.yaxis.axis_label = "Boiling point"

        # Calculate the average boiling point for all three groups by dividing the sum by the number of values
        gas_average_boil = sum(gas.data['boiling point']) / len(
            gas.data['boiling point'])
        liquid_average_boil = sum(liquid.data['boiling point']) / len(
            liquid.data['boiling point'])
        solid_average_boil = sum(solid.data['boiling point']) / len(
            solid.data['boiling point'])

        # Create three spans
        span_gas_average_boil = Span(location=gas_average_boil,
                                     dimension='width',
                                     line_color='yellow',
                                     line_width=2)
        span_liquid_average_boil = Span(location=liquid_average_boil,
                                        dimension='width',
                                        line_color='orange',
                                        line_width=2)
        span_solid_average_boil = Span(location=solid_average_boil,
                                       dimension='width',
                                       line_color='red',
                                       line_width=2)

        # Add spans to the figure
        f.add_layout(span_gas_average_boil)
        f.add_layout(span_liquid_average_boil)
        f.add_layout(span_solid_average_boil)

        # Add labels to spans
        label_span_gas_average_boil = Label(x=80,
                                            y=gas_average_boil,
                                            text="Gas average boiling point",
                                            render_mode="css",
                                            text_font_size="10px")
        label_span_liquid_average_boil = Label(
            x=80,
            y=liquid_average_boil,
            text="Liquid average boiling point",
            render_mode="css",
            text_font_size="10px")
        label_span_solid_average_boil = Label(
            x=80,
            y=solid_average_boil,
            text="Solid average boiling point",
            render_mode="css",
            text_font_size="10px")

        # Add labels to figure
        f.add_layout(label_span_gas_average_boil)
        f.add_layout(label_span_liquid_average_boil)
        f.add_layout(label_span_solid_average_boil)

        # Save and show the figure
        show(f)