def render_plot(): dist_plot = distribution() anim_plot = animated() pop = Population(curdoc()) return render_template( 'app_plot.html', tag1=autoload_server(dist_plot), tag2=autoload_server(anim_plot), tag3=autoload_server(pop.layout) )
def make_snippet(kind, plot, session=None, target=None): if kind == "plot": tag = autoload_server(plot, session) thread = Thread() thread.start() if kind == "animated": tag = autoload_server(plot, session) thread = Thread(target=target, args=(plot, session)) thread.start() elif kind == "widget": tag = autoload_server(plot, session) thread = Thread(target=target, args=(pop,)) thread.start() return tag, plot._id
def standalone(*tunnels, plots=None, remote_only=False, bokeh_port=5006, mon_port=8080): execs = make_tunnels(tunnels, (not remote_only)) plot_args = {'plot_list': plots} if plots else dict() plots, monitors, change_streams = generate_plots(execs, **plot_args) p_bokeh, session = start_bokeh(mon_port, bokeh_port, change_streams) def kill_bokeh(): if isinstance(p_bokeh, Popen): p_bokeh.terminate() try: print(session.id) scr = autoload_server(plots, session_id=session.id) print(scr) scr = re.sub('http://localhost:{0}'.format(bokeh_port), '', scr) scr = TEMPLATE.format(script=scr).encode() loop = asyncio.get_event_loop() start_tornado(loop, bokeh_port, mon_port, scr) loop.run_until_complete(asyncio.gather( *(mon() for mon in monitors), *(changes.start() for changes in change_streams) )) finally: kill_bokeh()
def test_script_attrs_no_session_id_provided(self): r = embed.autoload_server(None) self.assertFalse('bokeh-session-id' in r) html = bs4.BeautifulSoup(r) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set([ 'src', 'data-bokeh-doc-id', 'data-bokeh-model-id', 'data-bokeh-log-level', 'async', 'id' ])) divid = attrs['id'] src = "%s/autoload.js?bokeh-autoload-element=%s" % \ ("http://localhost:5006", divid) self.assertDictEqual({ 'async' : 'false', 'data-bokeh-doc-id' : '', 'data-bokeh-model-id' : '', 'data-bokeh-log-level' : 'info', 'id' : divid, 'src' : src }, attrs)
def test_script_attrs(self): r = embed.autoload_server(_embed_test_plot, self.sess) html = bs4.BeautifulSoup(r) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set([ 'src', 'data-bokeh-docid', 'data-bokeh-docapikey', 'data-bokeh-modeltype', 'data-bokeh-modelid', 'data-bokeh-root-url', 'async', 'id', 'data-bokeh-data', 'data-bokeh-conn-string' ])) self.assertEqual(attrs['async'], 'true') self.assertEqual(attrs['data-bokeh-data'], 'server') self.assertEqual(attrs['data-bokeh-docapikey'], 'apikey123') self.assertEqual(attrs['data-bokeh-docid'], 'docid10') self.assertEqual(attrs['data-bokeh-modelid'], str(_embed_test_plot._id)) self.assertEqual(attrs['data-bokeh-modeltype'], 'Plot') self.assertEqual(attrs['data-bokeh-root-url'], "http://foo/") self.assertEqual(attrs['data-bokeh-conn-string'], 'ws://foo/bokeh/sub') divid = attrs['id'] self.assertEqual(attrs['src'], "%s/bokeh/autoload.js/%s" % ("http://foo", divid))
def init_plot(crawl_name): session = Session() document = Document() session.use_doc(crawl_name) session.load_document(document) if document.context.children: plot = document.context.children[0] else: output_server(crawl_name) # TODO: Remove these when Bokeh is upgraded # placeholders or Bokeh can't inject properly current = np.datetime64(datetime.now()) xdr = Range1d(current, current + 1) ydr = ["urls"] # styling suggested by Bryan plot = figure(title="Crawler Monitor", tools="hover", x_axis_type="datetime", y_axis_location="right", x_range=xdr, y_range=ydr, width=1200, height=600) plot.toolbar_location = None plot.xgrid.grid_line_color = None document.add(plot) session.store_document(document) script = autoload_server(plot, session) #TODO: Looks like a Bokeh bug, probably not repeatable with current code script = script.replace("'modelid': u'", "'modelid': '") return script
def get_bokeh_script(self, suffix): assert hasattr(self, 'object') bokeh_session = pull_session(session_id=None, url='http://localhost:5006/%s/' % suffix) # We want to make this less cumbersome see https://github.com/bokeh/bokeh/issues/3349 user_source = bokeh_session.document.get_model_by_name('user_pk_source') user_source.data = dict(user_pk=[self.object.pk]) script = autoload_server(None, app_path='/%s' % suffix, session_id=bokeh_session.id) return script
def factexplorer(): # session = pull_session(url="http://localhost:5006/factexplorer") script = autoload_server(model=None, app_path="/factexplorer", url="http://localhost") return render_template( "description.html", script = script, title = "Exploring timeseries of selected facts", summary = summary, description = "The facts can be selected by user input. If no fact can be found, the graph will not change." )
def journals(): # session = pull_session(url="http://localhost:5006/journals") script = autoload_server(model=None, app_path="/journals", url="http://localhost:5006") return render_template( "description.html", script = script, title = "Exploring paper distribution across journals", summary = summary, description = "This graph shows the distribution of papers over journals, with absolute counts on the left hand scale, and cumulative percentage on the right hand scale." )
def cooccurrences(): # session = pull_session(url="https://contentmine-demo-staging.herokuapp.com/cooccurrences") script = autoload_server(model=None, app_path="/cooccurrences", url="https://contentmine-demo-staging.herokuapp.com") return render_template( "description.html", script = script, title = "Exploring co-occurrences of facts", summary = summary, description = "The plot shows the count of co-occurrences of facts with other facts of their dictionary, in a range of top 5 to top 25. Co-occurrence between two facts is defined as appearing together in the same publication." )
def trending(): # session = pull_session(url="http://127.0.0.1:5006/trending") script = autoload_server(model=None, app_path="/trending", url="http://127.0.0.1:5006") return render_template( "description.html", title = "Exploring most frequent and uptrending facts", summary = summary, description = "The left column shows the top 10 facts, determined by absolute counts over the whole period. The right column shows the top 10 uptrending facts, determined by the sum of percentage changes of daily counts.", script = script )
def dictionaries(): # session = pull_session(url="http://0.0.0.0:5006/dictionaries") script = autoload_server(model=None, app_path="/dictionaries", url="http://0.0.0.0:5006") return render_template( "description.html", script = script, title = "Exploring aggregated counts of facts over dictionaries", summary = summary, description = "The upper time series shows the absolute counts of facts, aggregated by their source dictionary. The lower time series shows the relative share of facts per dictionary, as a fraction of the daily total count." )
def index(): plot = figure() plot.circle([1,2], [3,4]) document = Document() document.add_root(plot) session = push_session(document) script = autoload_server(None, session_id=session.id) return render_template('index.html', bokeh_script=script)
def apply(self,target_df): self.init_func(target_df, *self.args, **self.kwargs) self.session = push_session(curdoc()) tag = autoload_server(self.p,session_id=self.session.id) target_df._top_df._plots.append(tag) thread = Thread(target = self._continuous_wrapper, args=(target_df,)) thread.start() return thread
def content(self): plot, session = self.create_plot() divs = autoload_server(plot, session) for var in self.variables: thread = threading.Thread(target=self.update_plot, args=(plot, session, var)) thread.start() return render_template('bokeh_linechart.html', divs=divs, variables=self.variables, viewid=self.viewid)
def pages_timeseries(response): parse_datetime = lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%f") parsed_dates = [parse_datetime(x[1]) for x in response] dates = sorted(parsed_dates) plot = figure(plot_width=584, x_axis_type="datetime", x_axis_label="Dates", y_axis_label="Number Fetched") plot.line(x=dates, y=range(len(dates))) button = Button(label="Press Me") session = push_session(curdoc()) script = autoload_server(vplot(plot, button), session_id=session.id) return script
def embed_bokeh(request, bokeh_app): """Render the requested app from the bokeh server""" # http://bokeh.pydata.org/en/0.12.3/docs/reference/embed.html # TODO: test if bokeh server is reachable bokeh_script = autoload_server(None, app_path="/{}".format(bokeh_app), url=bokeh_url) context = {'bokeh_script': bokeh_script, 'bokeh_app': bokeh_app} return render(request, "dashboard/embed_bokeh.html", context)
def get_bokeh_script(user, plot, suffix): from .models import UserSession document = Document() document.add_root(plot) document.title = suffix with closing(push_session(document)) as session: # Save the session id to a UserSession UserSession.objects.create(user=user, bokeh_session_id=session.id) # Get the script to pass into the template script = autoload_server(None, session_id=session.id) return script
def render_plot(): """ Get the script tags from each plot object and "insert" them into the template. This also starts different threads for each update function, so you can have a non-blocking update. """ dist_plot, dist_session = distribution() dist_tag = autoload_server(dist_plot, dist_session) anim_plot, anim_session = animated() anim_tag = autoload_server(anim_plot, anim_session) # for update_animation as target we need to pass the anim_plot and anim_session as args thread = Thread(target=update_animation, args=(anim_plot, anim_session)) thread.start() pop = Population() pop_tag = autoload_server(pop.layout, pop.session) # for update_population as target we need to pass the pop instance as args thread = Thread(target=update_population, args=(pop,)) thread.start() return render_template('app_plot.html', tag1=dist_tag, tag2=anim_tag, tag3=pop_tag)
def get_bokeh_script(plot): from .models import UserSession document = Document() document.add_root(plot) with closing(push_session(document, url=bokeh_url)) as session: # Save the session id UserSession.objects.create(user=User.objects.get(), bokehSessionId=session.id) # Get the script to pass into the template script = autoload_server(None, session_id=session.id, url=bokeh_url) return script
def root(): """ Returns the web interface to the estuary model """ bokeh_div = autoload_server(None, session_id=None, app_path='/app', url='') left, right = bokeh_div.split('src="') bokeh_div = left + 'src="http://yavinprime.mit.edu:5006' + right html = flask.render_template( 'app.html', # bokeh=autoload_server(None, session_id=None, # app_path='/app', url=''), bokeh=bokeh_div, ) return encode_utf8(html)
def render_dashboard(): #dashboard = DashBoard() #tag = autoload_server(dashboard.layout, dashboard.session) tag = autoload_server(dashboard.layout, dashboard.session) html = """ <html> <head></head> <body> %s </body> </html> """ html = html % (tag) #render_template('demo.html', tag=tag) return render_template('demo.html', tag=tag)
def wrapper(*args, **kwargs): docname = prefix + str(uuid.uuid4()) session = Session(name=url, root_url=url) session.use_doc(docname) session.load_document(curdoc()) curdoc().autoadd = False curdoc().autostore = False obj = func(*args, **kwargs) tag = embed.autoload_server(obj, session) obj.tag = tag curdoc().add(obj) changed = session.store_document(curdoc()) logger.debug("stored: %s", str(changed)) return obj
def input(): hover = HoverTool( tooltips=[ ('Agency','<font color="#000000"> @agency, @city, @state</font>')]) plot = format(figure(title="Hit Rate vs Search Rate Split by Race",plot_width=800, plot_height=400,tools=[hover,"pan","wheel_zoom","box_zoom","reset"])) plot.circle('black_search_rate','black_hit_rate',color="#dd3439",size=10,source=source_rates,legend="Black Drivers",alpha=0.7) plot.circle('white_search_rate','white_hit_rate',color="#257bf8",size=10,source=source_rates,legend="White Drivers",alpha=0.7) plot.xaxis.axis_label = "Searches / Stops" plot.yaxis.axis_label = "Hits / Searches" curdoc().add_root(plot) session = push_session(curdoc()) bokeh_script = autoload_server(plot, session_id=session.id, url=url) bokeh_id = bokeh_script.split()[2].split('"')[1] print "script:" print bokeh_script print "id:" print bokeh_id return render_template("input.html", bokeh_script=bokeh_script)
def test_script_attrs_session_id_provided(self): r = embed.autoload_server(_embed_test_plot, session_id='fakesession') self.assertTrue('bokeh-session-id=fakesession' in r) html = bs4.BeautifulSoup(r) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set([ 'src', 'data-bokeh-doc-id', 'data-bokeh-model-id', 'id' ])) divid = attrs['id'] src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-session-id=fakesession" % \ ("http://localhost:5006", divid) self.assertDictEqual({ 'data-bokeh-doc-id' : '', 'data-bokeh-model-id' : str(_embed_test_plot._id), 'id' : divid, 'src' : src }, attrs)
def root(): """ Returns the web interface to the estuary model """ # Over-write url if in deployment; else, accept default. autoload_kws = dict(app_path="/app", session_id=None) if args.deploy: autoload_kws['url'] = '' bokeh_div = autoload_server(None, **autoload_kws) if args.deploy: left, right = bokeh_div.split('src="') deployment_src = 'src="http://{:s}:{:d}'.format( args.host, args.bokeh_port ) bokeh_div = left + deployment_src + right html = flask.render_template( 'app.html', # bokeh=autoload_server(None, session_id=None, # app_path='/app', url=''), bokeh=bokeh_div, ) return encode_utf8(html)
def line_scratch(): line_width = 4 line1 = [(0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 5)] line2 = [(0, 1, 2, 3, 4, 5), (0, 5, 1, 4, 2, 3)] line3 = [(5, 4, 3, 2, 1), (5, 4, 3, 2, 1)] plot = figure() red = plot.line(x=line1[0], y=line1[1], line_width=line_width, color="crimson") blue = plot.line(x=line2[0], y=line2[1], line_width=line_width) # purple = plot.line(x=line3[0], y=line3[1], line_width=line_width, color="purple") button = Button(label="Add Line") button.on_click(add_line) curdoc().add_root(vplot(plot, button)) session = push_session(curdoc()) script = autoload_server(model=None, session_id=session.id) # script, div = components(vplot(plot, button)) return script
def embed_bokeh(request, bokeh_app): """Render the requested app from the bokeh server""" # http://bokeh.pydata.org/en/0.12.3/docs/reference/embed.html # TODO: test if bokeh server is reachable bokeh_script = autoload_server(None, app_path="/{}".format(bokeh_app), url=bokeh_url) template = loader.get_template('dashboard/embed_bokeh.html') context = {'bokeh_script': bokeh_script, 'bokeh_app': bokeh_app} response = HttpResponse(template.render(context, request)) # Save full url path in the HTTP response, so that the bokeh # app can use this info, e.g: # http://localhost:8000/dashboard/AMx/?metric=AM1&ci_dataset=cfht&ci_id=452 response.set_cookie('django_full_path', request.get_full_path()) return response
def init_func(self,target_df,f,title, legend=None,interval=1,colors=None,**kwargs): # self.connect_to_server() self.p = figure(plot_width=400, plot_height=400,title=title) (y0,x0) = f(**kwargs) target_df["x/","val/"].set_matrix(np.array(x0).reshape(1,len(x0))) target_df["y/","val/"].set_matrix(np.array(y0).reshape(1,len(y0))) if len(legend)==0: for i in range(len(y0)): legend.append(str(i)) if len(colors)==0: for i in range(len(y0)): color = "#%06x" % randint(0, 0xFFFFFF) colors.append(color) if len(y0)!= len(x0): raise ValueError("f must return two lists of equal length, equal\ to the number of lines to be plotted.") if len(y0)!= len(legend): raise ValueError("length of legend must match number of\ lines plotted") if len(y0) != len(colors): raise ValueError("length of list of colors must much number of\ lines plotted") for i in range(len(legend)): self.p.line([], [], name=legend[i], legend=legend[i], color=colors[i]) self.session = push_session(curdoc()) tag = autoload_server(self.p,session_id=self.session.id) target_df._top_df._plots.append(tag)
degree_normal = round(degree_rad*180./pi) plot.title = titlevalue + str(degree_normal) source.data = dict(x=x, y=y) for w in [mu, tau]: w.on_change('value', update_data) # Set up layouts and add to document inputs = VBoxForm(children=[mu, tau]) layout = HBox(children=[inputs, plot], width=800) html = """ <html> <head>Yolo</head> <body> %s </body> </html> """ % autoload_server(layout, session_id=session.id) with open("motion.html", "w+") as f: f.write(html) document.add_root(layout) if __name__ == "__main__": print("\npress ctrl-C to exit") session.loop_until_closed()
def somepath(): script = autoload_server(model=None, url="http://localhost:5006/generator") return render_template('slide.html', bokS=script)
async def test(request): script = autoload_server(model=None, url='http://localhost:5116/bkapp') with open("templates/embed.html") as tmp: templt = tmp.read() return html(Template(templt).render(script=script))
shifted = groups[1:] + [groups[-1] + 5] self.source_pyramid.data = dict( groups=groups, shifted=shifted, male=male_percent, female=female_percent, ) import bokeh.embed as embed pop = Population() pop.render() tag = embed.autoload_server(pop.layout) html = """ <html> <head></head> <body> %s </body> </html> """ html = html % (tag) with open("population_embed.html", "w+") as f: f.write(html) print(""" To view this example, run
def test_return_type(self): r = embed.autoload_server(_embed_test_plot, self.sess) self.assertTrue(isinstance(r, str))
from bokeh.plotting import * from bokeh.session import Session from bokeh import embed Session().register('testuser', 'testpassword') N = 80 x = np.linspace(0, 4*np.pi, N) y = np.sin(x) output_server("line_animate") TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select" p = figure(tools=TOOLS) p.circle(x, y, color="#3333ee", name="sin") push() renderer = p.select(dict(name="sin")) ds = renderer[0].data_source cursession().publish() tag = embed.autoload_server(p, cursession(), public=True) html = """ <html> <head></head> <body> %s </body> </html> """ html = html % (tag) with open("publishing.html", "w+") as f: f.write(html) print(""" To view this example, run
if __name__ == '__main__': # create a plot and style its properties model1 = get_forecast_data(model1_file) model2 = get_forecast_data(model2_file) i = 0 plots = [] new_pts = [] for city in ['denver', 'ny', 'chicago', 'seattle', 'sf']: for cartype in ['uberX', 'uberXL', 'uberBLACK', 'uberSUV']: p, ds = create_plots(model1, model2, city, cartype) plots.append(p) new_pts.append(ds) vp = vplot(*plots) ip = load(urlopen('http://jsonip.com'))['ip'] session = cursession() session.publish() tag = autoload_server(vp, session, public=True) html = """ {%% extends "base.html" %%} {%% block bokeh %%} %s {%% endblock %%} """ % tag with open('templates/index.html', 'w+') as f: f.write(html)
def run_chart(exchange, asset, limit): client = pymongo.MongoClient() db = client['bitpredict_'+exchange] collection = db[asset_+'_predictions'] def get_data(): if (limit) cursor = collection.find() else cursor = collection.find().limit(limit) data = pd.DataFrame(list(cursor)) data = data.set_index('_id') data = data.sort_index(ascending=True) timestamps = pd.to_datetime(data.index, unit='s').to_series() returns = data.returns.cumsum()*100 return timestamps, returns timestamps, returns = get_data() output_server('bitpredict_'+exchange+'_performance') background = '#f2f2f2' ylabel_standoff = 0 xformatter = DatetimeTickFormatter(formats=dict(hours=["%H:%M"])) yformatter = PrintfTickFormatter(format="%8.1f") p = figure(title=None, plot_width=750, plot_height=500, x_axis_type='datetime', min_border_top=5, min_border_bottom=10, background_fill=background, x_axis_label='Date', tools='', toolbar_location=None) p.line(x=timestamps, y=returns, name='returns', color='#8959a8', line_width=1, legend='Cumulative Return', line_cap='round', line_join='round') p.legend.orientation = 'top_left' p.legend.border_line_color = background p.outline_line_color = None p.xgrid.grid_line_color = 'white' p.ygrid.grid_line_color = 'white' p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.minor_tick_line_color = None p.yaxis.axis_label = 'Percent' p.yaxis.axis_label_standoff = ylabel_standoff p.xaxis.formatter = xformatter p.yaxis.formatter = yformatter p.xaxis.axis_label_standoff = 12 p.yaxis.major_label_text_font = 'courier' p.xaxis.major_label_text_font = 'courier' push() ip = load(urlopen('http://jsonip.com'))['ip'] ssn = cursession() ssn.publish() tag = embed.autoload_server(p, ssn, public=True) renderer = p.select(dict(name='returns')) ds_returns = renderer[0].data_source while True: timestamps, returns = get_data() ds_returns.data['x'] = timestamps ds_returns.data['y'] = returns ssn.store_objects(ds_returns) time.sleep(300)
controls = row(children=[year_select, location_select]) layout = column(children=[controls, pyramid(), population()]) return layout layout = create_layout() update_data() html = """ <html> <head></head> <body> %s </body> </html> """ % autoload_server(layout, session_id=session.id, relative_urls=False) with io.open("widget.html", mode='w+', encoding='utf-8') as f: f.write(html) print(__doc__) document.add_root(layout) if __name__ == "__main__": print("\npress ctrl-C to exit") session.loop_until_closed()
p.annular_wedge( 0, 0, rmin, rmax, theta[:-1], theta[1:], inner_radius_units="data", outer_radius_units="data", fill_color=colors, line_color="black", ) push() tag = embed.autoload_server(p, cursession()) html = """ <html> <head></head> <body> %s </body> </html> """ html = html % (tag) with open("animated_embed.html", "w+") as f: f.write(html) print(""" To view this example, run python -m SimpleHTTPServer (or http.server on python 3)
shifted = groups[1:] + [groups[-1] + 5] self.source_pyramid.data = dict( groups=groups, shifted=shifted, male=male_percent, female=female_percent, ) self.session.store_document(self.document) import bokeh.embed as embed pop = Population() pop.render() tag = embed.autoload_server(pop.layout, pop.session) html = """ <html> <head></head> <body> %s </body> </html> """ html = html % (tag) with open("population_embed.html", "w+") as f: f.write(html) print(""" To view this example, run
def index(): script = autoload_server(model=None, url=url, app_path="/sliders") return render_template('index.html', bokeh_script=script)
p3.axis.minor_tick_line_color = None p3.yaxis.axis_label = 'Basis Points' p3.yaxis.axis_label_standoff = ylabel_standoff p3.xaxis.formatter = xformatter p3.yaxis.formatter = yformatter p3.xaxis.axis_label_standoff = 12 p3.yaxis.major_label_text_font = 'courier' p3.xaxis.major_label_text_font = 'courier' p3.x_range = p1.x_range vp = vplot(p1, p2, p3) push() ip = load(urlopen('http://jsonip.com'))['ip'] ssn = cursession() ssn.publish() tag = embed.autoload_server(vp, ssn, public=True).replace('localhost', ip) html = """ {%% extends "layout.html" %%} {%% block bokeh %%} %s {%% endblock %%} """ % tag with open('templates/extended.html', 'w+') as f: f.write(html) renderer = p1.select(dict(name='prices')) ds_prices = renderer[0].data_source renderer = p2.select(dict(name='predictions')) ds_predictions = renderer[0].data_source renderer = p3.select(dict(name='returns')) ds_returns = renderer[0].data_source
def bokeh_plot(): bokeh_script = autoload_server(None, app_path="/visualize", url="http://rsfern.materials.cmu.edu") return render_template('visualize.html', bokeh_script=bokeh_script)
def update_data(attrname, old, new): #a = aperture.value m = magnitude.value e = exptime.value luvoir.aperture = aperture.value hdi.set_pixel_sizes(luvoir) # adaptively set the pixel sizes wave = hdi.pivotwave snr = phot_etc.compute_snr(luvoir, hdi, e, m) source.data = dict(x=wave[2:-3], y=snr[2:-3], desc=hdi.bandnames[2:-3]) source2.data = dict(x=hdi.pivotwave[0:2], y=snr[0:2], desc=hdi.bandnames[0:2]) source3.data = dict(x=hdi.pivotwave[-3:], y=snr[-3:], desc=hdi.bandnames[-3:]) for w in [aperture, exptime, magnitude]: # iterate on changes to parameters w.on_change('value', update_data) # Set up layouts and add to document inputs = WidgetBox(children=[aperture, exptime, magnitude]) curdoc().add_root(row(children=[inputs, snr_plot])) script = autoload_server(model=None, app_path="/simple_etc", url="pancho.local:5006") #print(script)
from bokeh.embed import autoload_server script = autoload_server("http://localhost:5008/vbar_example")
fill_color=colors, line_color="white") # add the plot to curdoc curdoc().add_root(p) # open a session which will keep our local doc in sync with server session = push_session(curdoc()) html = """ <html> <head></head> <body> %s </body> </html> """ % autoload_server(p, session_id=session.id) with io.open("animated.html", mode='w+', encoding='utf-8') as f: f.write(html) print(__doc__) ds = r.data_source def update(): rmin = roll(ds.data["inner_radius"], 1) rmax = roll(ds.data["outer_radius"], -1) ds.data.update(inner_radius=rmin, outer_radius=rmax) curdoc().add_periodic_callback(update, 30)
df = pd.DataFrame(data) df = df.set_index(['x']) def stacked(df, categories): areas = OrderedDict() last = np.zeros(len(df[categories[0]])) for cat in categories: next = last + df[cat] areas[cat] = np.hstack((last[::-1], next)) last = next return areas output_server("brewer") figure(plot_width=300, plot_height=300) areas = stacked(df, categories) colors = brewer["Spectral"][len(areas)] x2 = np.hstack((data['x'][::-1], data['x'])) patches([x2 for a in areas], list(areas.values()), color=colors, alpha=0.8, line_color=None) tag = embed.autoload_server(curplot(), cursession())
def get(self): template = env.get_template('embed.html') script = autoload_server(model=None, url='http://localhost:5006/bkapp', relative_urls=False) self.write(template.render(script=script, template="Tornado"))
# 'Long EMA(%smin)' % ((n1 * 15) / 60) : x0, # 'Short EMA(%smin)' % ((n2 * 15) / 60): x2 # } #d1 = max(data_obj_2['Short EMA(%smin)' % ((n2 * 15) / 60)]) #d2 = min(data_obj_2['Short EMA(%smin)' % ((n2 * 15) / 60)]) #a1 = abs(int(d1)-int(d2)) #y_r = max(data_obj_2['Recorded Usage']) + 5 x = 1 y = 1 p = figure() p.line(x, y) push() tag = embed.autoload_server(p, cursession()) html = """ <html> <head></head> <body> %s </body> </html> """ with open("animated_embed.html", "w+") as f: f.write(html) renderer = p.select(dict(type=GlyphRenderer)) ds = renderer[0].data_source t = 0
self.figure.toolbar_location = None self.figure.min_border_right = 0 thrustdisplay = ThrustDisplay() x = np.linspace(0, 10, 20) y = np.random.rand()*10 * x thrustdisplay.initdatafields(x, y) @linear(m=1, b=0) def update(step): step = step / 4 x = np.array(step) y = np.random.rand() * 10 * x thrustdisplay.updateData(x, y) # open a session to keep our local document in sync with server session = push_session(curdoc()) curdoc().add_periodic_callback(update, 10) #currently configured to print a script to the console and thats it script = autoload_server(thrustdisplay.figure, session_id=session.id) print(script) script2, div = components(thrustdisplay.figure) print(script2) print(div) #session.show() # open the document in a browser #session.loop_until_closed() # run forever'''