Ejemplo n.º 1
0
    def create_legend(self):

        x_range = Range1d(0, 185)
        y_range = Range1d(0, 130)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=185,
                        plot_height=130,
                        min_border=0,
                        **PLOT_FORMATS)

        FONT_PROPS_SM['text_font_size'] = '11pt'
        text_box.add_glyph(
            Text(x=35, y=9, text=['Low Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=18,
                 width=25,
                 height=25,
                 fill_color='#ef4e4d',
                 line_color=None))
        text_box.add_glyph(
            Text(x=35, y=49, text=['Medium Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=58,
                 width=25,
                 height=25,
                 fill_color='#14a1af',
                 line_color=None))

        text_box.add_glyph(
            Text(x=35, y=89, text=['High Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=98,
                 width=25,
                 height=25,
                 fill_color='#743184',
                 line_color=None))

        self.legend_plot = text_box

        ##Filler plot
        x_range = Range1d(0, 40)
        y_range = Range1d(0, 100)
        self.legend_filler = Plot(x_range=x_range,
                                  y_range=y_range,
                                  title="",
                                  plot_width=40,
                                  plot_height=100,
                                  min_border=0,
                                  **PLOT_FORMATS)
Ejemplo n.º 2
0
def test_get_screenshot_as_png_with_glyph(webdriver, dimensions: Tuple[int, int]) -> None:
    width, height = dimensions
    border = 5

    layout = Plot(x_range=Range1d(-1, 1), y_range=Range1d(-1, 1),
                  plot_height=width, plot_width=height,
                  toolbar_location=None,
                  min_border=border,
                  hidpi=False,
                  outline_line_color=None, background_fill_color="#00ff00", border_fill_color="#00ff00")
    glyph = Rect(x="x", y="y", width=2, height=2, fill_color="#ff0000", line_color="#ff0000")
    source = ColumnDataSource(data=dict(x=[0], y=[0]))
    layout.add_glyph(source, glyph)

    png = bie.get_screenshot_as_png(layout, driver=webdriver)
    assert png.size == (width, height)

    data = png.tobytes()
    assert len(data) == 4*width*height

    # count red pixels in center area
    count = 0
    for x in range(width*height):
        pixel = data[x*4:x*4+4]
        if pixel == b"\xff\x00\x00\xff":
            count += 1

    w, h, b = width, height, border
    expected_count = w*h - 2*b*(w + h) + 4*b**2
    assert count == expected_count
Ejemplo n.º 3
0
    def test_ranges_update(self, single_plot_page: SinglePlotPage) -> None:
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        plot = Plot(height=400,
                    width=400,
                    x_range=Range1d(0, 1),
                    y_range=Range1d(0, 1),
                    min_border=0)
        plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
        plot.add_tools(PanTool())
        code = RECORD("event_name", "cb_obj.event_name", final=False) + \
               RECORD("x0", "cb_obj.x0", final=False) + \
               RECORD("x1", "cb_obj.x1", final=False) + \
               RECORD("y0", "cb_obj.y0", final=False) + \
               RECORD("y1", "cb_obj.y1")
        plot.js_on_event(RangesUpdate, CustomJS(code=code))
        plot.tags.append(CustomJS(name="custom-action", code=""))
        plot.toolbar_sticky = False

        page = single_plot_page(plot)

        page.drag_canvas_at_position(plot, 100, 100, 20, 20)

        page.eval_custom_action()

        results = page.results
        assert results['event_name'] == "rangesupdate"
        assert results['x0'] < 0
        assert results['x1'] < 1
        assert results['y0'] > 0
        assert results['y1'] > 1

        assert page.has_no_console_errors()
Ejemplo n.º 4
0
def _get_provincial_map(
    plot_width, source, tibet_source, legend_data, fill_color,
    line_color='black', line_width=0.5, tooltip_text=''
):
    p_map = get_map_plot(plot_width)
    provinces = Patches(
        xs='xs',
        ys='ys',
        fill_color=fill_color,
        line_color=line_color,
        line_width=line_width,
        line_join='round',
    )
    pr = p_map.add_glyph(source, provinces)
    tibet = Patches(
        xs='xs',
        ys='ys',
        fill_color='white',
        line_color='gray',
        line_dash='dashed',
        line_width=0.5,
    )
    tr = p_map.add_glyph(tibet_source, tibet)

    # Add legend
    legend_source = ColumnDataSource(legend_data)
    rect = Rect(
        x='x',
        y=map_legend_y,
        height=1,
        width=0.3,
        fill_color='color',
        line_color=None,
    )
    p_map.add_glyph(legend_source, rect)
    # Add start val
    text_start = [legend_data.vals[0][:-2]]
    p_map.add_glyph(
        ColumnDataSource(
            dict(x=[map_legend_x], y=[map_legend_y - 3.5], text=text_start)
        ), Text(x='x', y='y', text='text', text_font_size='7pt', text_align='left')
    )
    # Add end val
    text_end = [legend_data.vals[99][:-2]]  # Note the 99 is dependent on legend having 100 points
    if len(text_end[0]) > 5:
        text_end = [legend_data.vals[99][0:5]]
    p_map.add_glyph(
        ColumnDataSource(
            dict(x=[map_legend_x + 25], y=[map_legend_y - 3.5], text=text_end)
        ), Text(x='x', y='y', text='text', text_font_size='8pt', text_align='right')
    )

    # Add hovers
    tooltips = "<span class='tooltip-text'>@name_en</span>"
    tooltips = tooltips + "<span class='tooltip-text'>%s</span>" % tooltip_text
    p_map.add_tools(HoverTool(tooltips=tooltips, renderers=[pr]))
    tibet_tooltips = "<span class='tooltip-text'>@name_en (No data)</span>"
    p_map.add_tools(HoverTool(tooltips=tibet_tooltips, renderers=[tr]))

    return p_map
Ejemplo n.º 5
0
def construct_key(palette):
    xdr = Range1d(0, 250)
    ydr = Range1d(0, 50)

    plot = Plot(x_range=xdr,
                y_range=ydr,
                title="",
                plot_width=250,
                plot_height=50,
                min_border=0,
                **PLOT_FORMATS)

    for index, color in enumerate(palette):
        width = 19
        rect = Rect(x=((width * index) + 40),
                    y=40,
                    width=width,
                    height=10,
                    fill_color=color,
                    line_color='white')
        plot.add_glyph(rect)

    zero = Text(x=30, y=15, text=['0 %'], **FONT_PROPS_SM)
    hundred = Text(x=190, y=15, text=['100 %'], **FONT_PROPS_SM)
    plot.add_glyph(zero)
    plot.add_glyph(hundred)

    return plot
Ejemplo n.º 6
0
    def test_ranges_update(self, single_plot_page) -> None:
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        plot = Plot(plot_height=400,
                    plot_width=400,
                    x_range=Range1d(0, 1),
                    y_range=Range1d(0, 1),
                    min_border=0)
        plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
        plot.add_tools(WheelZoomTool())
        code = RECORD("event_name", "cb_obj.event_name", final=False) + \
               RECORD("x0", "cb_obj.x0", final=False) + \
               RECORD("x1", "cb_obj.x1", final=False) + \
               RECORD("y0", "cb_obj.y0", final=False) + \
               RECORD("y1", "cb_obj.y1")
        plot.js_on_event(RangesUpdate, CustomJS(code=code))
        plot.add_tools(CustomAction(callback=CustomJS(code="")))
        plot.toolbar_sticky = False

        page = single_plot_page(plot)

        button = page.get_toolbar_button('wheel-zoom')
        button.click()

        page.driver.execute_script(SCROLL(-200))

        page.click_custom_action()

        results = page.results
        assert results['event_name'] == "rangesupdate"
        assert results['x0'] > 0
        assert results['x1'] < 1
        assert results['y0'] > 0
        assert results['y1'] < 1

        assert page.has_no_console_errors()
Ejemplo n.º 7
0
    def test_glyph_selection_updates_table(self, single_plot_page) -> None:
        plot = Plot(height=800, width=1000)

        data = {'x': [1, 2, 3, 4], 'y': [1, 1, 1, 1]}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x", sortable=True),
            TableColumn(field="y",
                        title="y",
                        sortable=True,
                        editor=NumberEditor())
        ],
                          source=source,
                          editable=True)

        plot.add_glyph(source, Rect(x='x', y='y', width=1.5, height=1))
        plot.add_tools(
            TapTool(callback=CustomJS(
                code=RECORD("indices", "cb_data.source.selected.indices"))))

        page = single_plot_page(column(plot, table))

        page.click_canvas_at_position(500, 400)
        assert set(page.results["indices"]) == {1, 2}

        assert get_table_selected_rows(page.driver) == {1, 2}

        assert page.has_no_console_errors()

        assert page.has_no_console_errors()
Ejemplo n.º 8
0
def test_get_screenshot_as_png_with_glyph():
    layout = Plot(x_range=Range1d(0, 1),
                  y_range=Range1d(0, 1),
                  plot_height=20,
                  plot_width=20,
                  toolbar_location=None,
                  outline_line_color=None,
                  background_fill_color=None,
                  min_border=2,
                  border_fill_color="blue",
                  border_fill_alpha=1)
    glyph = Rect(x="x",
                 y="y",
                 width=2,
                 height=2,
                 fill_color="red",
                 line_color="red")
    source = ColumnDataSource(data=dict(x=[0.5], y=[0.5]))
    layout.add_glyph(source, glyph)

    png = bie.get_screenshot_as_png(layout)
    assert png.size == (20, 20)

    # count 256 red pixels in center area (400 - 20*4 - 16*4)
    data = png.tobytes()
    count = 0
    for x in range(400):
        if data[x * 4:x * 4 + 4] == b"\xff\x00\x00\xff":
            count += 1
    assert count == 256

    assert len(data) == 1600
Ejemplo n.º 9
0
def bokeh_pcolor(p, xedges, yedges, H, color_mapper):
    # Still not great, edges of rectangles do not always touch. I blame bokeh...
    x_list = 0.5 * (xedges[1:] + xedges[:-1])
    y_list = 0.5 * (yedges[1:] + yedges[:-1])
    w_list = xedges[1:] - xedges[:-1]
    h_list = yedges[1:] - yedges[:-1]

    x = np.matlib.repmat(x_list.reshape(1, x_list.size), y_list.size,
                         1).reshape(x_list.size * y_list.size)
    w = np.matlib.repmat(w_list.reshape(1, w_list.size), y_list.size,
                         1).reshape(x_list.size * y_list.size)
    y = np.matlib.repmat(y_list.reshape(y_list.size, 1), 1,
                         x_list.size).reshape(x_list.size * y_list.size)
    h = np.matlib.repmat(h_list.reshape(h_list.size, 1), 1,
                         x_list.size).reshape(x_list.size * y_list.size)
    H = H.reshape(x_list.size * y_list.size)

    source = ColumnDataSource(dict(x=x, y=y, w=w, h=h, H=H))

    #glyph = Rect(x="x", y="y", width="w", height="h", angle=0, fill_color=mapper, line_color=None, dilate=True)
    glyph = Rect(x="x",
                 y="y",
                 width="w",
                 height="h",
                 angle=0,
                 fill_color=color_mapper,
                 line_color=color_mapper,
                 line_width=1)
    p.add_glyph(source, glyph)
Ejemplo n.º 10
0
    def modify_doc(doc):
        source = ColumnDataSource(
            dict(x=[1, 2], y=[1, 1], width=[0.5, 0.5], height=[0.5, 0.5]))
        plot = Plot(height=400,
                    width=400,
                    x_range=Range1d(0, 3),
                    y_range=Range1d(0, 3),
                    min_border=0)
        renderer = plot.add_glyph(
            source, Rect(x='x', y='y', width='width', height='height'))
        tool = BoxEditTool(dimensions='both',
                           num_objects=num_objects,
                           renderers=[renderer])
        plot.add_tools(tool)
        plot.toolbar.active_multi = tool
        div = Div(text='False')

        def cb(attr, old, new):
            if cds_data_almost_equal(new, expected):
                div.text = 'True'

        source.on_change('data', cb)
        code = RECORD("matches", "div.text")
        plot.add_tools(
            CustomAction(callback=CustomJS(args=dict(div=div), code=code)))
        doc.add_root(column(plot, div))
Ejemplo n.º 11
0
def create_decision_tree_graph_renderer(plot, tree):
    """Crea el renderizador del gráfico del árbol de decisión. Para ello se deben especificar configuraciones como: indices o identificadores
    de los nodos, colores de los nodos, tipos de figura de los nodos, tipos de figura de relación entre nodo y las relaciones entre los nodos (inicio y final).

    Parameters:
		plot (Figure): Figura Bokeh donde se muestra el árbol de decisión.
		tree (Tree): Estructura del árbol de decisión a mostrar.

    Returns:
		GraphRenderer: Renderizador del gráfico del árbol de decisión.
    """

    node_indices = [node.id for node in tree.node_list]
    node_colors = [node.color for node in tree.node_list]

    start, end = tree.get_nodes_relations()
    x, y = tree.get_layout_node_positions(plot)
    graph_layout = dict(zip(node_indices, zip(x, y)))

    graph = GraphRenderer()

    graph.node_renderer.data_source.add(node_indices, 'index')
    graph.node_renderer.data_source.add(node_colors, 'color')
    graph.node_renderer.glyph = Rect(height=0.15,
                                     width=0.2,
                                     fill_color='color')
    graph.edge_renderer.glyph = MultiLine(line_color='#b5b8bc',
                                          line_alpha=0.8,
                                          line_width=5)

    graph.edge_renderer.data_source.data = dict(start=start, end=end)

    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    return graph
Ejemplo n.º 12
0
    def make_legend_plot(self, min_idx=0, max_idx=MAX_IDX):
        x_range = Range1d(0, 90)
        y_range = Range1d(0, 295)
        x_range = Range1d(0, 580)
        y_range = Range1d(0, 30)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=580,
                        plot_height=30,
                        min_border=0,
                        **PLOT_FORMATS)

        prices_aves = [
            "67 ", "185", "271", "367", "500", "685", "827", "989", "1242",
            "1354", "1611"
        ]

        text_box.add_glyph(Text(x=2, y=1, text=['Ave:'], **FONT_PROPS_SMALLER))
        text_box.add_glyph(
            Text(x=24, y=1, text=['$' + prices_aves[0]], **FONT_PROPS_SMALLER))
        text_box.add_glyph(
            Rect(x=33,
                 y=22,
                 width=23,
                 height=10,
                 fill_color=Spectral11[0],
                 line_color=None))

        for i in range(1, 11):
            text_box.add_glyph(
                Text(x=(21 + 52 * i),
                     y=1,
                     text=['$' + prices_aves[i]],
                     **FONT_PROPS_SMALLER))
            text_box.add_glyph(
                Rect(x=33 + 52 * i,
                     y=22,
                     width=23,
                     height=10,
                     fill_color=Spectral11[i],
                     line_color=None))

        self.legend_plot = text_box
Ejemplo n.º 13
0
def _make_plot():
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    plot.add_tools(ZoomOutTool())
    code = RECORD("xrstart", "p.x_range.start") + RECORD("xrend", "p.x_range.end") + RECORD("yrstart", "p.y_range.start") + RECORD("yrend", "p.y_range.end")
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(p=plot), code=code)))
    plot.toolbar_sticky = False
    return plot
Ejemplo n.º 14
0
def make_sizing_mode_plot(plot_width, plot_height, sizing_mode='scale_width'):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    plot = Plot(plot_height=plot_height,
                plot_width=plot_width,
                x_range=DataRange1d(),
                y_range=DataRange1d(),
                sizing_mode=sizing_mode)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    return plot
Ejemplo n.º 15
0
def make_responsive_plot(plot_width, plot_height, responsive_mode='width_ar'):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    plot = Plot(plot_height=plot_height,
                plot_width=plot_width,
                x_range=DataRange1d(),
                y_range=DataRange1d(),
                responsive=responsive_mode)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    return plot
Ejemplo n.º 16
0
    def create_legend(self):
        x_range = Range1d(0, 550)
        y_range = Range1d(0, 38)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=680,
                        plot_height=38,
                        min_border=0,
                        **PLOT_FORMATS)

        text_box.add_glyph(
            Text(x=47, y=15, text=['High Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Text(x=423, y=15, text=['Low Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Text(x=235, y=15, text=['Medium Average Rating'], **FONT_PROPS_SM))

        #GREEN
        text_box.add_glyph(
            Rect(x=25,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#41ab5d",
                 line_color=None))
        #YELLOW
        text_box.add_glyph(
            Rect(x=217,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#ffffbf",
                 line_color=None))
        #RED
        text_box.add_glyph(
            Rect(x=402,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#e31a1c",
                 line_color=None))
        self.legend_plot = text_box
Ejemplo n.º 17
0
def make_plot():
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    plot = Plot(plot_height=400,
                plot_width=400,
                x_range=Range1d(0, 1),
                y_range=Range1d(0, 1),
                min_border=0)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    plot.add_tools(WheelZoomTool())
    return plot
Ejemplo n.º 18
0
def _make_plot(dimensions="both", num_objects=0):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], width=[0.5, 0.5], height=[0.5, 0.5]))
    plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0)
    renderer = plot.add_glyph(source, Rect(x='x', y='y', width='width', height='height'))
    tool = BoxEditTool(dimensions=dimensions, num_objects=num_objects, renderers=[renderer])
    plot.add_tools(tool)
    plot.toolbar.active_multi = tool
    code = RECORD("x", "source.data.x") + RECORD("y", "source.data.y") + RECORD("width", "source.data.width") + RECORD("height", "source.data.height")
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(source=source), code=code)))
    plot.toolbar_sticky = False
    return plot
Ejemplo n.º 19
0
def _make_plot():
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    r = Range1d(start=0.4, end=0.6)
    plot = Plot(height=400, width=1100, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    tool = RangeTool(x_range=r)
    plot.add_tools(tool)
    plot.min_border_right = 100
    code = RECORD("start", "t.x_range.start", final=False) + RECORD("end", "t.x_range.end")
    plot.tags.append(CustomJS(name="custom-action", args=dict(t=tool), code=code))
    plot.toolbar_sticky = False
    return plot
Ejemplo n.º 20
0
def _make_plot(tool):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    plot = Plot(height=400, width=450, min_border_right=50, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9))
    plot.add_tools(tool)
    code = RECORD("xrstart", "p.x_range.start", final=False) + \
           RECORD("xrend", "p.x_range.end", final=False) + \
           RECORD("yrstart", "p.y_range.start", final=False) + \
           RECORD("yrend", "p.y_range.end")
    plot.tags.append(CustomJS(name="custom-action", args=dict(p=plot), code=code))
    plot.toolbar_sticky = False
    return plot
Ejemplo n.º 21
0
    def draw(self):
        graph = self.graph
        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        print(node_indices)

        plot = figure(title='Graph Layout Demonstration',
                      x_range=(-7, 7),
                      y_range=(-7, 7),
                      tools='',
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        node_colors = [
            'red', 'blue', 'green', 'yellow', 'black', 'pink', 'purple',
            'white'
        ]
        graph_renderer.node_renderer.data_source.add(node_colors, 'color')
        graph_renderer.node_renderer.glyph = Rect(height=0.1,
                                                  width=0.2,
                                                  fill_color='color')

        graph_renderer.edge_renderer.data_source.data = dict(start=[0] * N,
                                                             end=node_indices)

        d = dict(start=[0] * N, end=node_indices)
        print(d)

        # start of layout code
        # circ = [i*2*math.pi/8 for i in node_indices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]

        x = []
        y = []
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        output_file('graph.html')
        show(plot)
def add_visual_box_select(plot):
    """
    Add a box select tool to your plot which draws a Rect on box select. This can
    be useful for debugging where selenium is hitting the canvas.

    To draw a box, with selenium, you can do something like this:
    ````
        canvas = selenium.find_element_by_tag_name('canvas')

        actions = ActionChains(selenium)
        actions.move_to_element_with_offset(canvas, PLOT_DIM * 0.25, PLOT_DIM * 0.25)
        actions.click_and_hold()
        actions.move_by_offset(PLOT_DIM * 0.5, PLOT_DIM * 0.5)
        actions.release()
        actions.perform()
    ````
    """
    source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
    rect = Rect(x='x',
                y='y',
                width='width',
                height='height',
                fill_alpha=0.3,
                fill_color='#009933')
    callback = CustomJS(args=dict(source=source),
                        code="""
        // get data source from Callback args
        var data = source.data;

        /// get BoxSelectTool dimensions from cb_data parameter of Callback
        var geometry = cb_data['geometry'];

        /// calculate Rect attributes
        var width = geometry['x1'] - geometry['x0'];
        var height = geometry['y1'] - geometry['y0'];
        var x = geometry['x0'] + width/2;
        var y = geometry['y0'] + height/2;

        /// update data source with new Rect attributes
        data['x'].push(x);
        data['y'].push(y);
        data['width'].push(width);
        data['height'].push(height);

        // trigger update of data source
        source.trigger('change');
    """)
    box_select = BoxSelectTool(callback=callback)
    plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
    plot.add_tools(box_select)
    return plot
Ejemplo n.º 23
0
def render_rectangle(dim_mins, dim_maxes):
    x_center = (dim_mins[0] + dim_maxes[0]) / 2.0
    y_center = (dim_mins[1] + dim_maxes[1]) / 2.0
    x_width = dim_maxes[0] - dim_mins[0]
    y_height = dim_maxes[1] - dim_mins[1]
    rect = Rect(x=x_center,
                y=y_center,
                width=x_width,
                height=y_height,
                fill_color=fill_color,
                fill_alpha=fill_alpha,
                line_width=line_width)

    return rect
Ejemplo n.º 24
0
def render(pkg):
    global current_rpm, level, hover, source
    current_rpm = pkg
    hist.append([pkg, level])
    newG = Graph()
    nrn, nre = graphe(pkg, newG)
    if nrn == 0:
        return Div(text="This package is unknown")
    newgraph = from_networkx(newG, spring_layout, scale=4, center=(0, 0))
    newplot = figure(title="RPM network",
                     sizing_mode="scale_width",
                     aspect_ratio=2,
                     x_range=(-2.2, 2.2),
                     y_range=(-2.1, 2.1),
                     tools="tap",
                     toolbar_location=None)
    newplot.axis.visible = False
    newplot.grid.visible = False
    newgraph.node_renderer.glyph = Rect(height=0.07,
                                        width=0.1,
                                        fill_color="color",
                                        fill_alpha=0.0,
                                        line_alpha=0.0)
    if nre != 0:
        newgraph.edge_renderer.glyph = MultiLine(line_color="color",
                                                 line_alpha=0.8)
    newplot.renderers.append(newgraph)
    source = newgraph.node_renderer.data_source
    xcoord = CustomJSTransform(v_func=code % "0",
                               args=dict(provider=newgraph.layout_provider))
    ycoord = CustomJSTransform(v_func=code % "1",
                               args=dict(provider=newgraph.layout_provider))
    source.selected.on_change('indices', selected)
    labels = LabelSet(x=transform('index', xcoord),
                      y=transform('index', ycoord),
                      text='name',
                      text_font_size="12px",
                      y_offset=-6,
                      x_offset="offset",
                      background_fill_color='color',
                      background_fill_alpha=0.85,
                      border_line_color='color',
                      border_line_alpha=1.0,
                      source=source,
                      render_mode='canvas')
    newplot.add_tools(hover)
    newplot.add_layout(labels)
    return newplot
Ejemplo n.º 25
0
def create(G,
           title,
           plot_height=500,
           layout_prog='dot',
           tools=None,
           colorPallete=None):
    '''Creates bokeh figure for Graph with given nodes and attributes
    G = networkX graph
    title = Graph Title
    plot_height = height of plot (default = 500)
    layout_prog = Layout program from Graphviz (default = dot)
    tools = Set of tools to display along with plot (Defalt = All Bokeh tools)
    colorPallette = a list of colors to use for Nodes (Default = sample from viridis)'''

    #Nodes and edges
    node_indices = list(G.nodes)
    edge_start = [x[0] for x in G.edges]
    edge_end = [x[1] for x in G.edges]

    #Assign location using layout program
    pos = nx.nx_pydot.graphviz_layout(G, prog=layout_prog)
    x_coords = [x[0] for x in pos.values()]
    y_coords = [x[1] for x in pos.values()]

    plot = figure(title="Graph Layout Demonstration",
                  x_range=(min(x_coords) - 10, max(x_coords) + 10),
                  y_range=(min(y_coords) - 10, max(y_coords) + 10),
                  tools=tools,
                  plot_height=plot_height)

    graph = GraphRenderer()

    graph.node_renderer.data_source.data = dict(index=node_indices,
                                                fill_color=viridis(
                                                    len(node_indices)))
    graph.node_renderer.glyph = Rect(height=10,
                                     width=10,
                                     fill_color="fill_color")

    graph.edge_renderer.data_source.data = dict(start=edge_start, end=edge_end)

    graph_layout = pos
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    plot.renderers.append(graph)

    return plot
Ejemplo n.º 26
0
 def _rect(self,
           df,
           fill_alpha=CALENDAR_FILL,
           line_alpha=CALENDAR_ALPHA,
           color=CALENDAR_COLOR):
     rect = Rect(x=CALENDAR_X,
                 y=CALENDAR_Y,
                 width=CALENDAR_SIZE,
                 height=CALENDAR_SIZE,
                 fill_color=color,
                 fill_alpha=fill_alpha,
                 line_color=color,
                 line_alpha=line_alpha)
     return self._plot.add_glyph(
         ColumnDataSource(df),
         rect,
         name='with_hover' if df is self._df else None)
Ejemplo n.º 27
0
    def render_sources(self, src_dict):  #todo , **render_kwargs
        tooltips = [('Pos', '$x{int}'), ('Index', '@index'),
                    ('Start', '@start (@_start)'), ('End', '@end (@_end)'),
                    ('Sequence', '@sequence'), ('Score', '@scores'),
                    ('Uptake',
                     '@uptake (@uptake_corrected / @ex_residues, @maxuptake)')]

        for name, data_source in src_dict.items():
            glyph = Rect(x='x',
                         y='y',
                         width='width',
                         height=1,
                         fill_color='color')
            renderer = self.figure.add_glyph(data_source.source, glyph)
            self.renderers[name] = renderer

            hovertool = HoverTool(renderers=[renderer], tooltips=tooltips)
            self.figure.add_tools(hovertool)
Ejemplo n.º 28
0
def plot(source):
    fig = setup_figure()

    # plot data
    rect = Rect(x='dates',
                y='y',
                width='w',
                height='h',
                line_width=0,
                fill_color='colors',
                fill_alpha=1)
    fig.add_glyph(source, rect)

    line = Line(x='dates', y='avg_to_bed_times')
    fig.add_glyph(source, line)
    # circ = Circle(x='dates', y='avg_to_bed_times', size=3)
    # fig.add_glyph(source, circ)
    line = Line(x='dates', y='avg_get_up_times')
    fig.add_glyph(source, line)
    # circ = Circle(x='dates', y='avg_get_up_times', size=3)
    # fig.add_glyph(source, circ)

    # plot select
    select = figure(
        # background_fill_color='#333333'
        title="",
        plot_width=PLOT_WIDTH,
        plot_height=80,
        toolbar_location=None,  # tools="xwheel_pan",
        x_axis_type="datetime",  # y_axis_type=None,
        x_axis_location=None,
        y_axis_location=None,
        y_range=fig.y_range,
    )
    range_tool = RangeTool(x_range=fig.x_range)
    select.add_tools(range_tool)

    select.line(x=[dt(2013, 5, 1), dt.now()], y=[0, 0], color=None)
    select.add_glyph(source, rect)
    select.ygrid.grid_line_color = None
    select.toolbar.active_multi = range_tool
    select.yaxis.ticker = []

    return fig, select
Ejemplo n.º 29
0
def draw_boxes(plt):
    # define two center points
    boxes = ColumnDataSource(data=dict(
        x=[-125.0, 0.0],
        y=[0.0, 0.0],
    ))
    # Create rectangle object of specified width, height, color
    rect = Rect(x="x",
                y="y",
                width=60,
                height=20,
                fill_color="blue",
                fill_alpha=0.5,
                line_color=None)
    # Draw rectangles at the centers specified in 'boxes'
    plt.add_glyph(boxes, rect)

    # Now create another rectangle, this time bypass the Rect class
    plt.rect([0.0], [60.0], width=40, height=20, color="green", alpha=0.5)
 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