Exemple #1
0
def get_empty_triangle_canvas(title):
    p = figure(title=title)
    # draw the axes
    f0 = (0, 0, 1)
    f1 = (0, 1, 0)
    f2 = (1, 0, 0)

    p.add_layout(
        Arrow(end=NormalHead(fill_color="gray"),
              x_start=triangle_transform(*f0)[0],
              y_start=triangle_transform(*f0)[1],
              x_end=triangle_transform(*f1)[0],
              y_end=triangle_transform(*f1)[1]))  # F0
    p.add_layout(
        Arrow(end=NormalHead(fill_color="gray"),
              x_start=triangle_transform(*f1)[0],
              y_start=triangle_transform(*f1)[1],
              x_end=triangle_transform(*f2)[0],
              y_end=triangle_transform(*f2)[1]))  # F1
    p.add_layout(
        Arrow(end=NormalHead(fill_color="gray"),
              x_start=triangle_transform(*f2)[0],
              y_start=triangle_transform(*f2)[1],
              x_end=triangle_transform(*f0)[0],
              y_end=triangle_transform(*f0)[1]))  # F2

    return p
Exemple #2
0
def test_arrow(output_file_url, selenium, screenshot):

    # Have to specify x/y range as labels aren't included in the plot area solver
    plot = figure(height=HEIGHT, width=WIDTH, x_range=(0,10), y_range=(0,10), tools='')

    arrow1 = Arrow(x_start=1, y_start=3, x_end=6, y_end=8,
                   line_color='green', line_alpha=0.7,
                   line_dash='8 4', line_width=5, end=OpenHead()
                   )
    arrow1.end.line_width=8

    arrow2 = Arrow(x_start=2, y_start=2, x_end=7, y_end=7,
                   start=NormalHead(), end=VeeHead()
                   )
    arrow2.start.fill_color = 'indigo'
    arrow2.end.fill_color = 'orange'
    arrow2.end.size = 50

    plot.add_layout(arrow1)
    plot.add_layout(arrow2)

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)

    # Take screenshot
    assert screenshot.is_valid()
Exemple #3
0
def generate(data, incoming_arrow_data, outgoing_arrow_data):
    plot = figure(title="", x_axis_label='', y_axis_label='', sizing_mode="scale_height")
    plot.xgrid.grid_line_color            = None
    plot.ygrid.grid_line_color            = None
    plot.xaxis.major_tick_line_color      = None
    plot.xaxis.minor_tick_line_color      = None
    plot.xaxis.major_label_text_color     = '#ffffff'
    plot.xaxis.major_label_text_font_size = '0px'
    plot.xaxis.axis_line_color            = "#ffffff"
    plot.yaxis.major_tick_line_color      = None
    plot.yaxis.minor_tick_line_color      = None
    plot.yaxis.major_label_text_color     = '#ffffff'
    plot.yaxis.major_label_text_font_size = '0px'
    plot.yaxis.axis_line_color            = "#ffffff"
    plot.toolbar.logo                     = None
    plot.toolbar_location                 = None

    source = ColumnDataSource(data)
    mapper = LinearColorMapper(palette=colors_hex, low=0, high=len(colors_hex))
    labels = LabelSet(x="x", y="y", text="value", text_align="center", text_font="helvetica", text_font_size="16pt", x_offset=0, y_offset=-12, source=source, render_mode='canvas')
    plot.rect(x="x", y="y", width=1, height=1, source=source, fill_color={'field': 'value', 'transform': mapper}, line_color="#000000", line_alpha=0)
    plot.add_layout(labels)
    
    if incoming_arrow_data:
        incoming_arrow_source = ColumnDataSource(incoming_arrow_data)
        incoming_arrows = Arrow(end=VeeHead(fill_color="gray"), source=incoming_arrow_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color="gray")
        plot.add_layout(incoming_arrows)

    if outgoing_arrow_data:
        outgoing_arrow_source = ColumnDataSource(outgoing_arrow_data)
        outgoing_arrows = Arrow(end=VeeHead(fill_color="black"), source=outgoing_arrow_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color="black")
        plot.add_layout(outgoing_arrows)

    return plot
Exemple #4
0
    def __init__(self):
        self.StrCapabilityPlot = figure(plot_width=580, plot_height=595,
                                     tools='', title="Storage capability curve")

        self.StrCapabilityPlot.xaxis.axis_label = 'Q [p.u]'
        self.StrCapabilityPlot.yaxis.axis_label = 'P [p.u]'
        self.StrCapabilityPlot.toolbar.logo = None
        self.StrCapabilityPlot.toolbar_location = None
        self.StrCapabilityPlot.y_range = Range1d(*(-1.15, 1.15))
        self.StrCapabilityPlot.x_range = Range1d(*(-1.15, 1.15))
        self.StrCapabilityPlot.circle(x=[0], y=[0], radius=1.00, line_color ="navy", fill_color=None, size= 1)
        self.StrCapabilityPlot.add_layout(Arrow(end=VeeHead(size=10), line_color="black",
                                                x_start=0.0, y_start=-1.1, x_end=0, y_end=1.1))
        self.StrCapabilityPlot.add_layout(Arrow(end=VeeHead(size=10), line_color="black",
                                                x_start=-1.1, y_start=0, x_end=1.1, y_end=0))

        self.StoragecurveDatasource  = ColumnDataSource(data=dict(x0=[], x1=[], x2=[], y0=[], y1=[], y2=[]))

        self.StrCapabilityPlot.line('x0', 'y0', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")
        self.StrCapabilityPlot.line('x1', 'y1', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")
        self.StrCapabilityPlot.line('x2', 'y2', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")

        Storagewidgetbox = self.createStoragewidgetbox()

        PVsettingsLayout = column(self.StrCapabilityPlot, Storagewidgetbox, width=800)
        self.final_layout = PVsettingsLayout

        for w in [self.kWratingSlider, self.PFslider]:
            w.on_change('value', self.updateStoragecurves)

        return
    def plot_label(self, fig):
        # only plot once!
        # use ColumnDataSource updates to change the plot
        # no re-plotting necessary!


        # plot point load
        point_load_glyph = Arrow(end=OpenHead(line_color=color_arrow,line_width=2, size=5), 
                        x_start='xS', x_end='xE', y_start='yS', y_end='yE',
                        line_width='lW', line_color='lC', source=self.point_load_source)
        fig.add_layout(point_load_glyph)

        # plot loads that use patches
        fig.patch(x='x', y='y', fill_alpha=0.5, source=self.constant_load_source)
        fig.patch(x='x', y='y', fill_alpha=0.5, source=self.triangular_load_source)
        fig.patches(xs='x', ys='y', color='c', fill_alpha=0.5, source=self.temperature_load_source)

        # plot the labels for the corresponding load
        labels = LabelSet(x='x', y='y', text='name', level='glyph', render_mode='canvas', source=self.load_labels)
        fig.add_layout(labels)

        # add force arrows into the patches
        arrow_glyphs = Arrow(end=OpenHead(line_color=color_arrow,line_width=2, size=5), 
                x_start='xS', x_end='xE', y_start='yS', y_end='yE',
                line_width='lW', line_color='lC', source=self.arrow_source)
        fig.add_layout(arrow_glyphs)
Exemple #6
0
def update() -> None:
    if toggles['pause'].active:
        return

    ds_now = data_sources['now'].data
    ds_history = data_sources['history'].data

    if ds_now['epoch'][0] + 1 > sliders['max_epoch'].value:
        return

    batches_x, batches_y = create_batches()

    for batch_x, batch_y in zip(batches_x, batches_y):
        weight_previous = tensors['weight_model']
        weight_updated = gradient_descent(batch_y, batch_x, weight_previous)

        arrow_head = VeeHead(size=5,
                             fill_color='darkgrey',
                             line_color='darkgrey')
        arrow = Arrow(end=arrow_head,
                      line_color='darkgrey',
                      x_start=ds_history['weight_0'][-1],
                      y_start=ds_history['weight_1'][-1],
                      x_end=weight_updated.numpy()[0, 0],
                      y_end=weight_updated.numpy()[1, 0])
        fig.add_layout(arrow)

        loss = loss_function(tensors['y_true'],
                             pass_neuron(tensors['X'],
                                         weight_updated)).numpy()[0]

        ds_history['weight_0'] += [weight_updated.numpy()[0, 0]]
        ds_history['weight_1'] += [weight_updated.numpy()[1, 0]]

        ds_now['loss'] = [loss]
        ds_now['weight_0'] = [weight_updated.numpy()[0, 0]]
        ds_now['weight_1'] = [weight_updated.numpy()[1, 0]]

        tensors['weight_model'] = weight_updated

    ds_now['epoch'] = [ds_now['epoch'][0] + 1]

    for arrow in fig.center[2:-sliders['num_samples'].value]:
        arrow.line_color = 'lightgrey'
        arrow.end.fill_color = 'lightgrey'
        arrow.end.line_color = 'lightgrey'

    return
def get_empirical_figure(x, y, data):
    fig = figure(
        height=600,
        sizing_mode='stretch_width',
        x_axis_label='X',
        y_axis_label='F(x)'
    )

    x.append(x[len(x)-1]+1)
    y.append(y[len(y)-1])
    fig.circle(x=x, y=y, fill_alpha=0)

    for i in range(0, len(data)):
        x = data[i+1].get('x') if i != len(data)-1 else data[i].get('x')+1
        fig.add_layout(Arrow(
            end=NormalHead(size=10, fill_color="blue"),
            line_color="blue",
            line_width=2,
            x_start=x,
            y_start=data[i].get('w_nak'),
            x_end=data[i].get('x'),
            y_end=data[i].get('w_nak')
        ))
        fig.add_layout(Span(
            location=data[i].get('x'),
            dimension='height', line_color='black',
            line_dash='dashed', line_width=1
        ))

    fig.yaxis.fixed_location = 0

    return fig
Exemple #8
0
    def _init_glyph(self, plot, mapping, properties, key):
        """
        Returns a Bokeh glyph object.
        """
        properties = {k: v for k, v in properties.items() if 'legend' not in k}

        if key == 'arrow_1':
            source = properties.pop('source')
            arrow_end = mapping.pop('arrow_end')
            arrow_start = mapping.pop('arrow_start')
            for p in ('alpha', 'color'):
                v = properties.pop(p, None)
                for t in ('line', 'fill'):
                    if v is None:
                        continue
                    key = '_'.join([t, p])
                    if key not in properties:
                        properties[key] = v
            start = arrow_start(**properties) if arrow_start else None
            end = arrow_end(**properties) if arrow_end else None
            line_props = {p: v for p, v in properties.items() if p.startswith('line_')}
            renderer = Arrow(start=start, end=end, source=source,
                             **dict(line_props, **mapping))
            glyph = renderer
        else:
            properties = {p if p == 'source' else 'text_'+p: v
                          for p, v in properties.items()}
            renderer, glyph = super(ArrowPlot, self)._init_glyph(
                plot, mapping, properties, key)
        plot.renderers.append(renderer)
        return renderer, glyph
Exemple #9
0
    def add_path(self, path, shock=False, thin=False):
        path["X_1"] = path["X"] + path["dX"]
        path["Y_1"] = path["Y"] + path["dY"]
        if shock:
            path["X_1"] = path["X_1"] / 10

        if thin:
            width = 1 / self.proportion
        else:
            width = 2 / self.proportion

        self.p.line(
            x=path.iloc[:-1, 0],
            y=path.iloc[:-1, 1],
            line_color="white",
            line_width=width,
        )

        last = path.iloc[-2, :]
        self.p.add_layout(
            Arrow(
                end=NormalHead(
                    line_color=None, fill_color="white", size=4 / self.proportion
                ),
                x_start=last["X"],
                y_start=last["Y"],
                x_end=last["X_1"],
                y_end=last["Y_1"],
                line_width=width,
                line_color="#FFFFFF",
            )
        )
Exemple #10
0
def map_demand(demand, network):

    demand_xy_df, agg_demand_df, agg_od_df, taz_df = prepare_demand(
        network, demand)

    o_trip_count_df = demand_xy_df.groupby(
        ['o_taz']).size().reset_index(name='o_trips')
    d_trip_count_df = demand_xy_df.groupby(
        ['d_taz']).size().reset_index(name='d_trips')

    p_map = figure(x_axis_type="mercator",
                   y_axis_type="mercator",
                   title="Origin and Destinations for Transit Trips",
                   width=800)
    p_map.grid.visible = False
    p_map.add_tile(STAMEN_TONER)

    source = ColumnDataSource(
        data=dict(x=list(agg_demand_df['taz-lon']),
                  y=list(agg_demand_df['taz-lat']),
                  origins=list(agg_demand_df['origins']),
                  destinations=list(agg_demand_df['destinations'])))

    p_map.circle(x='x',
                 y='y',
                 source=source,
                 size="origins",
                 legend="origin",
                 fill_color="green",
                 line_color="green",
                 fill_alpha=0.15,
                 line_alpha=0.15)

    p_map.circle(x='x',
                 y='y',
                 source=source,
                 size="destinations",
                 legend="destination",
                 fill_color="navy",
                 line_color="blue",
                 line_width=4,
                 fill_alpha=0.01,
                 line_alpha=0.2)

    for index, row in agg_od_df.iterrows():
        x1 = row['o-lon']
        x2 = row['d-lon']
        y1 = row['o-lat']
        y2 = row['d-lat']

        p_map.line([x1, x2], [y1, y2], line_width=row['trips'], line_alpha=0.2)
        p_map.add_layout(
            Arrow(end=OpenHead(size=row['trips']),
                  line_color="navy",
                  line_alpha=0.2,
                  x_start=x1,
                  y_start=y1,
                  x_end=x2,
                  y_end=y2))
    return p_map
Exemple #11
0
def arrows(pos_i=None, pos_f=None, p=None, names=None, color='black'):

    if pos_i is None:
        pos_i = np.zeros_like(pos_f)

    for i, (x0, y0, xf, yf) in enumerate(np.hstack((pos_i, pos_f))):
        p.add_layout(
            Arrow(end=VeeHead(fill_color=color, line_color=color, size=10),
                  x_start=x0,
                  y_start=y0,
                  x_end=xf,
                  y_end=yf))

        if names is not None:
            vec_norm = np.sqrt((xf - x0)**2 + (yf - y0)**2)

            labels = Label(x=xf,
                           y=yf,
                           text=names[i],
                           text_color=color,
                           x_offset=vec_norm * 0.2,
                           y_offset=vec_norm * 0.2)

            p.add_layout(labels)

    return p
Exemple #12
0
def test_Arrow() -> None:
    arrow = Arrow()
    assert arrow.x_start == field("x_start")
    assert arrow.y_start == field("y_start")
    assert arrow.start_units == 'data'
    assert arrow.start is None
    assert arrow.x_end == field("x_end")
    assert arrow.y_end == field("y_end")
    assert arrow.end_units == 'data'
    assert isinstance(arrow.end, ArrowHead)
    assert isinstance(arrow.source, ColumnDataSource)
    assert arrow.x_range_name == "default"
    assert arrow.y_range_name == "default"
    check_line_properties(arrow)
    check_properties_existence(
        arrow, ANNOTATION + [
            "x_start",
            "y_start",
            "start_units",
            "start",
            "x_end",
            "y_end",
            "end_units",
            "end",
            "source",
        ], LINE)
Exemple #13
0
    def render_graph(self, vert_size):
        display_graph = GraphRenderer(kwargs)

        display_graph.node_renderer.data_src.add(
            list(self.graph.vertices.keys()), "index")
        display_graph.node_renderer.data_src.add(self.get_colors(), "color")
        display_graph.node_renderer.glyph = Circle(size=vert_size,
                                                   fill_color="color")

        display_graph.node__renderer.data_src.data = self.get_edges()
        self.randomize()
        for i in range(len(
                display_graph.edge_renderer.data_src.data["start"])):
            self.plot.add_layout(
                Arrow(
                    end=NormalHead(fill_color="blue"),
                    x_start=self.pos[display_graph.edge_renderer.ddata.src.
                                     data["start"][i]][0],
                    x_end=self.pos[display_graph.edge_renderer.ddata.src.
                                   data["end"][i]][0],
                    y_start=self.pos[display_graph.edge_renderer.ddata.src.
                                     data["start"][i]][1],
                    y_end=self.pos[display_graph.edge_renderer.ddata.src.
                                   data["end"][i]][1],
                ))
Exemple #14
0
def notebook_bokeh(stcs):
    patch_xs = parse_s_region(stcs)['ra']
    patch_ys = parse_s_region(stcs)['dec']

    p = figure(plot_width=700,
               x_axis_label="RA (deg)",
               y_axis_label="Dec (deg)")

    data = {'x': [patch_xs], 'y': [patch_ys]}
    p.patches('x',
              'y',
              source=data,
              fill_alpha=0.1,
              line_color="black",
              line_width=0.5)

    p.add_layout(
        Arrow(end=VeeHead(line_color="black", line_width=1),
              line_width=2,
              x_start=patch_xs[0],
              y_start=patch_ys[0],
              x_end=patch_xs[1],
              y_end=patch_ys[1]))

    p.y_range.flipped = True

    output_notebook()
    show(p)
Exemple #15
0
    def _setup_graph_renderer(self, circle_size):
        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(
            list(self.graph.vertices.keys()), "index")
        graph_renderer.node_renderer.data_source.add(self._get_random_colors(),
                                                     "color")
        graph_renderer.node_renderer.glyph = Circle(size=circle_size,
                                                    fill_color="color")
        graph_renderer.edge_renderer.data_source.data = self._get_edge_indexes(
        )
        self.randomize()
        for i in range(
                len(graph_renderer.edge_renderer.data_source.data["start"])):
            self.plot.add_layout(
                Arrow(
                    end=VeeHead(size=20, fill_color="black"),
                    x_start=self.pos[graph_renderer.edge_renderer.data_source.
                                     data["start"][i]][0],
                    y_start=self.pos[graph_renderer.edge_renderer.data_source.
                                     data["start"][i]][1],
                    x_end=self.pos[graph_renderer.edge_renderer.data_source.
                                   data["end"][i]][0],
                    y_end=self.pos[graph_renderer.edge_renderer.data_source.
                                   data["end"][i]][1],
                ))

        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=self.pos)
        self.plot.renderers.append(graph_renderer)
        self._get_labels()
Exemple #16
0
def complex_notations_plot(*args):
    zs = np.array(args)
    m = max(np.max(np.real(np.abs(zs))), np.max(np.imag(np.abs(zs)))) + 1

    fig1 = figure(title="Complex Plane (Rectangular)",
                  plot_height=400,
                  plot_width=400,
                  x_range=[-m, m],
                  y_range=[-m, m],
                  toolbar_location=None)

    bokeh_central_axis(fig1, axis='both')
    bokeh_major_ticks(fig1)
    bokeh_hide_border(fig1)

    fig2 = figure(title="Complex Plane (Polar)",
                  plot_height=400,
                  plot_width=400,
                  x_range=[-m, m],
                  y_range=[-m, m],
                  toolbar_location=None)

    bokeh_central_axis(fig2, axis='both')
    bokeh_no_ticks(fig2)
    bokeh_hide_border(fig2)
    bokeh_hide_grid(fig2)

    for z in zs:
        c = 'green'
        z1_arrow = Arrow(x_start=0,
                         y_start=0,
                         x_end=np.real(z),
                         y_end=np.imag(z),
                         end=OpenHead(size=9, line_color=c),
                         line_color=c)
        z2_arrow = Arrow(x_start=0,
                         y_start=0,
                         x_end=np.real(z),
                         y_end=np.imag(z),
                         end=OpenHead(size=9, line_color=c),
                         line_color=c)
        fig1.add_layout(z1_arrow)
        fig2.add_layout(z2_arrow)

    show(row(fig1, fig2))
Exemple #17
0
def getWindCircle(circle_radius, dirList):
    radial_fig = figure(title="Wind Direction",
                        plot_width=500,
                        plot_height=500,
                        x_range=(-40, 40),
                        y_range=(-40, 40))
    radial_fig.circle(0,
                      0,
                      radius=circle_radius,
                      fill_color='#F4F6F6',
                      line_color='black')
    # add the smaller circles
    x_cir_ang, y_cir_ang = getAngularPoints(
        np.array(np.zeros(len(dirList), )) + circle_radius, dirList)
    radial_fig.circle(x=x_cir_ang, y=y_cir_ang, size=4, fill_color='black')
    # add wind annotations
    disp_wind = np.array([0, 60, 120, 180, 240, 300])
    x_cir_label_ang, y_cir_label_ang = getAngularPoints(
        np.array(np.zeros(len(disp_wind), )) + circle_radius + 1, disp_wind)
    cir_label_source = ColumnDataSource(
        data=dict(x=x_cir_label_ang, y=y_cir_label_ang, text=disp_wind))
    circle_labels = LabelSet(x='x',
                             y='y',
                             text='text',
                             level='glyph',
                             x_offset=0,
                             y_offset=0,
                             render_mode='canvas',
                             text_font_size='10pt',
                             source=cir_label_source)
    circle_title = Label(x=-6,
                         y=-1,
                         text='Wind Direction',
                         render_mode='canvas',
                         text_font_size='10pt',
                         text_font='helvetica',
                         text_font_style='bold')
    radial_fig.add_layout(circle_labels)
    true_north = Label(x=-0.5,
                       y=8,
                       text='N',
                       render_mode='canvas',
                       text_font_size='10pt',
                       text_font='helvetica',
                       text_font_style='bold')
    radial_fig.add_layout(
        Arrow(end=OpenHead(line_color="navy", line_width=2, size=10),
              x_start=0,
              y_start=-7.5,
              x_end=0,
              y_end=7.5,
              line_color='navy',
              line_width=2))
    radial_fig.add_layout(true_north)
    radial_fig.add_layout(circle_title)
    radial_fig.axis.visible = False
    return radial_fig
def setup_timeline_backend_parts(plot: figure,
                                 desc_label_source: ColumnDataSource) -> None:
    """

    :param plot:
    :param desc_label_source:
    :return:
    """
    start_date, end_date = plot.x_range.start, plot.x_range.end
    arrow_x = start_date + datetime.timedelta(days=180)

    # 補助線を引く
    plot.line([start_date, end_date], [1, 1], line_width=3, line_color='pink')
    plot.line([start_date, end_date], [0.5, 0.5],
              line_width=3,
              line_dash='dotted',
              line_color='pink')
    plot.line([start_date, end_date], [1.5, 1.5],
              line_width=3,
              line_dash='dotted',
              line_color='pink')

    # 矢印を表示する
    plot.add_layout(
        Arrow(end=VeeHead(size=15),
              line_color='black',
              x_start=arrow_x,
              y_start=1.4,
              x_end=arrow_x,
              y_end=1.1))
    plot.add_layout(
        Arrow(end=VeeHead(size=15),
              line_color='black',
              x_start=arrow_x,
              y_start=0.9,
              x_end=arrow_x,
              y_end=0.6))

    plot.text(source=desc_label_source,
              x='x',
              y='y',
              text='text',
              text_font_size='size',
              text_alpha=0.8)
def strut_pressure_plot(layers, net, brace_elev):
    axis_size = max([max(net[0]), -1 * min(net[0])])
    p = figure(
        x_range=[-axis_size-1000, axis_size*2.5],
        y_range=[net[1][-1]-3, net[1][0]+3],
        title="Strut Pressure Diagram",
        plot_width=800,
        plot_height=1200
    )
    p.xaxis.bounds = (0, 0)
    p.yaxis.bounds = (0, 0)
    p.line(net[0], net[1], line_width=2, color='black')
    p.line([0, 0], [layers[0][0], layers[-1][0]], color='black')
    p.add_layout(Label(x=1.5*axis_size, y=net[1][0] + 2, text="Pressure"))
    for i in range(len(layers)):
        p.line([-axis_size-1000, axis_size*2.5], [layers[i][0], layers[i][0]],
               color='dimgray', alpha=0.7)
        work_point_label = Label(x=-axis_size-1000, y=layers[i][0], text=str(layers[i][0]), text_font_size='12pt')
        p.add_layout(work_point_label)

    x, y = 0, 0
    for k in range(len(net[0])):
        i = net[0][k]
        j = net[1][k]
        if j == y and i != x:
            pressure_label = Label(x=axis_size*1.5, y=j-0.5, text=str(i), text_font_size='12pt')
        else:
            pressure_label = Label(x=axis_size*1.5, y=j, text=str(i), text_font_size='12pt')
        x, y = i, j
        p.add_layout(pressure_label)
    p.add_layout(Arrow(end=NormalHead(size=10),
                       x_start=-0.25*axis_size, y_start=brace_elev[0], x_end=00, y_end=brace_elev[0]))
    p.add_layout(Arrow(end=NormalHead(size=10),
                       x_start=-0.25 * axis_size, y_start=brace_elev[1], x_end=00, y_end=brace_elev[1]))
    top_waler_label = Label(x=-0.4*axis_size, y=brace_elev[0]-0.5, text='T1')
    bot_waler_label = Label(x=-0.4*axis_size, y=brace_elev[1]-0.5, text='T2')
    p.add_layout(top_waler_label)
    p.add_layout(bot_waler_label)
    if len(brace_elev) == 3:
        t3_waler_label = Label(x=-0.4*axis_size, y=brace_elev[2]-0.5, text='T3')
        p.add_layout(t3_waler_label)
        p.add_layout(Arrow(end=NormalHead(size=10),
                           x_start=-0.25 * axis_size, y_start=brace_elev[2], x_end=00, y_end=brace_elev[2]))
    return p
def biplot(score, coeff, expl_var, decomp='PCA', meta=None, fig_dir=None):

    coeff /= (np.abs(coeff).max() - np.abs(coeff).min()) * 1.5
    score /= (score.max() - score.min())

    coeff['norm'] = coeff.x**2 + coeff.y**2
    coeff = coeff.sort_values(by='norm', ascending=False).iloc[:8]

    labels = meta.unique()

    if len(labels) < 11:
        colors = Category10[len(labels)]
    else:
        colors = inferno(len(labels))
    color_map = {label: colors[i] for i, label in enumerate(labels)}

    score[meta.name] = meta.values
    score['color'] = [color_map[label] for label in meta.values]

    p = figure(plot_width=800,
               plot_height=800,
               x_range=(-1, 1),
               y_range=(-1, 1),
               title='Covariate contribution to the first 2 components')
    p.circle(x=score.columns[0],
             y=score.columns[1],
             color='color',
             alpha=0.25,
             size=5,
             legend_group=meta.name,
             source=score)

    for (x, y, _) in coeff.values:
        p.add_layout(
            Arrow(end=NormalHead(fill_color="orange", size=12, line_width=1),
                  x_start=0,
                  y_start=0,
                  x_end=x,
                  y_end=y))

    labels = LabelSet(x='x',
                      y='y',
                      text='index',
                      level='glyph',
                      x_offset=5,
                      y_offset=5,
                      render_mode='canvas',
                      source=ColumnDataSource(coeff.reset_index()))

    p.add_layout(labels)
    p.xaxis.axis_label = 'Component 1 ({:.1%})'.format(expl_var[0])
    p.yaxis.axis_label = 'Component 2 ({:.1%})'.format(expl_var[1])

    output_file(f"{fig_dir}/biplot_{decomp}.html")
    save(p)
 def __init__(self):
     # save original shape of car in a shape (to make displacement easy)
     self.carshape = SD_Shape(
         [-3, 0, 0, -0.05, -0.5, -1, -2, -2, -3],
         [0.25, 0.25, 0.7, 0.75, 0.75, 1.25, 1.25, 0.75, 0.75])
     # create column data sources for the car and its acceleration
     self.car = ColumnDataSource(
         data=dict(x=self.carshape.x, y=self.carshape.y))
     self.wheels = ColumnDataSource(data=dict(
         x=[-2.25, -0.75], y=[0.25, 0.25], w=[0.5, 0.5], h=[0.5, 0.5]))
     self.arrow = ColumnDataSource(data=dict(xS=[], yS=[], xE=[], yE=[]))
     self.v_label = ColumnDataSource(data=dict(x=[], y=[], S=[]))
     # create the figure
     self.fig = figure(tools="",
                       x_range=(-4, 31),
                       y_range=(0, 4),
                       height=100)
     #  remove graph lines
     self.fig.yaxis.visible = False
     self.fig.grid.visible = False
     self.fig.toolbar.logo = None
     self.fig.outline_line_color = None
     # draw the house
     self.fig.line([30.0, 30.0, 29.5, 30.5], [0, 3.0, 3.0, 4.0],
                   line_color="black",
                   line_width=4)
     # add the car chassis to the image
     self.fig.patch(x='x', y='y', color="#0065BD", source=self.car)
     # add the car wheels to the image
     self.fig.ellipse(x='x',
                      y='y',
                      width='w',
                      height='h',
                      source=self.wheels,
                      color="#0065BD")
     # create and add the arrow representing the velocity to the diagram
     arrow_glyph = Arrow(end=OpenHead(line_color="#003359",
                                      line_width=2,
                                      size=10),
                         x_start='xS',
                         y_start='yS',
                         x_end='xE',
                         y_end='yE',
                         source=self.arrow,
                         line_color="#003359",
                         line_width=2)
     self.fig.add_layout(arrow_glyph)
     # create the label for the velocity and add it to the diagram
     v_glyph = LabelSet(x='x',
                        y='y',
                        text='S',
                        text_color='#003359',
                        level='glyph',
                        source=self.v_label)
     self.fig.add_layout(v_glyph)
 def st_RHS_plotting(self):
     """
     Plot the drag factors on a sharp cornered rectanglar exposed member
     """
     plot = Plot(title=None, match_aspect=True)
     glyph = Rect(x=0,
                  y=0,
                  width=self.d,
                  height=self.b,
                  fill_color="#cab2d6")
     plot.add_glyph(glyph)
     plot.add_layout(
         Arrow(end=NormalHead(fill_color="orange"),
               x_start=0,
               y_start=self.b / 4,
               x_end=0,
               y_end=self.b / 2))
     plot.add_layout(
         Arrow(end=NormalHead(fill_color="orange"),
               x_start=-self.d / 2,
               y_start=0,
               x_end=-self.d / 4,
               y_end=0))
     plot.add_layout(LinearAxis(), 'below')
     plot.add_layout(LinearAxis(), 'left')
     plot.add_glyph(
         Text(
             x=0,
             y=self.b / 2,
             text=[
                 f"Cf_y = {self.Cf_y:.2f}\nsigma_wind = {self.sigma_wind_vert/1000:.2f} kPa"
             ],
             text_align="left"))
     plot.add_glyph(
         Text(
             x=-self.d / 4,
             y=0,
             text=[
                 f"Cf_x = {self.Cf_x:.2f}\nsigma_wind = {self.sigma_wind_horiz/1000:.2f} kPa"
             ],
             text_align="left"))
     return plot
Exemple #23
0
def bokeh_scatter_plot_xy_words(df_words,
                                title='',
                                xlabel='',
                                ylabel='',
                                line_data=False,
                                filename=None,
                                default_color='blue',
                                plot_width=700,
                                plot_height=600):

    plot = bp.figure(plot_width=plot_width,
                     plot_height=plot_height,
                     title=title,
                     tools=TOOLS,
                     toolbar_location="above"
                     )  #, x_axis_type=None, y_axis_type=None, min_border=1)

    color = 'color' if 'color' in df_words.columns else default_color

    plot.scatter(x='x', y='y', size=8, source=df_words, alpha=0.5, color=color)

    plot.xaxis[0].axis_label = xlabel
    plot.yaxis[0].axis_label = ylabel

    source = ColumnDataSource(df_words)
    labels = LabelSet(x='x',
                      y='y',
                      text='words',
                      level='glyph',
                      text_font_size="9pt",
                      x_offset=5,
                      y_offset=5,
                      source=source,
                      render_mode='canvas')

    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = {"word": "@words"}

    if line_data is True:
        end_arrow = OpenHead(line_color="firebrick", line_width=1, size=10)
        for i in range(1, len(df_words.index), 2):
            x_start, y_start = df_words.iloc[i - 1]['x'], df_words.iloc[i -
                                                                        1]['y']
            x_end, y_end = df_words.iloc[i]['x'], df_words.iloc[i]['y']
            plot.add_layout(
                Arrow(end=end_arrow,
                      x_start=x_start,
                      y_start=y_start,
                      x_end=x_end,
                      y_end=y_end))

    plot.add_layout(labels)
    return plot
Exemple #24
0
def plot_stream_arrow(plot,
                      line_color,
                      stream_arrow_temp,
                      temp_label_font_size,
                      x_start,
                      x_end,
                      y_start,
                      y_end,
                      stream_name=None):
    """Plot a stream arrow for the heat exchanger network diagram.

        Args:
            plot: bokeh.plotting.plotting.figure instance.
            line_color: color of arrow (defaults to white).
            stream_arrow_temp: Tempreature of the stream to be plotted.
            temp_label_font_size: font-size of the temperature label to be added.
            x_start: x-axis coordinate of arrow base.
            x_end: x-axis coordinate of arrow head.
            y_start: y-axis coordinate of arrow base.
            y_end: y-axis coordinate of arrow head.
            stream_name: Name of the stream to add as a label to arrow (defaults to None).

        Returns:
            modified bokeh.plotting.plotting.figure instance with stream arrow added.
        
        Raises:
            None            
    """
    plot.add_layout(
        Arrow(line_color=line_color,
              end=OpenHead(line_color=line_color, line_width=2, size=10),
              x_start=x_start,
              y_start=y_start,
              x_end=x_end,
              y_end=y_end))

    temp_end_label = Label(x=x_end,
                           y=y_end,
                           x_offset=-20,
                           y_offset=8,
                           text_font_size=temp_label_font_size,
                           text=str(stream_arrow_temp))
    plot.add_layout(temp_end_label)

    if stream_name:
        stream_name_label = Label(x=x_end,
                                  y=y_end,
                                  x_offset=-10,
                                  y_offset=-12,
                                  text_font_size=temp_label_font_size,
                                  text=stream_name)
        plot.add_layout(stream_name_label)
    return plot
def add_arrows(canvas, branch, color, pf_threshold=0, dist_threshold=0, n=1):
    """Add addorws for powerflow to figure.

    :param bokeh.plotting.figure.Figure canvas: canvas to plot arrows onto.
    :param pandas.DataFrame branch: data frame containing:
        'pf', 'dist', 'arrow_size', 'from_x', 'from_y', 'to_x', 'to_y'.
        x/y coordinates for to/from can be obtained from lat/lon coordinates
        using :func:`postreise.plot.projection_helpers.project_branch`.
    :param str color: arrow line color.
    :param int/float pf_threshold: minimum power flow for a branch to get arrow(s).
    :param int/float pf_threshold: minimum distance for a branch to get arrow(s).
    :param int n: number of arrows to plot along each branch.
    """
    positive_arrows = branch.loc[(branch.pf > pf_threshold)
                                 & (branch.dist > dist_threshold)]
    negative_arrows = branch.loc[(branch.pf < -1 * pf_threshold)
                                 & (branch.dist > dist_threshold)]
    # Swap direction of negative arrows
    negative_arrows = negative_arrows.rename(columns={
        "from_x": "to_x",
        "to_x": "from_x",
        "to_y": "from_y",
        "from_y": "to_y"
    })
    # Finally, plot arrows
    arrows = pd.concat([positive_arrows, negative_arrows])
    for i in range(n):
        start_fraction = i / n
        end_fraction = (i + 1) / n
        arrows.apply(
            lambda a: canvas.add_layout(
                Arrow(
                    end=VeeHead(
                        line_color="black",
                        fill_color="gray",
                        line_width=2,
                        fill_alpha=0.5,
                        line_alpha=0.5,
                        size=a["arrow_size"],
                    ),
                    x_start=(a["from_x"] +
                             (a["to_x"] - a["from_x"]) * start_fraction),
                    y_start=(a["from_y"] +
                             (a["to_y"] - a["from_y"]) * start_fraction),
                    x_end=(a["from_x"] +
                           (a["to_x"] - a["from_x"]) * end_fraction),
                    y_end=(a["from_y"] +
                           (a["to_y"] - a["from_y"]) * end_fraction),
                    line_color=color,
                    line_alpha=0.7,
                )),
            axis=1,
        )
Exemple #26
0
def plot_ortho(plot, X_n, neg=1, color_choice='blue'):
    X_n_list = X_n.tolist()
    for i in X_n_list:
        new_point = [i[0] + neg * 1 / (5**0.5), i[1] + neg * 4 / (5**0.5)]
        plot.add_layout(
            Arrow(end=NormalHead(fill_color=color_choice, size=10),
                  x_start=i[0],
                  y_start=i[1],
                  x_end=new_point[0],
                  y_end=new_point[1],
                  line_color=color_choice,
                  line_alpha=0.8))
    return plot
Exemple #27
0
def _add_forward(fig, ftype, e, match):
    color = _get_team_color(e, match)
    fig.diamond(x=[e['start']['x'] / 100],
                y=[e['start']['y'] / 100],
                size=10, color=color, line_width=2)
    if ftype == 'goals_attempts':
        line_dash = 'dashed'
    else:
        line_dash = 'solid'
    arrow = Arrow(end=NormalHead(fill_color=color, line_color=color),
                  line_color=color, line_width=2, line_dash=line_dash,
                  x_start=e['start']['x'] / 100,
                  y_start=e['start']['y'] / 100,
                  x_end=e['end']['x'] / 100,
                  y_end=e['end']['y'] / 100)
    fig.add_layout(arrow)
Exemple #28
0
def bokeh_scatter_plot_xy_words2(df_words,
                                 title='',
                                 xlabel='',
                                 ylabel='',
                                 line_data=False):

    plot = bp.figure(plot_width=700,
                     plot_height=600,
                     title=title,
                     tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
                     toolbar_location="above"
                     )  #, x_axis_type=None, y_axis_type=None, min_border=1)

    # plotting. the corresponding word appears when you hover on the data point.
    plot.scatter(x='x', y='y', size=8, source=df_words, alpha=0.5)
    plot.xaxis[0].axis_label = xlabel
    plot.yaxis[0].axis_label = ylabel

    source = ColumnDataSource(df_words)
    labels = LabelSet(x='x',
                      y='y',
                      text='words',
                      level='glyph',
                      text_font_size="9pt",
                      x_offset=5,
                      y_offset=5,
                      source=source,
                      render_mode='canvas')

    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = {"word": "@words"}
    # df.transform(lambda x: list(zip(x, df[2])))
    if line_data is True:
        end_arrow = OpenHead(line_color="firebrick", line_width=1, size=10)
        for i in range(1, len(df_words.index), 2):
            x_start, y_start = df_words.iloc[i - 1]['x'], df_words.iloc[i -
                                                                        1]['y']
            x_end, y_end = df_words.iloc[i]['x'], df_words.iloc[i]['y']
            plot.add_layout(
                Arrow(end=end_arrow,
                      x_start=x_start,
                      y_start=y_start,
                      x_end=x_end,
                      y_end=y_end))

    plot.add_layout(labels)
    show(plot, notebook_handle=True)
Exemple #29
0
 def create_plot(self):
     super().create_plot()
     self.plot.renderers[0].edge_renderer.data_source.data[
         'edge_data'] = self.y
     G = nx.convert_node_labels_to_integers(self.G)
     layout_coords = pd.DataFrame(
         [[
             self.layout[x1][0], self.layout[x1][1], self.layout[x2][0],
             self.layout[x2][1]
         ] for (x1, x2) in G.edges()],
         columns=['x_start', 'y_start', 'x_end', 'y_end'])
     layout_coords['x_end'] = (
         layout_coords['x_end'] -
         layout_coords['x_start']) / 2 + layout_coords['x_start']
     layout_coords['y_end'] = (
         layout_coords['y_end'] -
         layout_coords['y_start']) / 2 + layout_coords['y_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'x_start'] = layout_coords['x_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'y_start'] = layout_coords['y_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'x_end'] = layout_coords['x_end']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'y_end'] = layout_coords['y_end']
     self.plot.renderers[0].edge_renderer.glyph = MultiLine(
         line_color=linear_cmap('edge_data', self.palette, self.lo,
                                self.hi),
         line_width=5)
     if self.show_bar:
         cbar = ColorBar(color_mapper=LinearColorMapper(
             palette=self.palette, low=self.lo, high=self.hi),
                         ticker=BasicTicker(),
                         title=self.desc)
         self.plot.add_layout(cbar, 'right')
     arrows = Arrow(end=VeeHead(size=8),
                    x_start='x_start',
                    y_start='y_start',
                    x_end='x_end',
                    y_end='y_end',
                    line_width=0,
                    source=self.plot.renderers[0].edge_renderer.data_source)
     self.plot.add_layout(arrows)
     # self.plot.tooltips.append((self.desc, '@edge_data'))
     return self.plot
Exemple #30
0
 def _init_glyph(self, plot, mapping, properties, key):
     """
     Returns a Bokeh glyph object.
     """
     properties.pop('legend')
     if key == 'arrow':
         properties.pop('source')
         arrow_end = mapping.pop('arrow_end')
         arrow_start = mapping.pop('arrow_start')
         start = arrow_start(**properties) if arrow_start else None
         end = arrow_end(**properties) if arrow_end else None
         glyph = Arrow(start=start, end=end, **dict(**mapping))
     else:
         properties = {p if p == 'source' else 'text_'+p: v
                       for p, v in properties.items()}
         glyph, _ = super(ArrowPlot, self)._init_glyph(plot, mapping, properties, 'text')
     plot.renderers.append(glyph)
     return None, glyph