Пример #1
0
def make_plot():
    xdr = DataRange1d()
    ydr = DataRange1d()

    plot = Plot(x_range=xdr, y_range=ydr, plot_width=400, plot_height=400)
    plot.title.text = "Product downloads"

    line = Line(x="dates", y="downloads", line_color="blue")
    plot.add_glyph(source, line)

    circle = Circle(x="dates", y="downloads", fill_color="red")
    plot.add_glyph(source, circle)

    xaxis = DatetimeAxis()
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis()
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    plot.add_tools(HoverTool(tooltips=dict(downloads="@downloads")))

    return plot, source
Пример #2
0
    def test_js_on_change_executes(self, single_plot_page):
        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, Circle(x='x', y='y', size=20))
        text_input = TextInput(css_classes=['foo'])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = single_plot_page(column(text_input, plot))

        el = page.driver.find_element_by_css_selector('.foo input')
        enter_text_in_element(page.driver, el, "val1")

        results = page.results
        assert results['value'] == 'val1'

        # double click to highlight and overwrite old text
        enter_text_in_element(page.driver, el, "val2", click=2)

        results = page.results
        assert results['value'] == 'val2'

        # Check clicking outside input also triggers
        enter_text_in_element(page.driver, el, "val3", click=2, enter=False)
        page.click_canvas_at_position(10, 10)
        results = page.results

        assert results['value'] == 'val3'

        assert page.has_no_console_errors()
Пример #3
0
def make_plot(title, xname, yname):
    plot = Plot(
        x_range=xdr, y_range=ydr,
        title=title, plot_width=400, plot_height=400,
        border_fill='white', background_fill='#e9e0db'
    )

    xaxis = LinearAxis(axis_line_color=None)
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_line_color=None)
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    line = Line(x='x', y='y', line_color="#666699", line_width=2)
    plot.add_glyph(lines_source, line)

    circle = Circle(
        x=xname, y=yname, size=12,
        fill_color="#cc6633", line_color="#cc6633", fill_alpha=0.5
    )
    plot.add_glyph(circles_source, circle)

    return plot
Пример #4
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
Пример #5
0
def test_patches_hover_still_works_when_a_seleciton_is_preselcted(output_file_url, selenium):
    # This tests an edge case interaction when Patches (specifically) is used
    # with a tool that requires hit testing e.g. HitTool AND a selection is
    # pre-made on the data source driving it.
    plot = Plot(
        x_range=Range1d(0, 100),
        y_range=Range1d(0, 100),
        min_border=0
    )
    source = ColumnDataSource(dict(
        xs=[[0, 50, 50, 0], [50, 100, 100, 50]],
        ys=[[0, 0, 100, 100], [0, 0, 100, 100]],
        color=['pink', 'blue']
    ))
    source.selected = {
        '0d': {'glyph': None, 'indices': []},
        '1d': {'indices': [1]},
        '2d': {}
    }
    plot.add_glyph(source, Patches(xs='xs', ys='ys', fill_color='color'))
    plot.add_tools(HoverTool())
    plot.add_layout(LinearAxis(), 'below')
    plot.add_layout(LinearAxis(), 'left')
    save(plot)
    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)

    # Hover plot and test no error
    canvas = selenium.find_element_by_tag_name('canvas')
    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, 100, 100)
    actions.perform()

    # If this assertion fails then there were likely errors on hover
    assert has_no_console_errors(selenium)
Пример #6
0
def pyramid():
    xdr = DataRange1d()
    ydr = DataRange1d()

    plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=600, plot_height=600)

    xaxis = LinearAxis()
    plot.add_layout(xaxis, 'below')
    yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5))
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="#3B8686")
    male_quad_glyph = plot.add_glyph(source_pyramid, male_quad)

    female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="#CFF09E")
    female_quad_glyph = plot.add_glyph(source_pyramid, female_quad)

    plot.add_layout(Legend(items=[
        ("Male"   , [male_quad_glyph]),
        ("Female" , [female_quad_glyph]),
    ]))

    return plot
Пример #7
0
def classical_gear(module, large_teeth, small_teeth):
    xdr = Range1d(start=-300, end=150)
    ydr = Range1d(start=-100, end=100)

    plot = Plot(
        title=None,
        x_range=xdr, y_range=ydr,
        plot_width=800, plot_height=800
    )
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    radius = pitch_radius(module, large_teeth)
    angle = 0
    glyph = Gear(
        x=-radius, y=0,
        module=module, teeth=large_teeth, angle=angle,
        fill_color=fill_color[0], line_color=line_color
    )
    plot.add_glyph(glyph)

    radius = pitch_radius(module, small_teeth)
    angle = half_tooth(small_teeth)
    glyph = Gear(
        x=radius, y=0,
        module=module, teeth=small_teeth, angle=angle,
        fill_color=fill_color[1], line_color=line_color
    )
    plot.add_glyph(glyph)

    return plot
def make_plot(source, xname, yname, line_color, xdr=None, ydr=None, min_border=15, x_axis=True, y_axis=True, responsive=MODE, plot_width=600, plot_height=400):
    """ Returns a tuple (plot, [obj1...objN]); the former can be added
    to a GridPlot, and the latter is added to the plotcontext.
    """
    if not xdr:
        xdr = DataRange1d()
    if not ydr:
        ydr = DataRange1d()

    #title = Title(text='hello world', render_mode='canvas')

    plot = Plot(
        x_range=xdr, y_range=ydr,
        min_border=min_border,
        toolbar_location=None,
        responsive=responsive,
        plot_width=plot_width, plot_height=plot_height,
        title="Plot title",
    )

    if x_axis:
        plot.add_layout(LinearAxis(), 'below')
    if y_axis:
        plot.add_layout(LinearAxis(), 'left')

    plot.add_glyph(source, Line(x=xname, y=yname, line_color=line_color))

    return plot
Пример #9
0
def construct_map(source, fill_string='water_color', selected_color=ORANGE):
    assert isinstance(source, ColumnDataSource), "Require ColumnDataSource"

    # Plot and axes
    x_start, x_end = (-18, 55)
    y_start, y_end = (-35, 38)
    xdr = Range1d(x_start, x_end)
    ydr = Range1d(y_start, y_end)

    aspect_ratio = (x_end - x_start) / (y_end - y_start)
    plot_height = 600
    plot_width = int(plot_height * aspect_ratio)
    plot = Plot(
        x_range=xdr,
        y_range=ydr,
        title="",
        plot_width=plot_width,
        plot_height=plot_height,
        min_border=0,
        **PLOT_FORMATS
    )

    borders = Patches(
        xs='xs', ys='ys',
        fill_color=fill_string, fill_alpha=1,
        line_color="#FFFFFF", line_width=1,
    )
    selected_borders = Patches(
        xs='xs', ys='ys',
        fill_color=fill_string, fill_alpha=1,
        line_color=selected_color, line_width=3,
    )

    plot.add_glyph(source, borders, selection_glyph=selected_borders, nonselection_glyph=borders)  # nopep8
    return plot
Пример #10
0
  def plot(self, job, typename):
    u = utils.utils(job)

    colors = d3["Category20"][20]

    hc = {}
    for i, hostname in enumerate(u.hostnames):
      hc[hostname] = colors[i%20]
    
    plots = []

    schema, _stats  = u.get_type(typename)
    # Plot this type of data
    for index, event in enumerate(schema):
      try:
        plot = Plot(plot_width=400, plot_height=150, 
                    x_range = DataRange1d(), y_range = DataRange1d())                  
        for hostname, stats in _stats.items():               
          rate = stats[:, index]
          if typename == "mem":
            source = ColumnDataSource({"x" : u.hours, "y" : rate})
            plot.add_glyph(source, Step(x = "x", y = "y", mode = "after", 
                                        line_color = hc[hostname]))
          else: 
            rate = numpy.diff(rate)/numpy.diff(job.times)
            source = ColumnDataSource({"x" : u.hours, "y" : numpy.append(rate, rate[-1])})
            plot.add_glyph(source, Step(x = "x", y = "y", mode = "after", 
                                        line_color = hc[hostname]))
        plots += [self.add_axes(plot, event)]
      except:
        print(event + ' plot failed for jobid ' + job.id )
        print(sys.exc_info())
    return gridplot(*plots, ncols = len(plots)//4 + 1, toolbar_options = {"logo" : None})
Пример #11
0
def make_plot(yname, line_color, below_axis=True, left_axis=True, right_axis=False, border_fill_color="white"):
    """ Returns a tuple (plot, [obj1...objN]); the former can be added
    to a GridPlot, and the latter is added to the plotcontext.
    """
    plot = Plot(
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        min_border=15,
        border_fill_color=border_fill_color,
        border_fill_alpha=0.1,
        toolbar_location='above',
        plot_width=300,
        plot_height=300,
        responsive='box'
    )
    if below_axis:
        plot.add_layout(LinearAxis(), 'below')
    else:
        plot.add_layout(LinearAxis(), 'above')
    if left_axis:
        plot.add_layout(LinearAxis(), 'left')
    if right_axis:
        plot.add_layout(LinearAxis(), 'right')
    plot.add_glyph(source, Line(x="x", y=yname, line_color=line_color))
    plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
    return plot
Пример #12
0
def altitude_profile(data):
    plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400)
    plot.x_range = DataRange1d()
    plot.y_range = DataRange1d()

    xaxis = LinearAxis(axis_label="Distance (km)")
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_label="Altitude (m)")
    plot.add_layout(yaxis, 'left')

    xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker)
    ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker)
    plot.renderers.extend([xgrid, ygrid])

    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    X, Y = data.dist, data.alt
    y0 = min(Y)

    patches_source = ColumnDataSource(dict(
        xs=[[X[i], X[i+1], X[i+1], X[i]] for i in range(len(X[:-1])) ],
        ys=[[y0,   y0,     Y[i+1], Y[i]] for i in range(len(Y[:-1])) ],
        color=data.colors[:-1]
    ))
    patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color")
    plot.add_glyph(patches_source, patches)

    line_source = ColumnDataSource(dict(x=data.dist, y=data.alt))
    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    return plot
Пример #13
0
def construct_line(source, value_string, line_color=BLUE):
    xdr = Range1d(1990, 2013)
    ydr = Range1d(0, 100)
    line_plot = Plot(
        x_range=xdr,
        y_range=ydr,
        title="",
        plot_width=250,
        plot_height=150,
        min_border_top=10,
        min_border_left=50,
        **PLOT_FORMATS
    )
    xaxis = LinearAxis(SingleIntervalTicker(interval=50), **AXIS_FORMATS)
    yaxis = LinearAxis(SingleIntervalTicker(interval=10), **AXIS_FORMATS)
    line_plot.add_layout(xaxis, 'left')
    line_plot.add_layout(yaxis, 'below')

    line = Line(
        x='year', y=value_string,
        line_width=5, line_cap="round",
        line_color=line_color,
    )
    line_plot.add_glyph(source, line)

    return line_plot
Пример #14
0
    def __init__(self, **kwargs):
        names = ['processes', 'disk-read', 'cores', 'cpu', 'disk-write',
                 'memory', 'last-seen', 'memory_percent', 'host']
        self.source = ColumnDataSource({k: [] for k in names})

        columns = {name: TableColumn(field=name,
                                     title=name.replace('_percent', ' %'))
                   for name in names}

        cnames = ['host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent']

        formatters = {'cpu': NumberFormatter(format='0.0 %'),
                      'memory_percent': NumberFormatter(format='0.0 %'),
                      'memory': NumberFormatter(format='0 b'),
                      'latency': NumberFormatter(format='0.00000'),
                      'last-seen': NumberFormatter(format='0.000'),
                      'disk-read': NumberFormatter(format='0 b'),
                      'disk-write': NumberFormatter(format='0 b'),
                      'net-send': NumberFormatter(format='0 b'),
                      'net-recv': NumberFormatter(format='0 b')}

        table = DataTable(
            source=self.source, columns=[columns[n] for n in cnames],
        )

        for name in cnames:
            if name in formatters:
                table.columns[cnames.index(name)].formatter = formatters[name]

        mem_plot = Plot(
            title=Title(text="Memory Usage (%)"), toolbar_location=None,
            x_range=Range1d(start=0, end=1), y_range=Range1d(start=-0.1, end=0.1),
            **kwargs
        )

        mem_plot.add_glyph(
            self.source,
            Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5)
        )

        mem_plot.add_layout(LinearAxis(), 'below')

        hover = HoverTool(
            point_policy="follow_mouse",
            tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span>
                </div>
                """
        )
        mem_plot.add_tools(hover, BoxSelectTool())

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        self.root = column(mem_plot, table, id='bk-worker-table', **sizing_mode)
Пример #15
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
Пример #16
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
Пример #17
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
Пример #18
0
 def modify_doc(doc):
     source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
     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, Circle(x='x', y='y', size=20))
     plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
     slider = Slider(start=0, end=10, value=1, title="bar", css_classes=["foo"], width=300)
     def cb(attr, old, new):
         source.data['val'] = [old, new]
     slider.on_change('value', cb)
     doc.add_root(column(slider, plot))
Пример #19
0
 def modify_doc(doc):
     source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
     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, Circle(x='x', y='y', size=20))
     plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
     group = RadioButtonGroup(labels=LABELS, css_classes=["foo"])
     def cb(active):
         source.data['val'] = [active, "b"]
     group.on_click(cb)
     doc.add_root(column(group, plot))
Пример #20
0
 def modify_doc(doc):
     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, Circle(x='x', y='y', size=20))
     plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
     button = Button(css_classes=['foo'])
     def cb(event):
         source.data=dict(x=[10, 20], y=[10, 10])
     button.on_event('button_click', cb)
     doc.add_root(column(button, plot))
Пример #21
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    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, Circle(x='x', y='y', size=20))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    text_input = TextInput(css_classes=["foo"])
    def cb(attr, old, new):
        source.data['val'] = [old, new]
    text_input.on_change('value', cb)
    doc.add_root(column(text_input, plot))
Пример #22
0
def sample_gear():
    xdr = Range1d(start=-30, end=30)
    ydr = Range1d(start=-30, end=30)

    plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=800)
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    glyph = Gear(x=0, y=0, module=5, teeth=8, angle=0, shaft_size=0.2, fill_color=fill_color[2], line_color=line_color)
    plot.add_glyph(glyph)

    return plot
def make_plot(sizing_mode):
    plot = Plot(
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        toolbar_location=None,
        sizing_mode=sizing_mode
    )
    plot.add_glyph(source, Line(x="x", y="y1"))
    plot.add_layout(LinearAxis(), 'below')
    plot.add_layout(LinearAxis(), 'left')
    return plot
def make_figure(axes):
    xdr = Range1d(start=-1, end=1)
    ydr = Range1d(start=-1, end=1)

    plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=200, plot_height=200, toolbar_location=None)
    plot.add_glyph(Circle(x=0, y=0, size=100))

    for place in axes:
        plot.add_layout(LinearAxis(), aliases[place])

    return plot
Пример #25
0
def _make_plot():
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
    r = Range1d(start=0.4, end=0.6)
    plot = Plot(plot_height=400, plot_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") + RECORD("end", "t.x_range.end")
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(t=tool), code=code)))
    plot.toolbar_sticky = False
    return plot
Пример #26
0
def make_plot(xname, yname, xax=False, yax=False, text=None):
    plot = Plot(
        x_range=xdr,
        y_range=ydr,
        background_fill="#efe8e2",
        border_fill="white",
        title="",
        min_border=2,
        h_symmetry=False,
        v_symmetry=False,
        plot_width=250,
        plot_height=250,
    )

    circle = Circle(x=xname, y=yname, fill_color="color", fill_alpha=0.2, size=4, line_color="color")
    r = plot.add_glyph(source, circle)

    xdr.renderers.append(r)
    ydr.renderers.append(r)

    xticker = BasicTicker()
    if xax:
        xaxis = LinearAxis()
        plot.add_layout(xaxis, "below")
        xticker = xaxis.ticker
    plot.add_layout(Grid(dimension=0, ticker=xticker))

    yticker = BasicTicker()
    if yax:
        yaxis = LinearAxis()
        plot.add_layout(yaxis, "left")
        yticker = yaxis.ticker
    plot.add_layout(Grid(dimension=1, ticker=yticker))

    plot.add_tools(PanTool(), WheelZoomTool())

    if text:
        text = " ".join(text.split("_"))
        text = Text(
            x={"field": "xcenter", "units": "screen"},
            y={"field": "ycenter", "units": "screen"},
            text=[text],
            angle=pi / 4,
            text_font_style="bold",
            text_baseline="top",
            text_color="#ffaaaa",
            text_alpha=0.7,
            text_align="center",
            text_font_size="28pt",
        )
        plot.add_glyph(text_source, text)

    return plot
Пример #27
0
def make_plot(location, title_align, two_axes=True):
    plot = Plot(
        plot_width=400, plot_height=200,
        x_range=Range1d(0, 2), y_range=Range1d(0, 2), toolbar_location=None,
        title="Title %s - %s" % (location, title_align), title_location=location,
    )
    plot.title.title_align = title_align
    plot.title.title_padding = 10
    plot.add_glyph(source, Circle(x='x', y='y', radius=0.4))
    plot.add_layout(LinearAxis(), location)
    if two_axes:
        plot.add_layout(LinearAxis(), location)
    return plot
Пример #28
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    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, Circle(x='x', y='y', size=20))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    input_box = AutocompleteInput(css_classes=["foo"])
    input_box.title = "title"
    input_box.value = "400"
    input_box.completions = ["100001", "12344556", "12344557", "3194567289", "209374209374"]
    def cb(attr, old, new):
        source.data['val'] = [old, new]
    input_box.on_change('value', cb)
    doc.add_root(column(input_box, plot))
Пример #29
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    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, Circle(x='x', y='y'))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    spinner = Spinner(low=-1, high=10, step=0.1, value=4, css_classes=["foo"])

    def cb(attr, old, new):
        source.data['val'] = [old, new]

    spinner.on_change('value', cb)
    doc.add_root(column(spinner, plot))
    return doc
def test_no_border_or_background_fill(output_file_url, selenium, screenshot):

    # Have body background-color that should appear through the no-fill plot
    template = Template("""
    <!doctype html>
    <html lang="en">
    <head>
        {{ bokeh_js }}
        {{ bokeh_css}}
        <style>
            body { background-color: lightblue; }
        </style>
    </head>
    <body>
        {{ plot_script }}
        {{ plot_div }}
    </body>
    </html>
    """)

    plot = Plot(plot_height=HEIGHT, plot_width=WIDTH,
                x_range=Range1d(0, 10), y_range=Range1d(0, 10),
                toolbar_location=None)

    # This is the no-fill that we're testing
    plot.background_fill_color = None
    plot.border_fill_color = None

    plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff'))
    plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff'))

    plot.add_layout(LinearAxis(major_label_text_color='#ffffff',
                               major_label_text_font_size="30pt"),
                    'left')
    plot.add_layout(LinearAxis(major_label_text_color='#ffffff',
                               major_label_text_font_size="30pt"),
                    'below')

    html = file_html(plot, INLINE, template=template)

    # filename has to match test function + '.html' light
    filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            "test_no_border_or_background_fill.html")

    with io.open(filepath, "w", encoding="utf-8") as f:
        f.write(decode_utf8(html))

    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)
    screenshot.assert_is_valid()
Пример #31
0
def large_plot():
    source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1]))

    xdr = Range1d(start=0, end=1)
    xdr.tags.append("foo")
    xdr.tags.append("bar")

    ydr = Range1d(start=10, end=20)
    ydr.tags.append("foo")

    plot = Plot(x_range=xdr, y_range=ydr)

    ydr2 = Range1d(start=0, end=100)
    plot.extra_y_ranges = {"liny": ydr2}

    circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black")
    plot.add_glyph(source, circle, name="mycircle")

    line = Line(x="x", y="y")
    plot.add_glyph(source, line, name="myline")

    rect = Rect(x="x", y="y", width=1, height=1, fill_color="green")
    plot.add_glyph(source, rect, name="myrect")

    plot.add_layout(DatetimeAxis(), 'below')
    plot.add_layout(LogAxis(), 'left')
    plot.add_layout(LinearAxis(y_range_name="liny"), 'left')

    plot.add_layout(Grid(dimension=0), 'left')
    plot.add_layout(Grid(dimension=1), 'left')

    plot.add_tools(
        BoxZoomTool(),
        PanTool(),
        PreviewSaveTool(),
        ResetTool(),
        ResizeTool(),
        WheelZoomTool(),
    )

    return plot
Пример #32
0
def epicyclic_gear(module, sun_teeth, planet_teeth):
    xdr = Range1d(start=-150, end=150)
    ydr = Range1d(start=-150, end=150)

    plot = Plot(
    title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300,
    h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

    annulus_teeth = sun_teeth + 2*planet_teeth

    glyph = Gear(
        x=0, y=0,
        module=module, teeth=annulus_teeth, angle=0,
        fill_color=fill_color[0], line_color=line_color, internal=True
    )
    plot.add_glyph(glyph)

    glyph = Gear(
        x=0, y=0,
        module=module, teeth=sun_teeth, angle=0,
        fill_color=fill_color[2], line_color=line_color
    )
    plot.add_glyph(glyph)

    sun_radius = pitch_radius(module, sun_teeth)
    planet_radius = pitch_radius(module, planet_teeth)

    radius = sun_radius + planet_radius
    angle = half_tooth(planet_teeth)

    for i, j in [(+1, 0), (0, +1), (-1, 0), (0, -1)]:
        glyph = Gear(
            x=radius*i, y=radius*j,
            module=module, teeth=planet_teeth, angle=angle,
            fill_color=fill_color[1], line_color=line_color
        )
        plot.add_glyph(glyph)

    return plot
Пример #33
0
Файл: gears.py Проект: xnx/bokeh
def epicyclic_gear(module, sun_teeth, planet_teeth):
    xdr = Range1d(start=-150, end=150)
    ydr = Range1d(start=-150, end=150)

    plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=800)
    plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), UndoTool(), RedoTool(), ResetTool())

    annulus_teeth = sun_teeth + 2*planet_teeth

    glyph = Gear(
        x=0, y=0,
        module=module, teeth=annulus_teeth, angle=0,
        fill_color=fill_color[0], line_color=line_color, internal=True
    )
    plot.add_glyph(glyph)

    glyph = Gear(
        x=0, y=0,
        module=module, teeth=sun_teeth, angle=0,
        fill_color=fill_color[2], line_color=line_color
    )
    plot.add_glyph(glyph)

    sun_radius = pitch_radius(module, sun_teeth)
    planet_radius = pitch_radius(module, planet_teeth)

    radius = sun_radius + planet_radius
    angle = half_tooth(planet_teeth)

    for i, j in [(+1, 0), (0, +1), (-1, 0), (0, -1)]:
        glyph = Gear(
            x=radius*i, y=radius*j,
            module=module, teeth=planet_teeth, angle=angle,
            fill_color=fill_color[1], line_color=line_color
        )
        plot.add_glyph(glyph)

    return plot
Пример #34
0
))

plot = Plot(min_border=0,
            border_fill_color="white",
            plot_width=1300,
            plot_height=700)
plot.title.text = "2009 Unemployment Data"
plot.toolbar_location = None

county_patches = Patches(xs="county_xs",
                         ys="county_ys",
                         fill_color=transform("rate", cmap),
                         fill_alpha=0.7,
                         line_color="white",
                         line_width=0.5)
plot.add_glyph(county_source, county_patches)

state_patches = Patches(xs="state_xs",
                        ys="state_ys",
                        fill_alpha=0.0,
                        line_color="#884444",
                        line_width=2)
plot.add_glyph(state_source, state_patches)

cbar = ColorBar(color_mapper=cmap, location=(0, 0))
plot.add_layout(cbar, 'left')

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
Пример #35
0
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle,
                          WidgetBox, Row, Button, TapTool)

N = 9

x = np.linspace(-2, 2, N)
y = x**2

source1 = ColumnDataSource(dict(x=x, y=y, radius=[0.1] * N))
xdr1 = DataRange1d()
ydr1 = DataRange1d()
plot1 = Plot(x_range=xdr1, y_range=ydr1, plot_width=400, plot_height=400)
plot1.title.text = "Plot1"
plot1.tools.append(TapTool(plot=plot1))
plot1.add_glyph(source1, Circle(x="x",
                                y="y",
                                radius="radius",
                                fill_color="red"))

source2 = ColumnDataSource(dict(x=x, y=y, color=["blue"] * N))
xdr2 = DataRange1d()
ydr2 = DataRange1d()
plot2 = Plot(x_range=xdr2, y_range=ydr2, plot_width=400, plot_height=400)
plot2.title.text = "Plot2"
plot2.tools.append(TapTool(plot=plot2))
plot2.add_glyph(source2, Circle(x="x", y="y", radius=0.1, fill_color="color"))


def on_selection_change1(attr, _, inds):
    color = ["blue"] * N
    if inds['1d']['indices']:
        indices = inds['1d']['indices']
Пример #36
0
    y1  = np.linspace(  0, 150, N),
    w1  = np.linspace( 10,  50, N),
    h1  = np.linspace( 10,  50, N),
    x2  = np.linspace(-50, 150, N),
    y2  = np.linspace(  0, 200, N),
))

xdr = Range1d(start=-100, end=200)
ydr = Range1d(start=-100, end=200)

plot = Plot(x_range=xdr, y_range=ydr)
plot.title.text = "ImageURL"
plot.toolbar_location = None

image1 = ImageURL(url="url", x="x1", y="y1", w="w1", h="h1", anchor="center", global_alpha=0.2)
plot.add_glyph(source, image1)

image2 = ImageURL(url="url", x="x2", y="y2", w=20, h=20, anchor="top_left")
plot.add_glyph(source, image2)

image3 = ImageURL(url=dict(value=url), x=200, y=-100, anchor="bottom_right")
plot.add_glyph(image3)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis,'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
Пример #37
0
# set to roughly extent of points
x_range = Range1d(start=airports['x'].min() - 10000, end=airports['x'].max() + 10000)
y_range = Range1d(start=airports['y'].min() - 10000, end=airports['y'].max() + 10000)

# create plot and add tools
hover_tool = HoverTool(tooltips=[("Name", "@name"), ("Elevation", "@elevation (m)")])
p = Plot(x_range=x_range, y_range=y_range, plot_height=690, plot_width=990, title=title)
p.add_tools(ResizeTool(), WheelZoomTool(), PanTool(), BoxZoomTool(), hover_tool)
p.add_tile(tile_source)

# create point glyphs
point_options = {}
point_options['x'] = 'x'
point_options['y'] = 'y'
point_options['size'] = 9
point_options['fill_color'] = "#60ACA1"
point_options['line_color'] = "#D2C4C1"
point_options['line_width'] = 1.5
points_glyph = Circle(**point_options)
p.add_glyph(points_source, points_glyph)

doc = Document()
doc.add_root(p)

if __name__ == "__main__":
    filename = "airports_map.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Bokeh Airports Example"))
    print("Wrote %s" % filename)
    view(filename)
Пример #38
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)
Пример #39
0
browsers_source = ColumnDataSource(
    dict(
        start=start_angles,
        end=end_angles,
        colors=[colors[browser] for browser in browsers],
    ))

glyph = Wedge(x=0,
              y=0,
              radius=1,
              line_color="white",
              line_width=2,
              start_angle="start",
              end_angle="end",
              fill_color="colors")
plot.add_glyph(browsers_source, glyph)


def polar_to_cartesian(r, start_angles, end_angles):
    cartesian = lambda r, alpha: (r * cos(alpha), r * sin(alpha))
    points = []

    for start, end in zip(start_angles, end_angles):
        points.append(cartesian(r, (end + start) / 2))

    return zip(*points)


first = True

for browser, start_angle, end_angle in zip(browsers, start_angles, end_angles):
Пример #40
0
document = Document()
session = push_session(document)

x = linspace(-6 * pi, 6 * pi, 1000)
y = sin(x)
z = cos(x)

source = ColumnDataSource(data=dict(x=x, y=y, z=z))

plot = Plot(x_range=Range1d(-2 * pi, 2 * pi),
            y_range=DataRange1d(),
            min_border=50)

line_glyph = Line(x="x", y="y", line_color="blue")
plot.add_glyph(source, line_glyph)

line_glyph2 = Line(x="x", y="z", line_color="red")
plot.add_glyph(source, line_glyph2)

plot.add_layout(LinearAxis(), 'below')
plot.add_layout(LinearAxis(), 'left')

plot.add_tools(PanTool(), WheelZoomTool())

document.add_root(plot)
print("\nanimating... press ctrl-C to stop")
session.show(plot)

while True:
    for i in linspace(-2 * pi, 2 * pi, 50):
Пример #41
0
def radialplot(tree, node_color='node_color', node_size='node_size',
               node_alpha='node_alpha', edge_color='edge_color',
               edge_alpha='edge_alpha', edge_width='edge_width',
               hover_var='hover_var', figsize=(500, 500), **kwargs):
    """ Plots unrooted radial tree.

    Parameters
    ----------
    tree : instance of skbio.TreeNode
       Input tree for plotting.
    node_color : str
       Name of variable in `tree` to color nodes.
    node_size : str
       Name of variable in `tree` that specifies the radius of nodes.
    node_alpha : str
       Name of variable in `tree` to specify node transparency.
    edge_color : str
       Name of variable in `tree` to color edges.
    edge_alpha : str
       Name of variable in `tree` to specify edge transparency.
    edge_width : str
       Name of variable in `tree` to specify edge width.
    hover_var : str
       Name of variable in `tree` to display in the hover menu.
    figsize : tuple, int
       Size of resulting figure.  default: (500, 500)
    **kwargs: dict
       Plotting options to pass into bokeh.models.Plot

    Returns
    -------
    bokeh.models.Plot
       Interactive plotting instance.


    Notes
    -----
    This assumes that the tree is strictly bifurcating.

    See also
    --------
    bifurcate
    """
    warnings.warn("This visualization are deprecated.", DeprecationWarning)
    # This entire function was motivated by
    # http://chuckpr.github.io/blog/trees2.html
    t = UnrootedDendrogram.from_tree(tree.copy())

    nodes = t.coords(figsize[0], figsize[1])

    # fill in all of the node attributes
    def _retreive(tree, x, default):
        return pd.Series({n.name: getattr(n, x, default)
                          for n in tree.levelorder()})

    # default node color to light grey
    nodes[node_color] = _retreive(t, node_color, default='#D3D3D3')
    nodes[node_size] = _retreive(t, node_size, default=1)
    nodes[node_alpha] = _retreive(t, node_alpha, default=1)
    nodes[hover_var] = _retreive(t, hover_var, default=None)

    edges = nodes[['child0', 'child1']]
    edges = edges.dropna(subset=['child0', 'child1'])
    edges = edges.unstack()
    edges = pd.DataFrame({'src_node': edges.index.get_level_values(1),
                          'dest_node': edges.values})
    edges['x0'] = [nodes.loc[n].x for n in edges.src_node]
    edges['x1'] = [nodes.loc[n].x for n in edges.dest_node]
    edges['y0'] = [nodes.loc[n].y for n in edges.src_node]
    edges['y1'] = [nodes.loc[n].y for n in edges.dest_node]
    ns = [n.name for n in t.levelorder(include_self=True)]
    attrs = pd.DataFrame(index=ns)

    # default edge color to black
    attrs[edge_color] = _retreive(t, edge_color, default='#000000')
    attrs[edge_width] = _retreive(t, edge_width, default=1)
    attrs[edge_alpha] = _retreive(t, edge_alpha, default=1)

    edges = pd.merge(edges, attrs, left_on='dest_node',
                     right_index=True, how='outer')
    edges = edges.dropna(subset=['src_node'])

    node_glyph = Circle(x="x", y="y",
                        radius=node_size,
                        fill_color=node_color,
                        fill_alpha=node_alpha)

    edge_glyph = Segment(x0="x0", y0="y0",
                         x1="x1", y1="y1",
                         line_color=edge_color,
                         line_alpha=edge_alpha,
                         line_width=edge_width)

    def df2ds(df):
        return ColumnDataSource(ColumnDataSource.from_df(df))

    ydr = DataRange1d(range_padding=0.05)
    xdr = DataRange1d(range_padding=0.05)

    plot = Plot(x_range=xdr, y_range=ydr, **kwargs)
    plot.add_glyph(df2ds(edges), edge_glyph)
    ns = plot.add_glyph(df2ds(nodes), node_glyph)

    tooltip = [
        ("Feature ID", "@index")
    ]
    if hover_var is not None:
        tooltip += [(hover_var, "@" + hover_var)]

    hover = HoverTool(renderers=[ns], tooltips=tooltip)
    plot.add_tools(hover, BoxZoomTool(), ResetTool(),
                   WheelZoomTool(), SaveTool(), PanTool())

    return plot
Пример #42
0
]
data_table = DataTable(source=source, columns=columns, editable=True, width=1000,
                       index_position=-1, index_header="row index", index_width=60)

plot = Plot(title=None, plot_width=1000, plot_height=300)

# Set up x & y axis
plot.add_layout(LinearAxis(), 'below')
yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

# Add Glyphs
cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5)
hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5)
cty = plot.add_glyph(source, cty_glyph)
hwy = plot.add_glyph(source, hwy_glyph)

# Add the tools
tooltips = [
    ("Manufacturer", "@manufacturer"),
    ("Model", "@model"),
    ("Displacement", "@displ"),
    ("Year", "@year"),
    ("Cylinders", "@cyl"),
    ("Transmission", "@trans"),
    ("Drive", "@drv"),
    ("Class", "@class"),
]
cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")])
hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")])
Пример #43
0
def plot_results(fasta, protein_results_dict, outdir, epitope_threshold, epitopes, nonepitopes, fastaheader,
                 predicted_epitopes):
    ######## Plots #########
    print('\nPlotting.')

    ##### progress vars ####
    filecounter = 1
    printlen = 1
    total = str(len(fasta))
    ########################

    for geneid in protein_results_dict:

        ############### progress ###############
        elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - starttime))
        printstring = f'Plotting: {geneid}    File: {filecounter} / {total}   Elapsed time: {elapsed_time}'
        if len(printstring) < printlen:
            print(' ' * printlen, end='\r')
        print(printstring, end='\r')
        printlen = len(printstring)
        filecounter += 1
        #######################################

        # make output dir and create output filename
        if not os.path.exists(outdir + '/plots'):
            os.makedirs(outdir + '/plots')
        out = f'{outdir}/plots/{geneid}.html'
        output_file(out)

        seq = protein_results_dict[geneid].sequence
        pos = protein_results_dict[geneid].positions
        score = protein_results_dict[geneid].score
        protlen = len(seq)

        # create a new plot with a title and axis labels
        p = figure(title=fastaheader[geneid][1:], y_range=(-0.03, 1.03), y_axis_label='Scores', plot_width=1200,
                   plot_height=460, tools='xpan,xwheel_zoom,reset', toolbar_location='above')
        p.min_border_left = 80

        # add a line renderer with legend and line thickness
        l1 = p.line(range(1, protlen + 1), score, line_width=1, color='black', visible=True)
        l2 = p.line(range(1, protlen + 1), ([epitope_threshold] * protlen), line_width=1, color='red', visible=True)

        legend = Legend(items=[('EpiDope', [l1]),
                               ('epitope_threshold', [l2])])

        p.add_layout(legend, 'right')
        p.xaxis.visible = False
        p.legend.click_policy = "hide"

        p.x_range.bounds = (-50, protlen + 51)

        ### plot for sequence
        # symbol based plot stuff

        plot = Plot(title=None, x_range=p.x_range, y_range=Range1d(0, 9), plot_width=1200, plot_height=50, min_border=0,
                    toolbar_location=None)

        y = [1] * protlen
        source = ColumnDataSource(dict(x=list(pos), y=y, text=list(seq)))
        glyph = Text(x="x", y="y", text="text", text_color='black', text_font_size='8pt')
        plot.add_glyph(source, glyph)
        label = Label(x=-80, y=y[1], x_units='screen', y_units='data', text='Sequence', render_mode='css',
                      background_fill_color='white', background_fill_alpha=1.0)
        plot.add_layout(label)

        xaxis = LinearAxis()
        plot.add_layout(xaxis, 'below')
        plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))

        # add predicted epitope boxes
        if predicted_epitopes[geneid]:
            for epi in predicted_epitopes[geneid]:
                start = epi[0]
                end = epi[1]+1
                non_epitope = [-0.02] * (start - 1) + [1.02] * (end-start) + [-0.02] * (
                    (protlen - (start - 1) - (end-start)))
                p.vbar(x=list(pos), bottom=-0.02, top=non_epitope, width=1, alpha=0.2, line_alpha=0,
                       color='darkgreen',
                       legend_label='predicted_epitopes', visible=True)

        # add known epitope boxes
        if epitopes:
            for epi in epitopes:
                hits = [i for i in range(len(seq)) if seq[i:].startswith(epi)]
                if len(hits)>0:
                    for hit in hits:
                        start = hit
                        end = start + len(epi)
                        epitope = [-0.02] * (start) + [1.02] * len(epi) + [-0.02] * ((protlen - (start) - len(epi)))
                        p.vbar(x=list(pos), bottom=-0.02, top=epitope, width=1, alpha=0.2, line_alpha=0, color='blue',
                               legend_label='provided_epitope', visible=True)

        # add non-epitope boxes
        if nonepitopes:
            for epi in nonepitopes:
                hits = [i for i in range(len(seq)) if seq[i:].startswith(epi)]
                if len(hits) > 0:
                    for hit in hits:
                        start = hit
                        end = start + len(epi)
                        non_epitope = [-0.02] * (start) + [1.02] * len(epi) + [-0.02] * (
                            (protlen - (start) - len(epi)))
                        p.vbar(x=list(pos), bottom=-0.02, top=non_epitope, width=1, alpha=0.2, line_alpha=0,
                               color='darkred', legend_label='provided_non_epitope', visible=True)

        column(p, plot)
        save(column(p, plot))
    print()
Пример #44
0
class TaskStream(DashboardComponent):
    """ Task Stream

    The start and stop time of tasks as they occur on each core of the cluster.
    """
    def __init__(self, n_rectangles=1000, clear_interval=20000, **kwargs):
        """
        kwargs are applied to the bokeh.models.plots.Plot constructor
        """
        self.n_rectangles = n_rectangles
        self.clear_interval = clear_interval
        self.last = 0

        self.source = ColumnDataSource(data=dict(start=[],
                                                 duration=[],
                                                 key=[],
                                                 name=[],
                                                 color=[],
                                                 worker=[],
                                                 y=[],
                                                 worker_thread=[],
                                                 alpha=[]))

        x_range = DataRange1d(range_padding=0)
        y_range = DataRange1d(range_padding=0)

        self.root = Plot(title=Title(text="Task Stream"),
                         id='bk-task-stream-plot',
                         x_range=x_range,
                         y_range=y_range,
                         toolbar_location="above",
                         min_border_right=35,
                         **kwargs)

        self.root.add_glyph(
            self.source,
            Rect(x="start",
                 y="y",
                 width="duration",
                 height=0.4,
                 fill_color="color",
                 line_color="color",
                 line_alpha=0.6,
                 fill_alpha="alpha",
                 line_width=3))

        self.root.add_layout(DatetimeAxis(axis_label="Time"), "below")

        ticker = BasicTicker(num_minor_ticks=0)
        self.root.add_layout(
            LinearAxis(axis_label="Worker Core", ticker=ticker), "left")
        self.root.add_layout(
            Grid(dimension=1, grid_line_alpha=0.4, ticker=ticker))

        self.root.yaxis.major_label_text_alpha = 0

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                    <span style="font-size: 12px; font-weight: bold;">@name:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span>
                    <span style="font-size: 10px;">ms</span>&nbsp;
                </div>
                """)

        self.root.add_tools(hover, BoxZoomTool(), ResetTool(reset_size=False),
                            PanTool(dimensions="width"),
                            WheelZoomTool(dimensions="width"))
        if ExportTool:
            export = ExportTool()
            export.register_plot(self.root)
            self.root.add_tools(export)

        # Required for update callback
        self.task_stream_index = [0]

    def update(self, messages):
        with log_errors():
            index = messages['task-events']['index']
            rectangles = messages['task-events']['rectangles']

            if not index or index[-1] == self.task_stream_index[0]:
                return

            ind = bisect(index, self.task_stream_index[0])
            rectangles = {
                k: [v[i] for i in range(ind, len(index))]
                for k, v in rectangles.items()
            }
            self.task_stream_index[0] = index[-1]

            # If there has been a significant delay then clear old rectangles
            if rectangles['start']:
                m = min(map(add, rectangles['start'], rectangles['duration']))
                if m > self.last:
                    self.last, last = m, self.last
                    if m > last + self.clear_interval:
                        self.source.data.update(rectangles)
                        return

            self.source.stream(rectangles, self.n_rectangles)
Пример #45
0
    def __init__(self, **kwargs):
        names = [
            'processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory',
            'last-seen', 'memory_percent', 'host'
        ]
        self.source = ColumnDataSource({k: [] for k in names})

        columns = {
            name: TableColumn(field=name, title=name.replace('_percent', ' %'))
            for name in names
        }

        cnames = [
            'host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent'
        ]

        formatters = {
            'cpu': NumberFormatter(format='0.0 %'),
            'memory_percent': NumberFormatter(format='0.0 %'),
            'memory': NumberFormatter(format='0 b'),
            'latency': NumberFormatter(format='0.00000'),
            'last-seen': NumberFormatter(format='0.000'),
            'disk-read': NumberFormatter(format='0 b'),
            'disk-write': NumberFormatter(format='0 b'),
            'net-send': NumberFormatter(format='0 b'),
            'net-recv': NumberFormatter(format='0 b')
        }

        table = DataTable(
            source=self.source,
            columns=[columns[n] for n in cnames],
        )

        for name in cnames:
            if name in formatters:
                table.columns[cnames.index(name)].formatter = formatters[name]

        mem_plot = Plot(title=Title(text="Memory Usage (%)"),
                        toolbar_location=None,
                        x_range=Range1d(start=0, end=1),
                        y_range=Range1d(start=-0.1, end=0.1),
                        **kwargs)

        mem_plot.add_glyph(
            self.source,
            Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5))

        mem_plot.add_layout(LinearAxis(), 'below')

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span>
                </div>
                """)
        mem_plot.add_tools(hover, BoxSelectTool())

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        self.root = column(mem_plot,
                           table,
                           id='bk-worker-table',
                           **sizing_mode)
Пример #46
0
    def __init__(self, **kwargs):
        self.source = ColumnDataSource(
            data={
                'time': [],
                'cpu': [],
                'memory_percent': [],
                'network-send': [],
                'network-recv': []
            })

        x_range = DataRange1d(follow='end',
                              follow_interval=30000,
                              range_padding=0)

        resource_plot = Plot(x_range=x_range,
                             y_range=Range1d(start=0, end=1),
                             toolbar_location=None,
                             min_border_bottom=10,
                             **kwargs)

        line_opts = dict(line_width=2, line_alpha=0.8)
        g1 = resource_plot.add_glyph(
            self.source,
            Line(x='time',
                 y='memory_percent',
                 line_color="#33a02c",
                 **line_opts))
        g2 = resource_plot.add_glyph(
            self.source,
            Line(x='time', y='cpu', line_color="#1f78b4", **line_opts))

        resource_plot.add_layout(
            LinearAxis(formatter=NumeralTickFormatter(format="0 %")), 'left')

        legend_opts = dict(location='top_left',
                           orientation='horizontal',
                           padding=5,
                           margin=5,
                           label_height=5)

        resource_plot.add_layout(
            Legend(items=[('Memory', [g1]), ('CPU', [g2])], **legend_opts))

        network_plot = Plot(x_range=x_range,
                            y_range=DataRange1d(start=0),
                            toolbar_location=None,
                            **kwargs)
        g1 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-send', line_color="#a6cee3",
                 **line_opts))
        g2 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-recv', line_color="#b2df8a",
                 **line_opts))

        network_plot.add_layout(DatetimeAxis(axis_label="Time"), "below")
        network_plot.add_layout(LinearAxis(axis_label="MB/s"), 'left')
        network_plot.add_layout(
            Legend(items=[('Network Send', [g1]), ('Network Recv', [g2])],
                   **legend_opts))

        tools = [
            PanTool(dimensions='width'),
            WheelZoomTool(dimensions='width'),
            BoxZoomTool(),
            ResetTool()
        ]

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        combo_toolbar = ToolbarBox(tools=tools,
                                   logo=None,
                                   toolbar_location='right',
                                   **sizing_mode)

        self.root = row(column(resource_plot, network_plot, **sizing_mode),
                        column(combo_toolbar, **sizing_mode),
                        id='bk-resource-profiles-plot',
                        **sizing_mode)

        # Required for update callback
        self.resource_index = [0]
Пример #47
0
class TaskProgress(DashboardComponent):
    """ Progress bars per task type """
    def __init__(self, **kwargs):
        data = progress_quads(dict(all={}, memory={}, erred={}, released={}))
        self.source = ColumnDataSource(data=data)

        x_range = DataRange1d()
        y_range = Range1d(-8, 0)

        self.root = Plot(id='bk-task-progress-plot',
                         x_range=x_range,
                         y_range=y_range,
                         toolbar_location=None,
                         **kwargs)
        self.root.add_glyph(
            self.source,
            Quad(top='top',
                 bottom='bottom',
                 left='left',
                 right='right',
                 fill_color="#aaaaaa",
                 line_color="#aaaaaa",
                 fill_alpha=0.2))
        self.root.add_glyph(
            self.source,
            Quad(top='top',
                 bottom='bottom',
                 left='left',
                 right='released-loc',
                 fill_color="color",
                 line_color="color",
                 fill_alpha=0.6))
        self.root.add_glyph(
            self.source,
            Quad(top='top',
                 bottom='bottom',
                 left='released-loc',
                 right='memory-loc',
                 fill_color="color",
                 line_color="color",
                 fill_alpha=1.0))
        self.root.add_glyph(
            self.source,
            Quad(top='top',
                 bottom='bottom',
                 left='erred-loc',
                 right='erred-loc',
                 fill_color='#000000',
                 line_color='#000000',
                 fill_alpha=0.3))
        self.root.add_glyph(
            self.source,
            Text(text='show-name',
                 y='bottom',
                 x='left',
                 x_offset=5,
                 text_font_size=value('10pt')))
        self.root.add_glyph(
            self.source,
            Text(text='done',
                 y='bottom',
                 x='right',
                 x_offset=-5,
                 text_align='right',
                 text_font_size=value('10pt')))

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                    <span style="font-size: 14px; font-weight: bold;">Name:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span>
                </div>
                <div>
                    <span style="font-size: 14px; font-weight: bold;">All:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@all</span>
                </div>
                <div>
                    <span style="font-size: 14px; font-weight: bold;">Memory:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@memory</span>
                </div>
                <div>
                    <span style="font-size: 14px; font-weight: bold;">Erred:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@erred</span>
                </div>
                """)
        self.root.add_tools(hover)

    def update(self, messages):
        with log_errors():
            msg = messages['progress']
            if not msg:
                return
            d = progress_quads(msg)
            self.source.data.update(d)
            if messages['tasks']['deque']:
                self.root.title.text = (
                    "Progress -- total: %(total)s, "
                    "in-memory: %(in-memory)s, processing: %(processing)s, "
                    "waiting: %(waiting)s, failed: %(failed)s" %
                    messages['tasks']['deque'][-1])
Пример #48
0
    axis_line_cap="round",
    axis_line_width=1,
    major_tick_line_width=1,
)

xaxis = LinearAxis(ticker=SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS)
yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS)
plot.add_layout(xaxis, 'below')
plot.add_layout(yaxis, 'left')


# ### Add the background year text
# We add this first so it is below all the other glyphs
text_source = ColumnDataSource({'year': ['%s' % years[0]]})
text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE')
plot.add_glyph(text_source, text)

# Add the circle
color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list)
renderer_source = sources['_%s' % years[0]]
circle_glyph = Circle(
    x='fertility', y='life', size='population',
    fill_color={'field': 'region', 'transform': color_mapper},
    fill_alpha=0.8,
    line_color='#7c7e71', line_width=0.5, line_alpha=0.5)
circle_renderer = plot.add_glyph(renderer_source, circle_glyph)

# Add the hover (only against the circle and not other plot elements)
tooltips = "@index"
plot.add_tools(HoverTool(tooltips=tooltips, renderers=[circle_renderer]))
plot.add_layout(Legend(items=[LegendItem(label=field('region'), renderers=[circle_renderer])]))
Пример #49
0
def construct_text_box(source, value_string, color_string, bar_color):
    # Plot and axes
    xdr = Range1d(0, 220)
    ydr = Range1d(0, 120)

    plot = Plot(x_range=xdr,
                y_range=ydr,
                title="",
                plot_width=250,
                plot_height=120,
                min_border=0,
                **PLOT_FORMATS)
    # Add the writing
    country = Text(x=5, y=50, text='name', **FONT_PROPS_MD)
    percent = Text(x=15,
                   y=10,
                   text=value_string,
                   text_color=color_string,
                   **FONT_PROPS_LG)  # nopep8
    percent_sign = Text(x=69,
                        y=10,
                        text=['%'],
                        text_color=color_string,
                        **FONT_PROPS_LG)  # nopep8
    line_one = Text(x=90, y=28, text=['of people had'], **FONT_PROPS_SM)
    line_two_p1 = Text(x=90, y=14, text=['access in'], **FONT_PROPS_SM)
    line_two_p2 = Text(x=136, y=14, text='year', **FONT_PROPS_SM)
    plot.add_glyph(source, Text(), selection_glyph=country)
    plot.add_glyph(source, Text(), selection_glyph=percent)
    plot.add_glyph(source, Text(), selection_glyph=percent_sign)
    plot.add_glyph(line_one)
    plot.add_glyph(line_two_p1)
    plot.add_glyph(source, Text(), selection_glyph=line_two_p2)

    # Add the orange box with year
    shadow = Triangle(x=150,
                      y=109,
                      size=25,
                      fill_color=ORANGE_SHADOW,
                      line_color=None)  # nopep8
    plot.add_glyph(shadow)
    # Add the blue bar
    rect = Rect(x=75,
                y=99,
                width=150,
                height=5,
                fill_color=bar_color,
                line_color=None)  # nopep8
    plot.add_glyph(rect)
    box = Rect(x=200,
               y=100,
               width=100,
               height=40,
               fill_color=ORANGE,
               line_color=None)  # nopep8
    plot.add_glyph(box)
    year = Text(x=160,
                y=85,
                text='year',
                text_font_size='18pt',
                text_color="#FFFFF",
                text_font_style="bold")  # nopep8
    plot.add_glyph(source, Text(), selection_glyph=year)

    return plot
Пример #50
0
def create(palm):
    connected = False
    current_message = None
    stream_t = 0

    doc = curdoc()

    # Streaked and reference waveforms plot
    waveform_plot = Plot(
        title=Title(text="eTOF waveforms"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    waveform_plot.toolbar.logo = None
    waveform_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                            ResetTool())

    # ---- axes
    waveform_plot.add_layout(LinearAxis(axis_label='Photon energy, eV'),
                             place='below')
    waveform_plot.add_layout(LinearAxis(axis_label='Intensity',
                                        major_label_orientation='vertical'),
                             place='left')

    # ---- grid lines
    waveform_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    waveform_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    waveform_source = ColumnDataSource(
        dict(x_str=[], y_str=[], x_ref=[], y_ref=[]))
    waveform_ref_line = waveform_plot.add_glyph(
        waveform_source, Line(x='x_ref', y='y_ref', line_color='blue'))
    waveform_str_line = waveform_plot.add_glyph(
        waveform_source, Line(x='x_str', y='y_str', line_color='red'))

    # ---- legend
    waveform_plot.add_layout(
        Legend(items=[("reference",
                       [waveform_ref_line]), ("streaked",
                                              [waveform_str_line])]))
    waveform_plot.legend.click_policy = "hide"

    # Cross-correlation plot
    xcorr_plot = Plot(
        title=Title(text="Waveforms cross-correlation"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    xcorr_plot.toolbar.logo = None
    xcorr_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                         ResetTool())

    # ---- axes
    xcorr_plot.add_layout(LinearAxis(axis_label='Energy shift, eV'),
                          place='below')
    xcorr_plot.add_layout(LinearAxis(axis_label='Cross-correlation',
                                     major_label_orientation='vertical'),
                          place='left')

    # ---- grid lines
    xcorr_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    xcorr_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    xcorr_source = ColumnDataSource(dict(lags=[], xcorr=[]))
    xcorr_plot.add_glyph(xcorr_source,
                         Line(x='lags', y='xcorr', line_color='purple'))

    # ---- vertical span
    xcorr_center_span = Span(location=0, dimension='height')
    xcorr_plot.add_layout(xcorr_center_span)

    # Delays plot
    pulse_delay_plot = Plot(
        title=Title(text="Pulse delays"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    pulse_delay_plot.toolbar.logo = None
    pulse_delay_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                               ResetTool())

    # ---- axes
    pulse_delay_plot.add_layout(LinearAxis(axis_label='Pulse number'),
                                place='below')
    pulse_delay_plot.add_layout(
        LinearAxis(axis_label='Pulse delay (uncalib), eV',
                   major_label_orientation='vertical'),
        place='left',
    )

    # ---- grid lines
    pulse_delay_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_delay_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_delay_source = ColumnDataSource(dict(x=[], y=[]))
    pulse_delay_plot.add_glyph(pulse_delay_source,
                               Line(x='x', y='y', line_color='steelblue'))

    # Pulse lengths plot
    pulse_length_plot = Plot(
        title=Title(text="Pulse lengths"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    pulse_length_plot.toolbar.logo = None
    pulse_length_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                                ResetTool())

    # ---- axes
    pulse_length_plot.add_layout(LinearAxis(axis_label='Pulse number'),
                                 place='below')
    pulse_length_plot.add_layout(
        LinearAxis(axis_label='Pulse length (uncalib), eV',
                   major_label_orientation='vertical'),
        place='left',
    )

    # ---- grid lines
    pulse_length_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_length_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_length_source = ColumnDataSource(dict(x=[], y=[]))
    pulse_length_plot.add_glyph(pulse_length_source,
                                Line(x='x', y='y', line_color='steelblue'))

    # Image buffer slider
    def buffer_slider_callback(_attr, _old, new):
        message = receiver.data_buffer[new]
        doc.add_next_tick_callback(partial(update, message=message))

    buffer_slider = Slider(
        start=0,
        end=59,
        value=0,
        step=1,
        title="Buffered Image",
        callback_policy='throttle',
        callback_throttle=500,
    )
    buffer_slider.on_change('value', buffer_slider_callback)

    # Connect toggle button
    def connect_toggle_callback(state):
        nonlocal connected
        if state:
            connected = True
            connect_toggle.label = 'Connecting'
            connect_toggle.button_type = 'default'

        else:
            connected = False
            connect_toggle.label = 'Connect'
            connect_toggle.button_type = 'default'

    connect_toggle = Toggle(label="Connect", button_type='default', width=250)
    connect_toggle.on_click(connect_toggle_callback)

    # Intensity stream reset button
    def reset_button_callback():
        nonlocal stream_t
        stream_t = 1  # keep the latest point in order to prevent full axis reset

    reset_button = Button(label="Reset", button_type='default', width=250)
    reset_button.on_click(reset_button_callback)

    # Stream update coroutine
    async def update(message):
        nonlocal stream_t
        if connected and receiver.state == 'receiving':
            y_ref = message[receiver.reference].value[np.newaxis, :]
            y_str = message[receiver.streaked].value[np.newaxis, :]

            delay, length, debug_data = palm.process({
                '0': y_ref,
                '1': y_str
            },
                                                     debug=True)
            prep_data, lags, corr_res_uncut, _ = debug_data

            waveform_source.data.update(
                x_str=palm.energy_range,
                y_str=prep_data['1'][0, :],
                x_ref=palm.energy_range,
                y_ref=prep_data['0'][0, :],
            )

            xcorr_source.data.update(lags=lags, xcorr=corr_res_uncut[0, :])
            xcorr_center_span.location = delay[0]

            pulse_delay_source.stream({
                'x': [stream_t],
                'y': [delay]
            },
                                      rollover=120)
            pulse_length_source.stream({
                'x': [stream_t],
                'y': [length]
            },
                                       rollover=120)

            stream_t += 1

    # Periodic callback to fetch data from receiver
    async def internal_periodic_callback():
        nonlocal current_message
        if waveform_plot.inner_width is None:
            # wait for the initialization to finish, thus skip this periodic callback
            return

        if connected:
            if receiver.state == 'polling':
                connect_toggle.label = 'Polling'
                connect_toggle.button_type = 'warning'

            elif receiver.state == 'receiving':
                connect_toggle.label = 'Receiving'
                connect_toggle.button_type = 'success'

                # Set slider to the right-most position
                if len(receiver.data_buffer) > 1:
                    buffer_slider.end = len(receiver.data_buffer) - 1
                    buffer_slider.value = len(receiver.data_buffer) - 1

                if receiver.data_buffer:
                    current_message = receiver.data_buffer[-1]

        doc.add_next_tick_callback(partial(update, message=current_message))

    doc.add_periodic_callback(internal_periodic_callback, 1000)

    # assemble
    tab_layout = column(
        row(
            column(waveform_plot, xcorr_plot),
            Spacer(width=30),
            column(buffer_slider, row(connect_toggle, reset_button)),
        ),
        row(pulse_delay_plot, Spacer(width=10), pulse_length_plot),
    )

    return Panel(child=tab_layout, title="Stream")
Пример #51
0
sizes = np.linspace(10, 20, N)

source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))

plot = Plot(title=None,
            plot_width=300,
            plot_height=300,
            min_border=0,
            toolbar_location=None)

glyph = TriangleDot(x="x",
                    y="y",
                    size="sizes",
                    line_color="#99d594",
                    line_width=2,
                    fill_color=None)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)

show(plot)
Пример #52
0
    x_range=xdr,
    y_range=ydr,
    width=1000,
    height=600,
    min_border=0,
    toolbar_location=None,
    background_fill_color='#F0F0F0',
    border_fill_color='lightgray',
)

line_glyph = Line(x="x",
                  y="y",
                  line_color="navy",
                  line_width=2,
                  line_dash="dashed")
line = plot.add_glyph(source, line_glyph)
circle = Circle(x="x",
                y="y2",
                size=6,
                line_color="red",
                fill_color="orange",
                fill_alpha=0.6)
circle = plot.add_glyph(source, circle)

pan = PanTool()
wheel_zoom = WheelZoomTool()
preview_save = SaveTool()

plot.add_tools(pan, wheel_zoom, preview_save)

# Add axes (Note it's important to add these before adding legends in side panels)
Пример #53
0
              tools=[
                  'reset',
                  'save',
                  'hover',
                  'wheel_zoom',
              ],
              y_axis_type="log")  # 'tap'
mean.line('waves', 'deviations', source=deviation_source)
mean.circle('waves', 'proms', color='red', source=deviation_sel_source)
mean.add_layout(span)
# =============================================================================
multi_plot = Plot(plot_width=800,
                  plot_height=400,
                  background_fill_color='silver')
multi_glyph = MultiLine(xs='waves', ys='ys', line_width=2, line_color='label')
multi_plot.add_glyph(spectra_visible_multi, multi_glyph)
xaxis, yaxis = LinearAxis(), LinearAxis()
multi_plot.add_layout(xaxis, 'below')
multi_plot.xaxis.axis_label = 'Wavelength (nm)'
multi_plot.add_layout(yaxis, 'left')
multi_plot.yaxis.axis_label = 'Intensity (CPS)'
multi_plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
multi_plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
multi_plot.add_tools(BoxZoomTool())
multi_plot.add_tools(WheelZoomTool())
multi_plot.add_tools(ResetTool())
multi_plot.add_tools(SaveTool())
multi_plot.add_layout(span)
# =============================================================================
# ~~  Clustering figures
# ~  labeled_materials_image: map image of predicted material labels

# In[ ]:




# ### Add the background year text
# We add this first so it is below all the other glyphs

# In[ ]:

# Add the year in background (add before circle)
text_source = ColumnDataSource({'year': ['%s' % years[0]]})
text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE')
plot.add_glyph(text_source, text)


# ### Add the bubbles and hover
# We add the bubbles using the Circle glyph. We start from the first year of data and that is our source that drives the circles (the other sources will be used later).
# 
# plot.add_glyph returns the renderer, and we pass this to the HoverTool so that hover only happens for the bubbles on the page and not other glyph elements.

# In[ ]:

# Add the circle
renderer_source = sources['_%s' % years[0]]
circle_glyph = Circle(
    x='fertility', y='life', size='population',
    fill_color='region_color', fill_alpha=0.8, 
    line_color='#7c7e71', line_width=0.5, line_alpha=0.5)
Пример #55
0
        colors=list(css3_colors.Color),
    ))

xdr = FactorRange(factors=list(css3_colors.Group.unique()))
ydr = FactorRange(factors=list(reversed(css3_colors.Name)))

plot = Plot(x_range=xdr, y_range=ydr, plot_width=600, plot_height=2000)
plot.title.text = "CSS3 Color Names"

rect = Rect(x="groups",
            y="names",
            width=1,
            height=1,
            fill_color="colors",
            line_color=None)
rect_renderer = plot.add_glyph(source, rect)

xaxis_above = CategoricalAxis(major_label_orientation=pi / 4)
plot.add_layout(xaxis_above, 'above')

xaxis_below = CategoricalAxis(major_label_orientation=pi / 4)
plot.add_layout(xaxis_below, 'below')

plot.add_layout(CategoricalAxis(), 'left')

url = "http://www.colors.commutercreative.com/@names/"
tooltips = """Click the color to go to:<br /><a href="{url}">{url}</a>""".format(
    url=url)

tap = TapTool(plot=plot, renderers=[rect_renderer], callback=OpenURL(url=url))
hover = HoverTool(plot=plot, renderers=[rect_renderer], tooltips=tooltips)
Пример #56
0
plot.extra_y_ranges = {"foo": Range1d(start=0, end=100)}

plot.add_layout(LinearAxis(axis_label="default range"), 'above')
plot.add_layout(LinearAxis(axis_label="qux range", x_range_name="qux"), 'above')

plot.add_layout(LinearAxis(axis_label="default range"), 'below')
plot.add_layout(LinearAxis(axis_label="qux range", x_range_name="qux"), 'below')

plot.add_layout(LinearAxis(axis_label="default range"), 'left')
plot.add_layout(LinearAxis(axis_label="foo range", y_range_name="foo"), 'left')

plot.add_layout(LinearAxis(axis_label="default range"), 'right')
plot.add_layout(LinearAxis(axis_label="foo range", y_range_name="foo"), 'right')

circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black")
plot.add_glyph(source, circle)

circle2 = Circle(x="x", y="y2", fill_color="blue", size=5, line_color="black")
plot.add_glyph(source, circle2, y_range_name="foo")

plot.add_tools(PanTool(), WheelZoomTool())

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
    doc.validate()
    filename = "twin_axis.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Twin Axis Plot"))
    print("Wrote %s" % filename)
Пример #57
0
plot = Plot(title="Speedometer",
            x_range=xdr,
            y_range=ydr,
            plot_width=600,
            plot_height=600)

start_angle = pi + pi / 4
end_angle = -pi / 4

max_kmh = 250
max_mph = max_kmh * 0.621371

major_step, minor_step = 25, 5

plot.add_glyph(
    Circle(x=0, y=0, radius=1.00, fill_color="white", line_color="black"))
plot.add_glyph(
    Circle(x=0, y=0, radius=0.05, fill_color="gray", line_color="black"))

plot.add_glyph(
    Text(x=0,
         y=+0.15,
         text=["km/h"],
         text_color="red",
         text_align="center",
         text_baseline="bottom",
         text_font_style="bold"))
plot.add_glyph(
    Text(x=0,
         y=-0.15,
         text=["mph"],
Пример #58
0
        sepal_width=flowers['sepal_width'],
        color=flowers['color']
    )
)

xdr = DataRange1d()
ydr = DataRange1d()

plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=400)
plot.title.text = "Iris Data"

circle = Circle(
    x="petal_length", y="petal_width", size=10,
    fill_color="color", fill_alpha=0.2, line_color="color"
)
plot.add_glyph(source, circle)

xaxis = LinearAxis(axis_label="petal length", major_tick_in=0)
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis(axis_label="petal width", major_tick_in=0)
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

plot.add_tools(PanTool(), WheelZoomTool())

# Add a caption as a title placed in "below" layout panel.
msg = """The Iris flower data set, or Fisher's Iris data set, is a multivariate data set introduced by Ronald Fisher in his 1936 paper."""
caption = Title(text=msg, align='left', text_font_size='10pt')
Пример #59
0
        (x + 1 * e, y + 1 * e, 1, "blue", "%s01" % n),
        (x + 2 * e, y + 2 * e, 1, "green", "%s02" % n),
        (x + 3 * e, y + 3 * e, 1, "violet", "%s03" % n),
        (x + 4 * e, y + 4 * e, 1, "pink", "%s04" % n),
        (x + 5 * e, y + 5 * e, 1, "black", "%s05" % n),
        (x + 6 * e, y + 6 * e, 1, "gray", "%s06" % n),
        (x + 7 * e, y + 7 * e, 1, "olive", "%s07" % n),
        (x + 8 * e, y + 8 * e, 1, "yellow", "%s08" % n),
        (x + 9 * e, y + 9 * e, 1, "orange", "%s09" % n),
    ]
    f = lambda i: [t[i] for t in d]
    return dict(x=f(0), y=f(1), s=f(2), c=f(3), name=f(4))


ds1 = ColumnDataSource(data=fds(0, 0, 0.1, "c"))
cr1 = plot.add_glyph(
    ds1, Circle(x="x", y="y", radius="s", fill_color="c", line_color="c"))

ds2 = ColumnDataSource(data=fds(-5, 5, 0.5, "d"))
cr2 = plot.add_glyph(
    ds2, Circle(x="x", y="y", radius="s", fill_color="c", line_color="c"))
ln2 = plot.add_glyph(ds2, Line(x="x", y="y", line_width=3, line_color="red"))

ds3 = ColumnDataSource(data=fds(5, 5, 0.0, "e"))
cr3 = plot.add_glyph(
    ds3, Circle(x="x", y="y", radius="s", fill_color="c", line_color="c"))

tooltips = "<b>@name</b> = (@x{0.00}, @y{0.00})"

hover = HoverTool(tooltips=tooltips,
                  renderers=[cr1, cr2, ln2, cr3],
                  point_policy="follow_mouse")
Пример #60
0
class MemoryUse(DashboardComponent):
    """ The memory usage across the cluster, grouped by task type """
    def __init__(self, scheduler, **kwargs):
        self.scheduler = scheduler
        ps = [p for p in scheduler.plugins if isinstance(p, AllProgress)]
        if ps:
            self.plugin = ps[0]
        else:
            self.plugin = AllProgress(scheduler)

        self.source = ColumnDataSource(data=dict(name=[],
                                                 left=[],
                                                 right=[],
                                                 center=[],
                                                 color=[],
                                                 percent=[],
                                                 MB=[],
                                                 text=[]))

        self.root = Plot(id='bk-nbytes-plot',
                         x_range=DataRange1d(),
                         y_range=DataRange1d(),
                         toolbar_location=None,
                         outline_line_color=None,
                         **kwargs)

        self.root.add_glyph(
            self.source,
            Quad(top=1,
                 bottom=0,
                 left='left',
                 right='right',
                 fill_color='color',
                 fill_alpha=1))

        self.root.add_layout(LinearAxis(), 'left')
        self.root.add_layout(LinearAxis(), 'below')

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                    <span style="font-size: 14px; font-weight: bold;">Name:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span>
                </div>
                <div>
                    <span style="font-size: 14px; font-weight: bold;">Percent:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span>
                </div>
                <div>
                    <span style="font-size: 14px; font-weight: bold;">MB:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span>
                </div>
                """)
        self.root.add_tools(hover)

    def update(self):
        with log_errors():
            nb = nbytes_bar(self.plugin.nbytes)
            update(self.source, nb)
            self.root.title.text = \
                "Memory Use: %0.2f MB" % (sum(self.plugin.nbytes.values()) / 1e6)