def modify_document(self, doc): if self.failed: return from types import ModuleType self._module_name = 'bk_script_' + str(uuid.uuid4()).replace('-', '') self._module = ModuleType(self._module_name) self._module.__dict__['__file__'] = abspath(self._path) old_doc = curdoc() set_curdoc(doc) old_io = self._monkeypatch_io() try: exec(self._code, self._module.__dict__) newdoc = curdoc() # script is supposed to edit the doc not replace it if newdoc is not doc: raise RuntimeError("Script at '%s' replaced the output document" % (self._path)) except Exception as e: self._failed = True import traceback self._error_detail = traceback.format_exc() exc_type, exc_value, exc_traceback = sys.exc_info() filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1] self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt) finally: self._unmonkeypatch_io(old_io) set_curdoc(old_doc)
def toggle(): if play.label == '► Play': play.label = '❚❚ Pause' curdoc().add_periodic_callback(self.animate, 50) else: play.label = '► Play' curdoc().remove_periodic_callback(self.animate)
def test_return_type(self): plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users dont' have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) r = bes.components(plot1) assert len(r) == 2 _, divs = bes.components((plot1, plot2)) assert isinstance(divs, tuple) _, divs = bes.components([plot1, plot2]) assert isinstance(divs, tuple) _, divs = bes.components({"Plot 1": plot1, "Plot 2": plot2}) assert isinstance(divs, dict) assert all(isinstance(x, string_types) for x in divs.keys()) _, divs = bes.components(OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)])) assert isinstance(divs, OrderedDict) assert all(isinstance(x, string_types) for x in divs.keys())
def animate(): if button.label == '► Play': button.label = '❚❚ Pause' curdoc().add_periodic_callback(animate_update, 200) else: button.label = '► Play' curdoc().remove_periodic_callback(animate_update)
def animate (): if button.label == 'Start': button.label = 'Stop' curdoc().add_periodic_callback(animate_update, 200) else: button.label = 'Start' curdoc().remove_periodic_callback(animate_update)
def Main(): # parser = argparse.ArgumentParser() # parser.add_argument("-st", dest="stationId", nargs = '*', help="Please provide a list of station Id.") # parser.add_argument("-ct", dest="cityName", nargs = '*', help="Please provide a list of city names corresponding to stations.") # args = parser.parse_args() #city = args.cityName[0] #cities = { # args.cityName[0] : {'ID':args.stationId[0]}, # args.cityName[1] : {'ID':args.stationId[1]}, # args.cityName[2] : {'ID':args.stationId[2]} #} # for c in cities.keys(): global source source = DataSet('St_Johns') plot = make_plot(source, city) city_select.on_change('value', update_plot) # add to document output_file("./Plots/Op5.html", title="Optional Task # 5") save(HBox(city_select, plot)) curdoc().add_root(HBox(city_select, plot))
def modify_document(self, doc): if self.failed: return from types import ModuleType module_name = 'bk_script_' + str(uuid.uuid4()).replace('-', '') module = ModuleType(module_name) module.__dict__['__file__'] = abspath(self._path) # This is to prevent the module from being gc'd before the # document is. A symptom of a gc'd module is that its # globals become None. if not hasattr(doc, '_ScriptHandler__modules'): setattr(doc, '_ScriptHandler__modules', []) doc.__modules.append(module) old_doc = curdoc() set_curdoc(doc) old_io = self._monkeypatch_io() try: exec(self._code, module.__dict__) newdoc = curdoc() # script is supposed to edit the doc not replace it if newdoc is not doc: raise RuntimeError("Script at '%s' replaced the output document" % (self._path)) except Exception as e: self._failed = True import traceback self._error_detail = traceback.format_exc() exc_type, exc_value, exc_traceback = sys.exc_info() filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1] self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt) finally: self._unmonkeypatch_io(old_io) set_curdoc(old_doc)
def main(options, args): #logger = log.get_logger("ginga", options=options) logger = log.get_logger("ginga", level=20, log_file="/tmp/ginga.log") #TOOLS = "pan,wheel_zoom,box_select,tap" TOOLS = "box_select" # create a new plot with default tools, using figure fig = figure(x_range=[0, 600], y_range=[0, 600], plot_width=600, plot_height=600, tools=TOOLS) viewer = ib.CanvasView(logger) viewer.set_figure(fig) bd = viewer.get_bindings() bd.enable_all(True) ## box_select_tool = fig.select(dict(type=BoxSelectTool)) ## box_select_tool.select_every_mousemove = True #tap_tool = fig.select_one(TapTool).renderers = [cr] # open a session to keep our local document in sync with server #session = push_session(curdoc()) #curdoc().add_periodic_callback(update, 50) def load_file(path): image = load_data(path, logger=logger) viewer.set_image(image) def load_file_cb(attr_name, old_val, new_val): #print(attr_name, old_val, new_val) load_file(new_val) def zoom_ctl_cb(attr_name, old_val, new_val): if new_val >= 0: new_val += 2 viewer.zoom_to(int(new_val)) scale = viewer.get_scale() logger.info("%f" % scale) viewer.onscreen_message("%f" % (scale), delay=0.3) # add a entry widget and configure with the call back #dstdir = options.indir dstdir = "" path_w = TextInput(value=dstdir, title="File:") path_w.on_change('value', load_file_cb) slide = Slider(start=-20, end=20, step=1, value=1) slide.on_change('value', zoom_ctl_cb) layout = column(fig, path_w, slide) curdoc().add_root(layout) if len(args) > 0: load_file(args[0])
def main(): # example input: # bokeh serve # python3 waggle_dash/main.py --date 2016-07-29 --id ub_3 ub_4 parser = argparse.ArgumentParser(description='Plot Beehive data using Bokeh') parser.add_argument('-dates', metavar='dates', type=str, nargs='+', help='The dates for which the data will be retrieved') parser.add_argument('-id', metavar='id', type=str, nargs='+', help='The node IDs') parser.add_argument('-row_first', metavar='row_first', type=int, nargs='?', default = 0, help='maximum number of rows of data to load') parser.add_argument('-row_last', metavar='row_last', type=int, nargs='?', default = -1, help='maximum number of rows of data to load') parser.add_argument('-csv_out', type=str, nargs='?', help='the csv file to which the data is saved.') args = parser.parse_args() # node_ids = {'ub_1': '0000001e06107d6b', # 'ub_2': '0000001e06107e4c', # 'ub_3': '0000001e06107d7f', # 'ub_4': '0000001e06107cc5' # # 'ub_5':'0000001e06107cdc' # } print(args) #nodes = {'ub_3': '0000001e06107d7f', 'ub_4': '0000001e06107cc5'} dates = args.dates # '2016-07-29' node_ids = args.id print(dates) print('row_first = ', args.row_first) print('row_last = ', args.row_last) data = load_data(node_ids, dates, row0 = args.row_first, row1 = args.row_last) if bDebug: print('data: ', data) if (args.csv_out): store_csv(data, args.csv_out) else: sensor_names, data_types = compute_params(data) if False: sensor_names = {'Temperature': ['TSYS01', 'TMP112', 'BMP180', 'TMP421', 'HIH6130', 'HTU21D'], 'Humidity': ['HTU21D', 'HIH6130'], 'Concentration': ['Nitrogen Di-oxide (NO2)', 'Carbon Monoxide (C0)','Hydrogen Sulphide (H2S)', 'Sulfur Dioxide (SO2)']} data_types = ['Temperature', 'Humidity', 'Concentration'] # sensor_names = {'Temperature': ['TSYS01']} # data_types = ['Temperature'] panels = init_panels(data, sensor_names, data_types, dates, node_ids[0]) tabs = Tabs(tabs=[panels[dtype] for dtype in data_types]) #panels4 = init_panels(data, sensor_names, data_types, dates, node_ids['ub_4']) #tabs4 = Tabs(tabs=[panels4[dtype] for dtype in data_types]) # lo = layout([[tabs4]], sizing_mode='stretch_both') #lo = layout(tabs, sizing_mode='stretch_both') session = push_session(curdoc()) curdoc().add_root(tabs) session.show(tabs) session.loop_until_closed()
def test_single_model_with_no_document(self): p = Model() assert p.document is None with beu.OutputDocumentFor([p], apply_theme=beu.FromCurdoc): assert p.document is not None assert p.document.theme is curdoc().theme new_doc = p.document assert p.document is new_doc assert p.document.theme is not curdoc().theme
def dataurl_change(attr, old, new): if new != "DEMO": try: source_url.data = requests.get(new).json() inputs = VBoxForm(text, threshold, dataurl) curdoc().remove_root(plot) curdoc().add_root(HBox(inputs, plot, width=800)) except: logging.warn("unable to fetch {}".format(new)) update_data()
def UpdatePlot(source, source1): data_table.source=source1 plotClusters(source, p) #set callbacks #sliders[0].callback = cb.callbackMin(source) #sliders[1].callback = cb.callbackMax(source) #taptool.callback = cb.callbackTap(source) curdoc().add(vbox) #session = push_session(curdoc()) #session.show(vbox) show(curdoc())
def exg(source): if source.endswith('.bin'): data_dir, data_list = get_mock_data_list() source = os.path.join(data_dir, source) print('Loading data...', end='', flush=True) with open(source, 'rb') as fd: buff = bytearray(fd.read()) serial_obj = FakeSerialByteArray(buff) print('Done.', flush=True) else: serial_obj = serial.Serial(source, baudrate=DEFAULT_BAUDRATE) reader = PacketStreamReader(serial_obj) new_data_gen = get_new_data_points(reader) p = figure( x_range=(0, 1024), y_range=(0, 1024), plot_width=1024, plot_height=400, tools='save', toolbar_location='below', ) p.axis.visible = False p.xgrid.visible = False line = p.line( x=tuple(range(1024)), y=tuple(512 for _ in range(1024)) ) ds = line.data_source def update(): data = next(new_data_gen) new_y = tuple(ds.data['y']) + tuple(data) new_y = new_y[-1024:] new_x = tuple(range(len(new_y))) ds.data.update(x=new_x, y=new_y) curdoc().add_periodic_callback(update, 30) # open a session to keep our local document in sync with server session = push_session(curdoc()) session.show(p) # open the document in a browser try: session.loop_until_closed() # run forever finally: serial_obj.close()
def modify_document(self, doc): curdoc().clear() # doc = curdoc() try: curdoc().remove_periodic_callback(self._pcb) except: pass doc.clear() self.build_plot() layout = gridplot(self.plots, ncols=2) doc.add_root(layout) self._pcb = doc.add_periodic_callback(self.update_data, 10000) return doc
def main(): # list all plots # put in a selector by name # when selected, load that module # join output of that module to curdoc() print(sys.path[:3]) import gliderops import gliderops.plots print(dir(gliderops.plots)) import gliderops.plots.plot_timeseries as plot_timeseries plot_this = plot_timeseries.plot() master_layout = hplot(plot_this) curdoc().add_root(master_layout)
def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs): """ Given a HoloViews Viewable return a corresponding plot instance. Allows supplying a document attach the plot to, useful when combining the bokeh model with another plot. """ if doc is None: doc = Document() if self_or_cls.notebook_context else curdoc() if self_or_cls.notebook_context: curdoc().theme = self_or_cls.theme doc.theme = self_or_cls.theme plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer, **kwargs) plot.document = doc return plot
def test_patch_notification(self): d = document.Document() assert not d.roots m = ColumnDataSource(data=dict(a=[10,11], b=[20,21])) d.add_root(m) assert len(d.roots) == 1 assert curdoc() is not d events = [] curdoc_from_listener = [] def listener(event): curdoc_from_listener.append(curdoc()) events.append(event) d.on_change(listener) m.patch(dict(a=[(0, 1)], b=[(0,0), (1,1)])) assert events event = events[0] assert isinstance(event, ModelChangedEvent) assert isinstance(event.hint, ColumnsPatchedEvent) assert event.document == d assert event.model == m assert event.hint.column_source == m assert event.hint.patches == dict(a=[(0, 1)], b=[(0,0), (1,1)]) assert event.attr == 'data' # old == new because stream events update in-place assert event.old == dict(a=[1, 11], b=[0, 1]) assert event.new == dict(a=[1, 11], b=[0, 1]) assert len(curdoc_from_listener) == 1 assert curdoc_from_listener[0] is d
def modify_document(self, doc): if self.failed: return module = self._runner.new_module() # This is to prevent the module from being gc'd before the # document is. A symptom of a gc'd module is that its # globals become None. if not hasattr(doc, '_CodeHandler__modules'): setattr(doc, '_CodeHandler__modules', []) doc.__modules.append(module) old_doc = curdoc() set_curdoc(doc) old_io = self._monkeypatch_io() try: def post_check(): newdoc = curdoc() # script is supposed to edit the doc not replace it if newdoc is not doc: raise RuntimeError("%s at '%s' replaced the output document" % (self._origin, self._runner.path)) self._runner.run(module, post_check) finally: self._unmonkeypatch_io(old_io) set_curdoc(old_doc)
def test_other_attrs_raise(): d = locking.UnlockedDocumentProxy(Document()) assert curdoc() is not d for attr in (set(dir(d._doc)) - set(dir(d))) | {'foo'}: with pytest.raises(RuntimeError) as e: getattr(d, attr) assert e.value.args[0] == locking.UNSAFE_DOC_ATTR_USAGE_MSG
def range_column_filter(colname, stepsize, title=None): """Create a column filter, if the column exists and contains at least one\ not-None value. Creates the slider for the filter and returns a getter\ for the slider's current range""" if colname in entries[0]: column_data = [entry[colname] for entry in entries] if validate_column(column_data, colname): top = stepUp(max((val for val in column_data if val is not None)), stepsize) col_filter = RangeSlider( title = cols[colname] if title is None else title, range=(0, top), start = 0, end = top, step=stepsize ) getter = lambda :col_filter.range col_filter.on_change( 'range', lambda a,r,g: debounce( update, getter, 150, curdoc() ) ) widgets.append(col_filter) return getter
def test__trigger_event_wraps_curdoc(self): # This test is pretty clunky by assures that callbacks triggered by # events use the correct value of curdoc() from bokeh.io.doc import set_curdoc from bokeh.io import curdoc oldcd = curdoc() d1 = Document() d2 = Document() set_curdoc(d1) out = {} def cb(): out['curdoc'] = curdoc() m = cbm.EventCallbackManager() m.subscribed_events = [] m.on_event('foo', cb) m.id = 10 m._document = d2 assert len(m._event_callbacks) == 1 assert m._event_callbacks['foo'] == [cb] class ev(object): _model_id = 10 event_name = "foo" m._trigger_event(ev()) assert out['curdoc'] is d2 set_curdoc(oldcd)
def test_stream_notification(self): d = document.Document() assert not d.roots m = ColumnDataSource(data=dict(a=[10], b=[20])) d.add_root(m) assert len(d.roots) == 1 assert curdoc() is not d events = [] curdoc_from_listener = [] def listener(event): curdoc_from_listener.append(curdoc()) events.append(event) d.on_change(listener) m.stream(dict(a=[11, 12], b=[21, 22]), 200) assert events event = events[0] assert isinstance(event, ModelChangedEvent) assert isinstance(event.hint, ColumnsStreamedEvent) assert event.document == d assert event.model == m assert event.hint.column_source == m assert event.hint.data == dict(a=[11, 12], b=[21, 22]) assert event.hint.rollover == 200 assert event.attr == 'data' # old == new because stream events update in-place assert event.old == dict(a=[10, 11, 12], b=[20, 21, 22]) assert event.new == dict(a=[10, 11, 12], b=[20, 21, 22]) assert len(curdoc_from_listener) == 1 assert curdoc_from_listener[0] is d
def test_change_notification(self): d = document.Document() assert not d.roots m = AnotherModelInTestDocument() d.add_root(m) assert len(d.roots) == 1 assert m.bar == 1 assert curdoc() is not d events = [] curdoc_from_listener = [] def listener(event): curdoc_from_listener.append(curdoc()) events.append(event) d.on_change(listener) m.bar = 42 assert events event = events[0] assert isinstance(event, ModelChangedEvent) assert event.document == d assert event.model == m assert event.attr == 'bar' assert event.old == 1 assert event.new == 42 assert len(curdoc_from_listener) == 1 assert curdoc_from_listener[0] is d
def main(): N = 200 xs = np.linspace(0, 4*np.pi, N) ys = np.sin(xs) viewer=BokehViewer(xs,ys) document=curdoc() document.add_root(viewer.plot)
def serve(host='localhost', port=5006, session_id='test'): url = 'http://' + host + ':' + str(port) + '/' session = push_session(curdoc(), session_id=session_id, url=url) session.show() return session
def modify_document(self, doc): if self.failed: return module = self._runner.new_module() # One reason modules are stored is to prevent the module # from being gc'd before the document is. A symptom of a # gc'd module is that its globals become None. Additionally # stored modules are used to provide correct paths to # custom models resolver. sys.modules[module.__name__] = module doc._modules.append(module) old_doc = curdoc() set_curdoc(doc) old_io = self._monkeypatch_io() try: def post_check(): newdoc = curdoc() # script is supposed to edit the doc not replace it if newdoc is not doc: raise RuntimeError("%s at '%s' replaced the output document" % (self._origin, self._runner.path)) self._runner.run(module, post_check) finally: self._unmonkeypatch_io(old_io) set_curdoc(old_doc)
def update_data(self): controller = self.network.notes[0] notes_df = pd.DataFrame(self.network.notes[1]).reset_index() notes_df.columns = ["index", "notes"] notes = ColumnDataSource(notes_df) self.data_table.source.data.update(notes.data) curdoc().title = "Notes for %s" % controller
def _with_self_as_curdoc(self, f): from bokeh.io import set_curdoc, curdoc old_doc = curdoc() try: set_curdoc(self) f() finally: set_curdoc(old_doc)
def main(): import imageio imageio.imwrite("black.png", 10 * np.ones((100, 200, 3)).astype(np.uint8)) imageio.imwrite("gray.png", 128 * np.ones((400, 100, 3)).astype(np.uint8)) imageio.imwrite("white.png", 240 * np.ones((100, 10, 3)).astype(np.uint8)) document = curdoc() viewer = DataViewer() document.add_root(viewer.plot)
def test_with_request(self, mock_request, mock_logger): mock_request.bokeh_server_document = "FOO" self.assertEqual(io.curdoc(), "FOO") self.assertTrue(io.logger.debug.called) self.assertEqual( io.logger.debug.call_args[0], ("curdoc() returning Document from flask request context",) )
* Add the color mapper to the circle glyph as a dictionary with dict(field='region', transform=color_mapper) as the argument passed to the color parameter of plot.circle(). Also set the legend parameter to be the 'region'. * Set the legend.location attribute of plot to 'top_right'. ''' # Make a list of the unique values from the region column: regions_list regions_list = data.region.unique().tolist() # Import CategoricalColorMapper from bokeh.models and the Spectral6 palette from bokeh.palettes from bokeh.models import CategoricalColorMapper from bokeh.palettes import Spectral6 # Make a color mapper: color_mapper color_mapper = CategoricalColorMapper(factors=regions_list, palette=Spectral6) # Add the color mapper to the circle glyph plot.circle(x='x', y='y', fill_alpha=0.8, source=source, color=dict(field='region', transform=color_mapper), legend='region') # Set the legend.location attribute of the plot to 'top_right' plot.legend.location = 'top_right' # Add the plot to the current document and add the title curdoc().add_root(plot) curdoc().title = 'Gapminder' # To start bokeh server run this command in the current folder # bokeh serve --show 03-enhancing-the-plot-with-some-shading.py
source.data = dict( x=df[x_name], y=df[y_name], color=df["color"], title=df["Title"], year=df["Year"], revenue=df["revenue"], alpha=df["alpha"], ) controls = [ reviews, boxoffice, genre, min_year, max_year, oscars, director, cast, x_axis, y_axis ] for control in controls: control.on_change('value', lambda attr, old, new: update()) sizing_mode = 'fixed' # 'scale_width' also looks nice with this example inputs = widgetbox(*controls, sizing_mode=sizing_mode) l = layout([ [desc], [inputs, p], ], sizing_mode=sizing_mode) update() # initial load of the data curdoc().add_root(l) curdoc().title = "Movies"
# stats.text = str(data[[t1, t2]].describe()) stats.text = statsText(data, t1, t2) ticker1.on_change('value', ticker1_change) ticker2.on_change('value', ticker2_change) def selection_change(attrname, old, new): t1, t2 = ticker1.value, ticker2.value selected = source.selected['1d']['indices'] if selected: data = dict(date=t[selected], t1=signal[selected, signalIndices[t1]], t2=signal[selected, signalIndices[t2]]) update_stats(data, t1, t2) source.on_change('selected', selection_change) # set up layout widgets = column(ticker1, ticker2, stats) main_row = row(corr, widgets, reduced) if predux else row(corr, widgets) series = column(ts1, ts2) layout = column(main_row, series) # initialize update() curdoc().add_root(layout) curdoc().title = sys.argv[1]
x_units='data', y_units='data', text='Goal=$12.5K') p.add_layout(goal) p.add_layout(span_label) else: p.xaxis.major_label_orientation = radians(60) p.sizing_mode = 'scale_width' return p #create updated func: def update(attr, old, new): layout.children[1] = create_figure(total_sales) layout.children[1].sizing_mode = 'scale_width' select_options = [('Pack', 'Pack'), ('Den', 'Den'), ('Rank', 'Scout Rank')] select = Select(title="Aggregate By:", value='Pack', options=select_options) select.on_change('value', update) controls = widgetbox([select], width=200) layout = column(controls, create_figure(total_sales), sizing_mode='scale_width') curdoc().add_root(layout) curdoc().title = "Popcorn Sales"
tableWaterY.append(str(round(sum(water) * 365, 2)) + " L") tableName.append(place.location) tableSpace.append(str(round((dims[0] * dims[1] * dims[2]), 2)) + " m^3") tableTime.append(place.time) sourceTable.data = dict(name=tableName, time=tableTime, Year_Price=tablePriceY, Day_Price=tablePriceD, Day_Water=tableWaterD, Year_Water=tableWaterY, space=tableSpace) updates = [ location_select, time_select, select_material, slide_length, slide_height, slide_width, slide_thick, slide_desired_temp ] for u in updates: u.on_change('value', update_data) calculate_button.on_click(button_updates) widgets = column(location_select, time_select, select_material, slide_length, slide_height, slide_width, slide_thick, slide_desired_temp, calculate_button, data_table) graphs = column(row(diff_temps, hourly_temps), row(g1, g3)) curdoc().add_root(row(widgets, graphs)) curdoc().title = "Heat Transfer and Cost for ZECC Model"
'sum': '%dM', 'amax': '%dk' } data = [ ('Number of Projects', 'Total projects', 'counts', 'len'), ('Most Expensive Project', 'Max cost', 'cost', 'amax'), ('Total Project Cost', 'Total project cost', 'cost', 'sum'), ('Mean Project Cost', 'Median project cost', 'cost', 'mean') ] do_update() plots = [ make_plot(src, *args) for args in data ] # Create a row layout lyt = layout([controls, plots[3]], plots[0:3]) # Make a tab with the layout tab = Panel(child=lyt, title = 'Histogram') tabs = Tabs(tabs=[tab]) doc.add_periodic_callback(time_update, 1000) doc.add_root(tabs) # Set up an application #handler = FunctionHandler(modify_doc) #app = Application(handler) # run the app #show(app) modify_doc(curdoc())
def update_title(attrname, old, new): plot.title.text = text.value text.on_change("value", update_title) def update_data(attrname, old, new): # Get the current slider values a = amplitude.value b = offset.value w = phase.value k = freq.value # Generate the new curve x = np.linspace(0, 4 * np.pi, N) y = a * np.sin(k * x + w) + b source.data = dict(x=x, y=y) for w in [offset, amplitude, phase, freq]: w.on_change("value", update_data) # Set up layouts and add to document inputs = column(text, offset, amplitude, phase, freq) curdoc().add_root(row(inputs, plot, width=800)) curdoc().title = "Sliders"
rectangular_slider_display = column(rectangular_pretext, rectangular_width, rectangular_height) rotation_display = column(rotation) simulation_params_display = row(spacer, quality_factor_input, plasmon_wavelength_input, spacer) dirichlet_params_display = row(spacer, lambda_input, phi_input, spacer) button_display = row(reset_button, run_button) right_display_column_elements = [ mesh_params_display, Div(width=300, height=1, background='#000000'), toggle_button_display, Div(width=300, height=1, background='#000000'), circular_slider_display, Div(width=300, height=1, background='#000000'), rectangular_slider_display, rotation_display, Div(width=300, height=1, background='#000000'), simulation_params_display, dirichlet_params_display, plot_value_dropdown, button_display, #test_url_button, Div(width=300, height=1, background='#000000'), updates_pretext ] right_display = column(right_display_column_elements) curdoc().add_root( row(row(clickable_display, output_display, sizing_mode='scale_both'), row(spacer, right_display, spacer)))
widgets.src_table.on_change( "data", partial( cb.edit_flag, btl_data=btl_data, src_table=widgets.src_table, src_table_changes=widgets.src_table_changes, ), ) widgets.src_table.selected.on_change( "indices", partial(cb.selected_from_table, btl_sal=widgets.btl_sal)) widgets.btl_sal.data_source.selected.on_change( "indices", partial(cb.selected_from_plot, src_table=widgets.src_table)) # Page layout curdoc().add_root(row(widgets.controls, widgets.tables, widgets.fig)) curdoc().title = "CTDO Data Flagging Tool" cb.update_selectors( attr=None, old=None, new=None, ctd_data=ctd_data, btl_data=btl_data, upcast_data=upcast_data, btl_sal=widgets.btl_sal, station=widgets.station, flag_list=widgets.flag_list, parameter=widgets.parameter, src_table=widgets.src_table, src_plot_trace=widgets.src_plot_trace,
from scripts.histogram import histogram_tab from scripts.density import density_tab from scripts.table import table_tab from scripts.draw_map import map_tab from scripts.routes import route_tab # Using included state data from Bokeh for map from bokeh.sampledata.us_states import data as states # Read data into dataframes flights = pd.read_csv(join(dirname(__file__), 'data', 'flights.csv'), index_col=0).dropna() # Formatted Flight Delay Data for map map_data = pd.read_csv(join(dirname(__file__), 'data', 'flights_map.csv'), header=[0, 1], index_col=0) # Create each of the tabs tab1 = histogram_tab(flights) tab2 = density_tab(flights) tab3 = table_tab(flights) tab4 = map_tab(map_data, states) tab5 = route_tab(flights) # Put all the tabs into one application tabs = Tabs(tabs=[tab1, tab2, tab3, tab4, tab5]) # Put the tabs in the current document for display curdoc().add_root(tabs)
dsTable.datasets_table, dsTable.vars_table, btn_plot_lonXlat, plotLayout, status_bar, name='mainLayout') doc.remove_root(loadLayout) doc.add_root(mainLayout) def log(msg, ex=None): status_bar.text = msg if ex is None: logger.debug(msg) else: logger.exception(msg, ex) doc = curdoc() log("Load an index file to get started.") btnLoad = Button(label="Load") btnLoad.on_click(lambda: load_file(txt_file.value)) txt_file = TextInput(value="index_201x.json", title="Specify index file to load") loadLayout = column(Div(height=50, style={"height": "50px"}), txt_file, btnLoad, status_bar) doc.add_root(loadLayout) # [plot.init_layout()]
'country': df.loc[df['Year'] == yr].Country, 'pop': (df.loc[df['Year'] == yr].population / 20000000) + 2, 'region': df.loc[df['Year'] == yr].region, } source.data = new_data p.x_range.start = min(df[x]) p.x_range.end = max(df[x]) p.y_range.start = min(df[y]) p.y_range.end = max(df[y]) plot.title.text = 'Gapminder data for %d' % yr slider = Slider(start=1970, end=2010, step=1, value=1970, title='Year') slider.on_change('value', update_plot) x_select = Select(options=['fertility', 'life', 'child_mortality', 'gdp'], value='fertility', title='x-axis data') x_select.on_change('value', update_plot) y_select = Select(options=['fertility', 'life', 'child_mortality', 'gdp'], value='life', title='y-axis data') y_select.on_change('value', update_plot) layout = row(widgetbox(slider, x_select, y_select), p) curdoc().add_root(layout)
from bokeh.io import curdoc, show from bokeh.models import ColumnDataSource, Dash, Grid, 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 = Dash(x="x", y="y", size="sizes", line_color="#3288bd", line_width=1, 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)
slider = RangeSlider(title="Max Salary", start=10000, end=110000, value=(10000, 50000), step=1000, format="0,0") slider.on_change('value', lambda attr, old, new: update()) button = Button(label="Download", button_type="success") button.js_on_event( "button_click", CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read())) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) controls = column(slider, button) curdoc().add_root(row(controls, data_table)) curdoc().title = "Export CSV" update()
year = years[0] slider.value = year def slider_update(attrname, old, new): year = slider.value label.text = str(year) source.data = data[year] slider = Slider(start=years[0], end=years[-1], value=years[0], step=1, title="Year") slider.on_change('value', slider_update) def animate(): if button.label == '► Play': button.label = '❚❚ Pause' curdoc().add_periodic_callback(animate_update, 200) else: button.label = '► Play' curdoc().remove_periodic_callback(animate_update) button = Button(label='► Play', width=60) button.on_click(animate) layout = layout([ [plot], [slider, button], ], sizing_mode='scale_width') curdoc().add_root(layout) curdoc().title = "Gapminder"
}, 'Boston': { 'airport': 'BOS', 'title': 'Boston, MA', }, 'Seattle': { 'airport': 'SEA', 'title': 'Seattle, WA', } } city_select = Select(value=city, title='City', options=sorted(cities.keys())) distribution_select = Select(value=distribution, title='Distribution', options=['Discrete', 'Smoothed']) #df = pd.read_csv(join(dirname(__file__), 'data/2015_weather.csv')) #df = pd.read_csv(join(dirname(r'D:\Python_files\Bokeh_serve'), '2015_weather.csv')) df = pd.read_csv(r'D:\Python_files\Bokeh_serve\2015_weather.csv') source = get_dataset(df, cities[city]['airport'], distribution) plot = make_plot(source, "Weather data for " + cities[city]['title']) city_select.on_change('value', update_plot) distribution_select.on_change('value', update_plot) controls = column(city_select, distribution_select) curdoc().add_root(row(plot, controls)) curdoc().title = "Weather"
k_means = KMeans(n_clusters=N) k_means.fit(iris.data) centroids = k_means.cluster_centers_ palette = sns.palettes.color_palette('hls', N) colormap = np.array(palette.as_hex( ))[k_means. labels_] # as hex is necessary for bokeh to render the colors properly. plot.xaxis.axis_label = x_axis.value plot.yaxis.axis_label = y_axis.value source.data = dict(x=iris.data[:, x_var], y=iris.data[:, y_var], colors=colormap) centers.data = dict(cx=centroids[:, x_var], cy=centroids[:, y_var]) controls = [clusters, x_axis, y_axis] for control in controls: control.on_change('value', lambda attr, old, new: update()) # Set up layouts and add to document inputs = widgetbox(x_axis, y_axis, clusters) update() #initial load of data curdoc().add_root(row(inputs, plot, width=1000)) curdoc().title = "Iris K-means clustering"
plot9.add_layout(transition2_box) # misc text intro.text = TEXT_INTRO summary.text = TEXT_SUMMARY summary.style = {'font-weight': 'bold'} stats_str = 'Transmissions: ' + str(ar_stats[0]) + '<br/>Recoveries: ' + str( ar_stats[1]) + '<br/>Deaths: ' + str(ar_stats[2]) stats.text = stats_str notes.text = TEXT_NOTES # Set up layouts and add to document notespacer = Spacer(width=TEXT_WIDTH, height=10, width_policy='auto', height_policy='fixed') inputs = column(intro, population, iinfections, period, period_stdev, latent, duration1, transition1, duration2, transition2, beta1, beta2, beta3, drate, button, summary, stats, notespacer, notes) curdoc().title = PAGE_TITLE # useful for mobile scrolling on the left side leftmargin = Spacer(width=LMARGIN_WIDTH, height=400, width_policy='fixed', height_policy='auto') curdoc().add_root( row(leftmargin, inputs, column(plot, plot2, plot5), column(plot4, plot6, plot7), column(plot3, plot8, plot9)))
odesystem_settings.init_fun_key][1], title="v(x,y):") # dropdown menu for selecting one of the sample functions sample_fun_input = Dropdown( label="choose a sample function pair or enter one below", menu=odesystem_settings.sample_system_names) # Interactor for entering starting point of initial condition interactor = my_bokeh_utils.Interactor(plot) # initialize callback behaviour sample_fun_input.on_change('value', sample_fun_change) u_input.on_change('value', ode_change) v_input.on_change('value', ode_change) interactor.on_click(initial_value_change) # calculate data init_data() # lists all the controls in our app associated with the default_funs panel function_controls = widgetbox(sample_fun_input, u_input, v_input, width=400) # refresh quiver field and streamline all 100ms curdoc().add_periodic_callback(refresh_user_view, 100) # make layout curdoc().add_root(row(function_controls, plot)) curdoc().title = split(dirname(__file__))[-1].replace('_', ' ').replace( '-', ' ' ) # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '
main_column = column(continent_select, non_static_row, static_row) main_column = column(question_1, main_column) correlation_column = column(correlation_select, correlation) pyramid_plot = gridplot([[pyramid_left, pyramid_right]], border_space=0) pyramid_plot_slider = row(pyramid_plot, pyramid_xaxis_slider) pyramid_column = column(pyramid_year_select, pyramid_plot_slider) pyramid_row = row(pyramid_column) correlations_200 = row(correlation_column, pyramid_row) correlations_200 = column(question_2, correlations_200) histogram_figure_mean_median = row(histogram_figure, histogram_mean_median) hist_column = column(histogram_year_select, histogram_figure) gdp_column = column(gdp_correlation_select, gdp_correlation) further_row = row(hist_column, gdp_column) rest_column = column(correlations_200, further_row) regions_column = column(main_column, map_column) layout = row(regions_column, rest_column) # initial update update_bar_chart() update_correlation() update_pyramid() update_histogram() update_gdp_correlation() curdoc().add_root(layout) curdoc().title = 'Interactive Data Visualisation'
stats.text = str(data[[t1, t2, t1 + '_returns', t2 + '_returns']].describe()) ticker1.on_change('value', ticker1_change) ticker2.on_change('value', ticker2_change) def selection_change(attrname, old, new): t1, t2 = ticker1.value, ticker2.value data = get_data(t1, t2) selected = source.selected.indices if selected: data = data.iloc[selected, :] update_stats(data, t1, t2) source.selected.on_change('indices', selection_change) # set up layout widgets = column(ticker1, ticker2, stats) main_row = row(corr, widgets) series = column(ts1, ts2) layout = column(main_row, series) # initialize update() curdoc().add_root(layout) curdoc().title = "Stocks"
def f() -> None: nonlocal reported_curdoc reported_curdoc = curdoc()
layout = row(p, inputs) # In[107]: set_values = update(prof_Select.value) # In[2]: profession = merged_df_all.primaryProfession1.unique() # In[108]: p.vbar(source=source, x='x', top='y', bottom=2000000, width=0.3, color=factor_cmap('prof', palette=['Darkblue', 'magenta'], factors=profession), legend='prof') # In[109]: curdoc().add_root(layout) curdoc().title = "Highest Rated Actor/Actress" # In[1]: #show(layout)
def invoker() -> None: nonlocal reported_curdoc nonlocal reported_foo reported_curdoc = curdoc() reported_foo = 10
# Get the current slider values x_start = datetime.fromtimestamp(date_slider.value[0] / 1000) x_end = datetime.fromtimestamp(date_slider.value[1] / 1000) x_start = pd.to_datetime(x_start) x_end = pd.to_datetime(x_end) #print(x_start) #print(x_end) # Generate new data new_df = df[(df['x'] >= x_start) & (df['x'] <= x_end)] new_df.loc[:, 'port'] = (new_df['port'].pct_change().fillna(0) + 1).cumprod() * 100 new_df.loc[:, 'bm'] = (new_df['bm'].pct_change().fillna(0) + 1).cumprod() * 100 new_df.loc[:, 'longOnly'] = (new_df['longOnly'].pct_change().fillna(0) + 1).cumprod() * 100 new_df.loc[:, 'ER_port'] = new_df['port'] - new_df['bm'] new_df.loc[:, 'ER_long'] = new_df['port'] - new_df['longOnly'] new_df.loc[:, 'dd'] = drawdown(new_df['port'].values).values new_df = new_df.reset_index().iloc[:, 1:] newdata = ColumnDataSource(new_df) source.data = newdata.data date_slider.on_change('value', update_data) plots = column(p1, p2, date_slider) panel_1 = Panel(child=plots, title='Panel 1') tabs = Tabs(tabs=[panel_1, panel_2]) curdoc().add_root(tabs) curdoc().title = "DateRangeSlider Example"
# We will generate x and y coordinates every 0.1 seconds # out of angles starting from an angle of 0 for both earth and mars i_earth = 0 i_mars = 0 # The update function will generate coordinates def update(): global i_earth, i_mars # This tells the function to use global variables declared outside the function i_earth += 2 # We will increase the angle of earth by 2 in function call i_mars += 1 new_earth_data = dict( x_earth=[earth_orbit.glyph.radius * cos(radians(i_earth))], y_earth=[earth_orbit.glyph.radius * sin(radians(i_earth))]) new_mars_data = dict( x_mars=[mars_orbit.glyph.radius * cos(radians(i_mars))], y_mars=[mars_orbit.glyph.radius * sin(radians(i_mars))]) earth_source.stream(new_earth_data, rollover=1) mars_source.stream(new_mars_data, rollover=1) print(earth_source.data) print(mars_source.data) # Add periodic callback and plot the curdoc curdoc().add_periodic_callback(update, 100) curdoc().add_root(p)
def __call__(self, parameterized, doc=None, plots=[], **params): self.p = param.ParamOverrides(self, params) if self.p.initializer: self.p.initializer(parameterized) self._widgets = {} self.parameterized = parameterized self.document = None self.comm_target = None if self.p.mode == 'notebook': if not IPYTHON_AVAILABLE: raise ImportError('IPython is not available, cannot use ' 'Widgets in notebook mode.') self.comm = JupyterCommJS(on_msg=self.on_msg) # HACK: Detects HoloViews plots and lets them handle the comms hv_plots = [plot for plot in plots if hasattr(plot, 'comm')] if hv_plots: self.comm_target = [p.comm.id for p in hv_plots][0] self.document = [p.document for p in hv_plots][0] plots = [p.state for p in plots] self.p.push = False else: self.comm_target = uuid.uuid4().hex self.document = doc or Document() else: self.document = doc or curdoc() self._queue = [] self._active = False self._widget_options = {} self.shown = False widgets, views = self.widgets() plots = views + plots container = widgetbox(widgets, width=self.p.width) if plots: view_box = column(plots) layout = self.p.view_position if layout in ['below', 'right']: children = [container, view_box] else: children = [view_box, container] container_type = column if layout in ['below', 'above'] else row container = container_type(children=children) for view in views: p_obj = self.parameterized.params(view.name) value = getattr(self.parameterized, view.name) if value is not None: rendered = p_obj.renderer(value, p_obj) self._update_trait(view.name, rendered) # Keeps track of changes between button presses self._changed = {} if self.p.on_init: self.execute() if self.p.mode == 'raw': return container self.document.add_root(container) if self.p.mode == 'notebook': self.notebook_handle = notebook_show(container, self.document, self.comm_target) if self.document._hold is None: self.document.hold() self.shown = True return return self.document
demand_source.data = dict(x=demand_x, y=new_demand_y) new_equilibrium_x = (demand_intercept - supply_intercept) / (supply_gradient - demand_gradient) new_equilibrium_y = new_equilibrium_x * demand_gradient + demand_intercept equilibrium_source.data = dict(x=[new_equilibrium_x], y=[new_equilibrium_y]) print(f'equilibrium ({round(new_equilibrium_x, 2)}, {round(new_equilibrium_y, 2)})') print(f'demand ({round(demand_gradient, 2)}x+{round(demand_intercept, 2)})') print(f'supply ({round(supply_gradient, 2)}x+{round(supply_intercept, 2)})') new_equilibrium_vertical_x = np.linspace(new_equilibrium_x, new_equilibrium_x, N) new_equilibrium_vertical_y = np.linspace(0, new_equilibrium_y, N) equilibrium_vertical_source.data = dict(x=new_equilibrium_vertical_x, y=new_equilibrium_vertical_y) new_equilibrium_horizontal_x = np.linspace(0, new_equilibrium_x, N) new_equilibrium_horizontal_y = np.linspace(new_equilibrium_y, new_equilibrium_y, N) equilibrium_horizontal_source.data = dict(x=new_equilibrium_horizontal_x, y=new_equilibrium_horizontal_y) update_text(new_x=new_equilibrium_x, new_y=new_equilibrium_y) for widget in [supply, demand, supply_elasticity, demand_elasticity]: widget.on_change('value', update_data) inputs = widgetbox(supply, demand, supply_elasticity, demand_elasticity, equilibrium) curdoc().add_root(row(inputs, plot, width=800)) curdoc().title = "Interactive Demand & Supply"
def clear_plot(): source_data.data = dict(x=[], y=[]) pred_data.data = dict(x=[], y=[]) source_bars.data = dict(y=[], right=[]) pred_line.data = dict(y=[], x=[]) tsne.data = dict(y=[], x=[]) def update_plot_signature(attr, old, new): # print(attr, old, new) update_plot() # Disable controls initially change_model() plot_run.on_click(update_plot) plot_clear.on_click(clear_plot) ctl_model.on_click(change_model) ctl_feat_reduce.on_click(update_plot) ctl_kernel.on_click(update_plot) # Page Layout col_inputs = column(plot_ctls, ctl_inputs, disp_disclaimer) row_plots = row(plot_mood_scatter, plot_mood_bar) row_page = row(col_inputs, column(row_plots, plot_feature_scatter), column(disp_features, disp_score), width=1200) curdoc().add_root(row_page) curdoc().title = "Daylio Data Display"
def update_intermediate(attr, old, new): source.data = dict(x=[], y=[]) update() f.xaxis.formatter = DatetimeTickFormatter( seconds=["%Y-%m-%d-%H-%m-%S"], minsec=["%Y-%m-%d-%H-%m-%S"], minutes=["%Y-%m-%d-%H-%m-%S"], hourmin=["%Y-%m-%d-%H-%m-%S"], hours=["%Y-%m-%d-%H-%m-%S"], days=["%Y-%m-%d-%H-%m-%S"], months=["%Y-%m-%d-%H-%m-%S"], years=["%Y-%m-%d-%H-%m-%S"], ) f.xaxis.major_label_orientation = radians(90) # Create Select widget options = [("bitstampUSD", "Bitstam USD"), ("bitstampEUR", "Bitstamp EUR")] select = Select(title="Currancy Name", value="bitstampUSD", options=options) select.on_change("value", update_intermediate) # Add figure to curdoc lay_out = layout([[f], [select]]) curdoc().add_root(lay_out) # Configure callback curdoc().add_periodic_callback(update, 2000)