コード例 #1
0
 def make_correlation_datatable(correl_df):
     """
     the input datframe must have columns ['Target (as string)', 'Hedge (as string)', 'Correlation ( as float )']
     :param correl_df:
     :return:
     """
     correl_df.reset_index(inplace=True)
     source = ColumnDataSource(correl_df)
     target_ts_asset = sorted(correl_df["Target"].unique())
     hedge_ts_asset = sorted(correl_df["Hedge"].unique())
     columns = [
         TableColumn(field="Target",
                     title="Target Timeseries",
                     formatter=StringFormatter(font_style="bold",
                                               text_color='red')),
         TableColumn(field="Hedge",
                     title="Hedge Timeseries",
                     formatter=StringFormatter(font_style="bold",
                                               text_color='blue')),
         TableColumn(field="Correlation",
                     title="Correlation",
                     formatter=StringFormatter(font_style="bold",
                                               text_color='darkgreen'))
     ]
     data_table = DataTable(source=source,
                            columns=columns,
                            editable=False,
                            width=1000)
     plot = Plot(title=Title(
         text="Correlations, Target vs. Hedge Timeseries)", align="center"),
                 x_range=DataRange1d(),
                 y_range=DataRange1d(),
                 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
     correlation_glyph = Circle(x="index",
                                y="Correlation",
                                fill_color="#396285",
                                size=8,
                                fill_alpha=0.5,
                                line_alpha=0.5)
     target_glyph = Circle(x="index",
                           y="Target",
                           fill_color="#396285",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
     hedge_glyph = Circle(x="index",
                          y="Hedge",
                          fill_color="#396285",
                          size=8,
                          fill_alpha=0.5,
                          line_alpha=0.5)
     correlation = plot.add_glyph(source, correlation_glyph)
     target = plot.add_glyph(source, target_glyph)
     hedge = plot.add_glyph(source, hedge_glyph)
     # Add the tools
     tooltips = [("Correlation", "@Correlation"), ("Target", "@Target"),
                 ("Hedge", "@Hedge")]
     correlation_hover_tool = HoverTool(renderers=[correlation],
                                        tooltips=tooltips)
     target_hover_tool = HoverTool(renderers=[target], tooltips=tooltips)
     hedge_hover_tool = HoverTool(renderers=[hedge], tooltips=tooltips)
     select_tool = BoxSelectTool(renderers=[target, hedge, correlation],
                                 dimensions='width')
     plot.add_tools(target_hover_tool, hedge_hover_tool,
                    correlation_hover_tool, select_tool)
     layout = Column(plot, data_table)
     the_doc = Document()
     the_doc.add_root(layout)
     return the_doc
コード例 #2
0
from bokeh.document import Document
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle,
                          WidgetBox, Row, Button, TapTool)

document = Document()
session = push_session(document)

N = 9

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

source1 = ColumnDataSource(dict(x=x, y=y, size=[20] * 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", size="size", 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", size=20, fill_color="color"))


def on_selection_change1(attr, _, inds):
    color = ["blue"] * N
コード例 #3
0
def create(palm):
    fit_max = 1
    fit_min = 0

    doc = curdoc()

    # THz calibration plot
    scan_plot = Plot(
        title=Title(text="THz calibration"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location="right",
    )

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

    # ---- axes
    scan_plot.add_layout(LinearAxis(axis_label="Stage delay motor"),
                         place="below")
    scan_plot.add_layout(LinearAxis(axis_label="Energy shift, eV",
                                    major_label_orientation="vertical"),
                         place="left")

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

    # ---- circle cluster glyphs
    scan_circle_source = ColumnDataSource(dict(x=[], y=[]))
    scan_plot.add_glyph(scan_circle_source,
                        Circle(x="x", y="y", line_alpha=0, fill_alpha=0.5))

    # ---- circle glyphs
    scan_avg_circle_source = ColumnDataSource(dict(x=[], y=[]))
    scan_plot.add_glyph(
        scan_avg_circle_source,
        Circle(x="x", y="y", line_color="purple", fill_color="purple"))

    # ---- line glyphs
    fit_line_source = ColumnDataSource(dict(x=[], y=[]))
    scan_plot.add_glyph(fit_line_source, Line(x="x",
                                              y="y",
                                              line_color="purple"))

    # THz calibration folder path text input
    def path_textinput_callback(_attr, _old_value, _new_value):
        update_load_dropdown_menu()
        path_periodic_update()

    path_textinput = TextInput(title="THz calibration path:",
                               value=os.path.join(os.path.expanduser("~")),
                               width=510)
    path_textinput.on_change("value", path_textinput_callback)

    # THz calibration eco scans dropdown
    def scans_dropdown_callback(_attr, _old_value, new_value):
        scans_dropdown.label = new_value

    scans_dropdown = Dropdown(label="ECO scans",
                              button_type="default",
                              menu=[])
    scans_dropdown.on_change("value", scans_dropdown_callback)

    # ---- eco scans periodic update
    def path_periodic_update():
        new_menu = []
        if os.path.isdir(path_textinput.value):
            for entry in os.scandir(path_textinput.value):
                if entry.is_file() and entry.name.endswith(".json"):
                    new_menu.append((entry.name, entry.name))
        scans_dropdown.menu = sorted(new_menu, reverse=True)

    doc.add_periodic_callback(path_periodic_update, 5000)

    # Calibrate button
    def calibrate_button_callback():
        palm.calibrate_thz(
            path=os.path.join(path_textinput.value, scans_dropdown.value))
        fit_max_spinner.value = np.ceil(palm.thz_calib_data.index.values.max())
        fit_min_spinner.value = np.floor(
            palm.thz_calib_data.index.values.min())
        update_calibration_plot()

    def update_calibration_plot():
        scan_plot.xaxis.axis_label = f"{palm.thz_motor_name}, {palm.thz_motor_unit}"

        scan_circle_source.data.update(
            x=np.repeat(palm.thz_calib_data.index,
                        palm.thz_calib_data["peak_shift"].apply(len)).tolist(),
            y=np.concatenate(
                palm.thz_calib_data["peak_shift"].values).tolist(),
        )

        scan_avg_circle_source.data.update(
            x=palm.thz_calib_data.index.tolist(),
            y=palm.thz_calib_data["peak_shift_mean"].tolist())

        x = np.linspace(fit_min, fit_max, 100)
        y = palm.thz_slope * x + palm.thz_intersect
        fit_line_source.data.update(x=np.round(x, decimals=5),
                                    y=np.round(y, decimals=5))

        calib_const_div.text = f"""
        thz_slope = {palm.thz_slope}
        """

    calibrate_button = Button(label="Calibrate THz",
                              button_type="default",
                              width=250)
    calibrate_button.on_click(calibrate_button_callback)

    # THz fit maximal value text input
    def fit_max_spinner_callback(_attr, old_value, new_value):
        nonlocal fit_max
        if new_value > fit_min:
            fit_max = new_value
            palm.calibrate_thz(
                path=os.path.join(path_textinput.value, scans_dropdown.value),
                fit_range=(fit_min, fit_max),
            )
            update_calibration_plot()
        else:
            fit_max_spinner.value = old_value

    fit_max_spinner = Spinner(title="Maximal fit value:",
                              value=fit_max,
                              step=0.1)
    fit_max_spinner.on_change("value", fit_max_spinner_callback)

    # THz fit maximal value text input
    def fit_min_spinner_callback(_attr, old_value, new_value):
        nonlocal fit_min
        if new_value < fit_max:
            fit_min = new_value
            palm.calibrate_thz(
                path=os.path.join(path_textinput.value, scans_dropdown.value),
                fit_range=(fit_min, fit_max),
            )
            update_calibration_plot()
        else:
            fit_min_spinner.value = old_value

    fit_min_spinner = Spinner(title="Minimal fit value:",
                              value=fit_min,
                              step=0.1)
    fit_min_spinner.on_change("value", fit_min_spinner_callback)

    # Save calibration button
    def save_button_callback():
        palm.save_thz_calib(path=path_textinput.value)
        update_load_dropdown_menu()

    save_button = Button(label="Save", button_type="default", width=250)
    save_button.on_click(save_button_callback)

    # Load calibration button
    def load_dropdown_callback(_attr, _old_value, new_value):
        palm.load_thz_calib(os.path.join(path_textinput.value, new_value))
        update_calibration_plot()

    def update_load_dropdown_menu():
        new_menu = []
        calib_file_ext = ".palm_thz"
        if os.path.isdir(path_textinput.value):
            for entry in os.scandir(path_textinput.value):
                if entry.is_file() and entry.name.endswith((calib_file_ext)):
                    new_menu.append(
                        (entry.name[:-len(calib_file_ext)], entry.name))
            load_dropdown.button_type = "default"
            load_dropdown.menu = sorted(new_menu, reverse=True)
        else:
            load_dropdown.button_type = "danger"
            load_dropdown.menu = new_menu

    doc.add_next_tick_callback(update_load_dropdown_menu)
    doc.add_periodic_callback(update_load_dropdown_menu, 5000)

    load_dropdown = Dropdown(label="Load", menu=[], width=250)
    load_dropdown.on_change("value", load_dropdown_callback)

    # Calibration constants
    calib_const_div = Div(text=f"""
        thz_slope = {0}
        """)

    # assemble
    tab_layout = column(
        row(
            scan_plot,
            Spacer(width=30),
            column(
                path_textinput,
                scans_dropdown,
                calibrate_button,
                fit_max_spinner,
                fit_min_spinner,
                row(save_button, load_dropdown),
                calib_const_div,
            ),
        ))

    return Panel(child=tab_layout, title="THz Calibration")
コード例 #4
0
def test_lodend_constructor_plot():
    model = Plot()
    event = events.LODEnd(model)
    assert event._model_id == model.id
コード例 #5
0
                          PanTool, WheelZoomTool)
from bokeh.resources import INLINE

x = arange(-2 * pi, 2 * pi, 0.1)
y = sin(x)

# Create an array of times, starting at the current time, and extending
# for len(x) number of hours.
times = np.arange(len(x)) * 3600000 + time.time()

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

xdr = DataRange1d()
ydr = DataRange1d()

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

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

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

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

doc = Document()
doc.add(plot)

if __name__ == "__main__":
    filename = "dateaxis.html"
    with open(filename, "w") as f:
コード例 #6
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)
コード例 #7
0
def test_buttonclick_constructor_plot():
    with pytest.raises(ValueError):
        events.ButtonClick(Plot())
コード例 #8
0
 def test_server_callback_resolve_attr_spec_tap_event(self):
     plot = Plot()
     event = Tap(plot, x=42)
     msg = Callback.resolve_attr_spec('cb_obj.x', event, plot)
     self.assertEqual(msg, {'id': plot.ref['id'], 'value': 42})
コード例 #9
0
def test_setting_logo_on_plot_declaration_sets_them_on_toolbar():
    plot = Plot(logo='grey')
    assert plot.toolbar.logo == 'grey', "Remove this test when deprecation cycle is over"
コード例 #10
0
ファイル: taylor_server.py プロジェクト: zlxs23/bokeh
    plot.title = "%s vs. taylor(%s, n=%d)" % (expr, expr, order)
    legend.legends = [
        ("%s" % expr, [line_f_glyph]),
        ("taylor(%s)" % expr, [line_t_glyph]),
    ]
    source.data = dict(x=x, fy=fy, ty=ty)
    slider.value = order


source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))

xdr = Range1d(-7, 7)
ydr = Range1d(-20, 200)

plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=400)

line_f = Line(x="x", y="fy", line_color="blue", line_width=2)
line_f_glyph = plot.add_glyph(source, line_f)
plot.add_layout(line_f_glyph)

line_t = Line(x="x", y="ty", line_color="red", line_width=2)
line_t_glyph = plot.add_glyph(source, line_t)
plot.add_layout(line_t_glyph)

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

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
コード例 #11
0
ファイル: daylight.py プロジェクト: tommycarpi/py-tracy
d3 = summer_end + (calendar_end - summer_end) / 2

text_source = ColumnDataSource(
    dict(
        dates=[d1, d2, d3],
        times=[dt.time(11, 30)] * 3,
        texts=["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"],
    ))

xdr = DataRange1d()
ydr = DataRange1d()

title = "Daylight Hours - Warsaw, Poland"
plot = Plot(title=title,
            x_range=xdr,
            y_range=ydr,
            plot_width=800,
            plot_height=400)

patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8)
plot.add_glyph(patch1_source, patch1)

patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8)
plot.add_glyph(patch2_source, patch2)

line1 = Line(x="dates", y="sunrises", line_color="yellow", line_width=2)
line1_glyph = plot.add_glyph(source, line1)

line2 = Line(x="dates", y="sunsets", line_color="red", line_width=2)
line2_glyph = plot.add_glyph(source, line2)
コード例 #12
0
ファイル: twin_axis.py プロジェクト: tommycarpi/py-tracy
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models.glyphs import Circle
from bokeh.models import (Plot, LinearAxis, ColumnDataSource, Range1d, PanTool,
                          WheelZoomTool)
from bokeh.resources import INLINE

x = arange(-2 * pi, 2 * pi, 0.1)
y = sin(x)
y2 = linspace(0, 100, len(y))

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

plot = Plot(x_range=Range1d(start=-6.5, end=6.5),
            y_range=Range1d(start=-1.1, end=1.1),
            min_border=80)

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

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

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

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_layout(LinearAxis(y_range_name="foo"), 'left')
コード例 #13
0
nx.draw(G, with_labels=True,
        node_size=nodeSize2,
        node_color='#EFC9AF',
        node_shape='h', #node_shape="d,h,o,p,s,v,x,"
        alpha=0.7, #node transparancy rate out of '1'
        linewidths=4,
        font_size=10,
        font_color='#104C91',
        font_weight='bold',
        width=1,
        edge_color='#1F8AC0'
       )

# -------------------- Setting a Plot option part --------------------

plot = Plot(plot_width=1000, plot_height=750,
            x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2))
plot.title.text = "My Positive Words Graph (hold 'shift' key for multi-clicking)"

plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

# -------------------- Edge adding in Graph part --------------------

popular = dict()
G = nx.DiGraph()
for line in posWordsList:
    words = line.split()
    # adding edge
    G.add_edge(words[0], words[1])
    G.add_edge(words[1], words[2])
    # word-frequency
    for word in words:
コード例 #14
0
    def make_example_datatable():
        source = ColumnDataSource(mpg)
        print(source.column_names)
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        columns = [
            TableColumn(field="manufacturer",
                        title="Manufacturer",
                        editor=SelectEditor(options=manufacturers),
                        formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",
                        title="Model",
                        editor=StringEditor(completions=models)),
            TableColumn(field="displ",
                        title="Displacement",
                        editor=NumberEditor(step=0.1),
                        formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year", title="Year", editor=IntEditor()),
            TableColumn(field="cyl", title="Cylinders", editor=IntEditor()),
            TableColumn(field="trans",
                        title="Transmission",
                        editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",
                        title="Drive",
                        editor=SelectEditor(options=drives)),
            TableColumn(field="class",
                        title="Class",
                        editor=SelectEditor(options=classes)),
            TableColumn(field="cty", title="City MPG", editor=IntEditor()),
            TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()),
        ]
        data_table = DataTable(source=source,
                               columns=columns,
                               editable=True,
                               width=1000)
        plot = Plot(title=None,
                    x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    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")])
        select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width')
        plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)
        layout = Column(plot, data_table)
        doc = Document()
        doc.add_root(layout)
        return doc
コード例 #15
0
    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)
コード例 #16
0
def test_setting_tools_on_plot_declaration_sets_them_on_toolbar():
    pan = PanTool()
    plot = Plot(tools=[pan])
    assert plot.toolbar.tools == [
        pan
    ], "Remove this test when deprecation cycle is over"
コード例 #17
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]
コード例 #18
0
def test_plot_raises_error_if_toolbar_and_logo_are_set():
    with pytest.raises(ValueError):
        Plot(logo='grey', toolbar=Toolbar())
コード例 #19
0
    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()
        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.8,
                 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))

        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>
                """)

        # export = ExportTool()
        # export.register_plot(self.root)

        self.root.add_tools(
            hover,
            # export,
            BoxZoomTool(),
            ResetTool(reset_size=False),
            PanTool(dimensions="width"),
            WheelZoomTool(dimensions="width"))

        # Required for update callback
        self.task_stream_index = [0]
コード例 #20
0
def test_plot_raises_error_if_toolbar_and_tools_are_set():
    with pytest.raises(ValueError):
        Plot(tools=[PanTool()], toolbar=Toolbar())
コード例 #21
0
def test_lodstart_constructor_plot():
    model = Plot()
    event = events.LODStart(model)
    assert event._model_id == model.id
コード例 #22
0
def test_plot_with_no_title_specified_creates_an_empty_title():
    plot = Plot()
    assert plot.title.text == ""
コード例 #23
0
def test_event_constructor_plot():
    model = Plot()
    event = events.Event(model)
    assert event._model_id == model.id
コード例 #24
0
 def verify_axis(self, axis_name):
     plot = Plot()  # no need for setUp()
     range_obj = getattr(plot, 'extra_{}_ranges'.format(axis_name))
     range_obj['foo_range'] = self.get_range_instance()
     self.assertTrue(range_obj['foo_range'])
コード例 #25
0
import numpy as np

from bokeh.io import curdoc, show
from bokeh.models import ColumnDataSource, Grid, InvertedTriangle, LinearAxis, Plot

N = 9
x = np.linspace(-2, 2, N)
y = x**2
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 = InvertedTriangle(x="x",
                         y="y",
                         size="sizes",
                         line_color="#de2d26",
                         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')
コード例 #26
0
ファイル: ImageURL.py プロジェクト: PaulGureghian1/Bokeh
        x1=np.linspace(0, 150, N),
        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(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)

image1 = ImageURL(url="url", x="x1", y="y1", w="w1", h="h1", anchor="center")
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(source, image3)

xaxis = LinearAxis()
コード例 #27
0
from bokeh.models import WheelZoomTool, ResizeTool, PanTool, BoxZoomTool
from bokeh.models import WMTSTileSource

output_file("tile_source_example.html", title="Tile Source Example")

# set to roughly full extent of web mercator projection
x_range = Range1d(start=-20000000, end=20000000)
y_range = Range1d(start=-20000000, end=20000000)

# create tile source from templated url
tile_options = {}
tile_options['url'] = 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png'
tile_source = WMTSTileSource(**tile_options)

# instantiate plot and add tile source
p = Plot(x_range=x_range, y_range=y_range, plot_height=800, plot_width=800)
p.add_tools(ResizeTool(), WheelZoomTool(), PanTool(),
            BoxZoomTool(match_aspect=True))

tile_renderer_options = {}
p.add_tile(tile_source, **tile_renderer_options)

doc = Document()
doc.add_root(p)

if __name__ == "__main__":
    filename = "tile_source.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Tile Source Example"))
    print("Wrote %s" % filename)
    view(filename)
コード例 #28
0
def write_bokeh_graph(data_frame, html_output, project_code):
    df_tp = data_frame.T
    df_tp.index = pd.to_datetime(df_tp.index)
    df_tp.sort_index(inplace=True)
    df_columns_count = df_tp.shape[0]
    df_rows_count = df_tp.shape[1]
    colors = viridis(len(df_tp.columns))

    # option_sets
    hover = HoverTool(tooltips=[("name", "@name"),
                                ("time", "@time"),
                                ("count", "@count"),
                                ]
                      )
    tools_opt = ["resize", hover, "save", "pan", "wheel_zoom", "reset"]
    graph_opt = dict(width=900, x_axis_type="datetime",
                     toolbar_location="left", tools=tools_opt, toolbar_sticky=False,
                     background_fill_alpha=0, border_fill_alpha=0,
                     )
    line_opt = dict(line_width=3, alpha=0.8)
    output_file(html_output, mode="inline")

    legend_items = []

    # figure and line glyphs
    warning_figure = figure(title=project_code + " rvt warnings",
                            **graph_opt,
                            )

    for i, warning_type in enumerate(df_tp.columns):
        # print(f"df_tp.index is: \n{df_tp.index}")
        line_name_dict = [warning_type for _ in range(df_columns_count)]
        cds = ColumnDataSource(data=dict(x=df_tp.index,
                                         y=df_tp[warning_type],
                                         name=line_name_dict,
                                         count=df_tp[warning_type],
                                         time=df_tp.index.strftime("%Y-%m-%d %H:%M:%S"),
                                         )
                               )
        warning_figure.line("x",
                            "y",
                            color=colors[i],
                            name="name",
                            source=cds,
                            **line_opt
                            )
        legend_items.append((warning_type, colors[i]))

    square_size, legend_sq_offset = 20, 20
    legend_plot_height = df_rows_count * (legend_sq_offset + square_size)
    # print(f"plot height is: {legend_plot_height}")

    legend = Plot(plot_width=900,
                  plot_height=legend_plot_height,
                  x_range=Range1d(0, 300),
                  y_range=Range1d(0, legend_plot_height),
                  toolbar_location="left",
                  background_fill_alpha=0,
                  border_fill_alpha=0,
                  outline_line_alpha=0,
                  )

    for i, item in enumerate(legend_items):
        warn_type = item[0]
        color = item[1]

        square_y_pos = legend_plot_height - legend_sq_offset - i * (legend_sq_offset + square_size)

        square = Square(x=square_size,
                        y=square_y_pos,
                        size=square_size,
                        fill_color=color,
                        line_alpha=0,
                        )
        legend.add_glyph(square)

        warning_count_text = str(df_tp[warn_type][-1]).rjust(5)
        warning_text = warn_type

        count_txt = Text(x=square_size + 15,
                         y=square_y_pos,
                         text_align="right",
                         text_baseline="middle",
                         text=[warning_count_text],
                         text_font_size="10pt",
                         )
        legend.add_glyph(count_txt)
        warn_txt = Text(x=square_size + 16,
                        y=square_y_pos,
                        text_align="left",
                        text_baseline="middle",
                        text=[warning_text[:120]],
                        text_font_size="10pt",
                        )
        legend.add_glyph(warn_txt)

    save(column(style_plot(warning_figure), legend))
    print(colorful.bold_green(f" {html_output}\n updated successfully."))
    return df_tp
コード例 #29
0
    ResetTool,
    SaveTool,
    Select,
    Spacer,
    Spinner,
    Title,
    WheelZoomTool,
)

doc = curdoc()
stats = doc.stats
doc.title = f"{doc.title} ROI Projections"

plot = Plot(
    title=Title(text="ROI Projections"),
    x_range=DataRange1d(),
    y_range=DataRange1d(),
    toolbar_location="left",
)

plot.toolbar.logo = None
plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(),
               ResetTool())

plot.add_layout(LinearAxis(), place="below")
plot.add_layout(LinearAxis(), place="left")

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

line_off_source = ColumnDataSource(dict(x=[], y=[]))
line_off = plot.add_glyph(line_off_source,
コード例 #30
0
document = Document()
session = Session()
session.use_doc('linked_tap_server')
session.load_document(document)

N = 9

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

source1 = ColumnDataSource(dict(x=x, y=y, size=[20] * N))
xdr1 = DataRange1d(sources=[source1.columns("x")])
ydr1 = DataRange1d(sources=[source1.columns("y")])
plot1 = Plot(title="Plot1",
             x_range=xdr1,
             y_range=ydr1,
             plot_width=400,
             plot_height=400)
plot1.tools.append(TapTool(plot=plot1))
plot1.add_glyph(source1, Circle(x="x", y="y", size="size", fill_color="red"))
plot1.toolbar_location = None

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