def index(): streaming = True source = AjaxDataSource(data_url="http://localhost:5000/source_data", polling_interval=100) source.data = get_data(time_slice) payload = encode_utf8(get_html(source)) return payload
def index(request): plot = figure(responsive=True, tools=[], plot_width=500, plot_height=250, x_range=(-180, 180), y_range=(-90, 90)) plot.toolbar_location = None plot.axis.visible = None source = AjaxDataSource(method='GET', data_url='http://localhost:8000/view2d/data/', polling_interval=1000) source.data = dict(x=[], y=[]) # Workaround to initialize the plot img = load_image("static/images/earth.png") plot.image_rgba(image=[img], x=[-180], y=[-90], dw=[360], dh=[180]) plot.cross(source=source, x='x', y='y', size=22, line_width=4, color='Orange') # CLU1 script, div = components(plot, INLINE) js_resources = INLINE.render_js() css_resources = INLINE.render_css() context = { 'bokeh_script' : script, 'bokeh_div' : div, 'js_resources' : js_resources, 'css_resources' : css_resources } return render(request, 'view2d/index.html', context)
def plot(): from bokeh.models import AjaxDataSource, CustomJS from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import components from bokeh.layouts import gridplot pid_adapter = CustomJS(code=""" const result = {x:[], ref:[], v:[], e:[], rv:[]} const pts = cb_data.response.points for (let i=0; i<pts.length; i++) { result.x.push(pts[i][0]) result.ref.push(pts[i][1]) result.v.push(pts[i][2]) result.e.push(pts[i][3]) result.rv.push(pts[i][4]) } return result """) pid_t_source = AjaxDataSource(data_url=f'{host}{url_for("data.get_pid_t_data")}', polling_interval=4500, adapter=pid_adapter, mode='append', max_size=500) pid_y_source = AjaxDataSource(data_url=f'{host}{url_for("data.get_pid_y_data")}', polling_interval=4500, adapter=pid_adapter, mode='append', max_size=1024) pid_p_source = AjaxDataSource(data_url=f'{host}{url_for("data.get_pid_p_data")}', polling_interval=800, adapter=pid_adapter, mode='append', max_size=1024) pid_r_source = AjaxDataSource(data_url=f'{host}{url_for("data.get_pid_r_data")}', polling_interval=800, adapter=pid_adapter, mode='append', max_size=1024) pid_t_plot = figure(title='dist', output_backend='webgl') pid_y_plot = figure(title='yaw', output_backend='webgl') pid_p_plot = figure(title='pitch', output_backend='webgl') pid_r_plot = figure(title='roll', output_backend='webgl') pid_t_plot.line('x', 'ref', legend_label="ref", source=pid_t_source) pid_t_plot.line('x', 'v', color='orange', legend_label="measured", source=pid_t_source) pid_t_plot.line('x', 'rv', color='red', legend_label="pid out", source=pid_t_source) pid_y_plot.line('x', 'ref', source=pid_y_source) pid_y_plot.line('x', 'v', color='orange', source=pid_y_source) pid_y_plot.line('x', 'rv', color='red', source=pid_y_source) pid_p_plot.line('x', 'ref', source=pid_p_source) pid_p_plot.line('x', 'v', color='orange', source=pid_p_source) pid_p_plot.line('x', 'rv', color='red', source=pid_p_source) pid_r_plot.line('x', 'ref', source=pid_r_source) pid_r_plot.line('x', 'v', color='orange', source=pid_r_source) pid_r_plot.line('x', 'rv', color='red', source=pid_r_source) p = gridplot([[pid_t_plot, pid_y_plot], [pid_p_plot, pid_r_plot]]) script, div = components(p) cdn_js = CDN.js_files return script, div, cdn_js
def plot(): from bokeh.models import AjaxDataSource, CustomJS from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import components from bokeh.layouts import gridplot sound_adapter = CustomJS(code=""" const result = {x: [], y: []} const pts = cb_data.response.points for (let i=0; i<pts.length; i++) { result.x.push(pts[i][0]) result.y.push(pts[i][1]) } return result """) sound_source = AjaxDataSource(data_url=f'{host}{url_for("data.get_data")}', polling_interval=200, adapter=sound_adapter, mode='replace') sound_plot = figure(output_backend='webgl', y_range=(-(2**15), 2**15)) sound_plot.line('x', 'y', source=sound_source) #sound_plot.xaxis.visible = False #sound_plot.yaxis.visible = False pred_adapter = CustomJS(code=""" const result = {x:[], y: []} const pts = cb_data.response.points for (let i=0; i<pts.length; i++) { result.x.push(i) result.y.push(pts[i]) } return result """) pred_source = AjaxDataSource(data_url=f'{host}{url_for("data.predict")}', polling_interval=100, adapter=pred_adapter, max_size=100, mode='replace') pred_plot = figure(output_backend="webgl", y_range=(0, 6), title='Proba') pred_plot.vbar(x='x', top='y', source=pred_source, color='blue', width=0.2) #pred_plot.xaxis.visible = False p = gridplot([[sound_plot, pred_plot]]) script, div = components(p) cdn_js = CDN.js_files return script, div, cdn_js
def makeTable(period, route): source = AjaxDataSource(data_url=request.url_root + route, polling_interval=period, method='GET', mode='replace') source.data = dict(x=[], y=[]) colx = TableColumn(field="x", title="Time") coly = TableColumn(field="y", title="Info") table = DataTable(source=source, columns=[colx, coly], height=300) script, div = components(table) return script, div
def makePlot(period, route, title, line_color): source = AjaxDataSource(data_url=request.url_root + route, polling_interval=period, method='GET', mode='replace') source.data = dict(x=[], y=[]) plot = figure(plot_height=200, plot_width=800, title=title) plot.line('x', 'y', source=source, line_width=1, line_color=line_color) script, div = components(plot) return script, div
def streaming(): source = AjaxDataSource(data_url = request.url_root + 'ventra2/stream_result/data/', polling_interval = 1000, mode = 'append') #plot = figure(plot_width=300, plot_height=300) plot = figure(plot_height=300,sizing_mode='scale_width',x_axis_label='time (sec)', y_axis_label='count') plot.line('x', 'y', source = source, line_width = 4) script, div = components(plot) return render_template('seconds.html', script = script, div = div)
def simple(): source = AjaxDataSource(data_url="http://127.0.0.1:5000/data", polling_interval=500, mode='append', max_size=30) source.data = dict(x=[], y=[]) fig = figure(height=250, width=450) fig.circle('x', 'y', source=source) script, div = components(fig, INLINE) return jsonify(script=script, div=div, js_resources=INLINE.render_js(), css_resources=INLINE.render_css())
def ajax_data_sample(): # setup AjaxDataSource with URL and polling interval source = AjaxDataSource(data_url='http://some.api.com/data', polling_interval=100) p = figure() # use the AjaxDataSource just like a ColumnDataSource p.circle('x', 'y', source=source) show(p)
def __init__(self,web_app_url): self.dataset = dict(genres=list(), count=list()) self.__adapter = CustomJS(code=""" const result = {genres: [], count: []} const {data} = cb_data.response result.genres = data.genres result.count = data.count return result """) self.__source = AjaxDataSource(data_url=web_app_url + '/MoviesPerGenreByUser', polling_interval=1000, adapter=self.__adapter)
def __init__(self, web_app_url): self.dataset = dict(users=list(), movies=list()) self.__adapter = CustomJS(code=""" const result = {users: [], movies: []} const {data} = cb_data.response result.users = data.users result.movies = data.movies return result """) self.__source = AjaxDataSource(data_url=web_app_url + '/MoviesWatchedByUsers', polling_interval=1000, adapter=self.__adapter)
def __init__(self,web_app_url): self.dataset = dict(users=list(), movies=list()) self.__adapter = CustomJS(code=""" const result = {genre: [], movieId: [], title: [], watches: []} const {data} = cb_data.response result.genre = data.genre result.movieId = data.movieId result.title = data.title result.watches = data.watches return result """) self.__source = AjaxDataSource(data_url=web_app_url + '/TopWatchedMovies', polling_interval=1000, adapter=self.__adapter)
def bokeh_image_ajax_data(request, bokeh_id): model = BokehVisual.objects.get(pk=bokeh_id) x_title = "" y_title = "" with open(os.path.join(model.path,'vis.dat'),'r') as f_in: titles = f_in.readline().split(',') x_title = titles[0].replace(' ','') y_title = titles[1].replace(' ','') plot = figure(title= model.title, x_axis_label= x_title, y_axis_label= y_title, plot_width = model.width, plot_height = model.height) source = AjaxDataSource(data_url="http://localhost:8000/bokeh/id/{}/data/".format(bokeh_id), content_type="json", method="GET", mode='replace') source.data = dict(x=[], y=[]) if(model.img_type == 'line'): im = plot.line('x', 'y', source=source) if(model.img_type == 'circle'): im = plot.circle('x', 'y', source=source) callback = bokeh.models.CustomJS(args=dict(src=source,plt=plot), code=""" var source = src; var plot = plt; start_redrawing = Date.now(); for (var i = 0; i < 100000; i++) { plot.change.emit(); } stop_redrawing = Date.now(); statistic_redrawing(); """) button = bokeh.models.Button(label="Start redrawing", callback=callback) layout = bokeh.models.layouts.Column(button, plot) response_dict = {'script':'', 'div':''} response_dict['script'], response_dict['div'] = components(layout) return JsonResponse({'get':response_dict})
def __init__(self,web_app_url): self.dataset = dict(users=list(), movies=list()) self.__adapter = CustomJS(code=""" const result = {ids: [], titles: [], avgs: [], watches:[]} const {data} = cb_data.response result.ids = data.ids result.titles = data.titles result.avgs = data.avgs result.watches = data.watches return result """) self.__source = AjaxDataSource(data_url=web_app_url + '/MoviesByTitle', polling_interval=1000, adapter=self.__adapter)
def full_plot(): # Set up to connect with self to get data source = AjaxDataSource(data_url='http://localhost:5000/api/data', polling_interval=5000) # Make fig = figure(height=400, sizing_mode='stretch_width') # Make a simple plot fig.line('detect_time', 'void_frac', source=source) fig.xaxis.axis_label = 'Time (s)' fig.yaxis.axis_label = 'Void Fraction' return json.dumps(json_item(fig, "plot"))
def plot_conceptDrift(): # "append" mode is used to output the concatenated data source = AjaxDataSource(data_url='http://127.0.0.1:5000/ConceptDrift/', polling_interval=1000, mode='append') source.data = dict(t_stamp=[], drift_num=[], avg_loss=[], loss_batch=[], label_avg_loss=[], label_loss_batch=[], label_concept_drift=[]) plot = figure(plot_height=300, plot_width=500, x_range=(0, 2000), y_range=(0, 1.1)) plot.line('t_stamp', 'avg_loss', source=source, line_color="red", legend="label_avg_loss", line_width=2) plot.line('t_stamp', 'loss_batch', source=source, line_color="blue", legend="label_loss_batch", line_width=2) plot.square('t_stamp', 'drift_num', source=source, color="orange", legend="label_concept_drift", size=5) script, div = components(plot) return script, div
def index(self): """Render the plots""" plots = [] # Build plot df = data('iris') # source = ColumnDataSource(df) source = AjaxDataSource(data_url='/api/bokeh?dataset=iris') species = df['species'].unique() fill_color = factor_cmap('species', palette=Category10[len(species)], factors=species) hover = HoverTool(tooltips=[ ('index', '$index'), ('petalLength', '@petalLength{0.0}'), ('sepalLength', '@sepalLength{0.0}'), ('species', '@species'), ]) p = figure(title='Iris Morphology', tools=[ hover, 'pan', 'wheel_zoom', 'reset'], active_scroll='wheel_zoom') p.xaxis.axis_label = 'petalLength' p.yaxis.axis_label = 'sepalLength' p.circle(x='petalLength', y='sepalLength', color=fill_color, fill_alpha=0.5, size=10, source=source) # Save plot script, div = components(p) basename = 'iris_scatter' filename = '{}/{}.js'.format(PLOTS_DIR, basename) url = to_url(filename) file = open(filename, 'w') file.write(etree.fromstring(script).text) file.close() plots.append({ 'title': 'Scatterplot', 'div': div, 'script_url': url }) return { 'plots': plots }
def make_plot_ajax(): source = AjaxDataSource(data_url=request.url_root + 'bokeh/data', polling_interval=100) p = figure(plot_height=300, plot_width=800, background_fill_color="lightgrey", title="Streaming Noisy sin(x) via Ajax") p.circle('x', 'y', source=source) p.circle('x', 'z', source=source, line_color="#3288bd", fill_color="white") p.x_range.follow = "end" p.x_range.follow_interval = 10 script, div = components(p) return script, div
def get_states_plot(): source = AjaxDataSource(data={ 'STATE': [], 'STNAME': [], 'STUSAB': [], 'TOT_POP': [], 'TOT_MALE': [], 'TOT_FEMALE': [] }, data_url='/api/states/', mode='replace', method='GET') hover = HoverTool(tooltips=[ ("State", "@STNAME"), ("Population", "@TOT_POP"), ("Female Population", "@TOT_FEMALE"), ("Male Population", "@TOT_MALE"), ]) plot = figure( title='Population by State', plot_width=1200, plot_height=500, x_range=FactorRange(factors=get_state_abbreviations()), y_range=(0, 40000000), tools=[hover, 'tap', 'box_zoom', 'wheel_zoom', 'save', 'reset']) plot.toolbar.active_tap = 'auto' plot.xaxis.axis_label = 'State' plot.yaxis.axis_label = 'Population' plot.yaxis.formatter = NumeralTickFormatter(format="0a") plot.sizing_mode = 'scale_width' plot.vbar(bottom=0, top='TOT_POP', x='STUSAB', legend=None, width=0.5, source=source) url = "/counties/@STATE/" taptool = plot.select(type=TapTool) taptool.callback = OpenURL(url=url) return plot
def page_a(): global widgets init_widgets() # Create a dominate document, see https://github.com/Knio/dominate widgets.dominate_document() with widgets.dom_doc.body: # add css elements here... style(raw("""body {background-color:powderblue;}""")) args, _redirect_page_metrics = widgets.process_req(request) if not args: return _redirect_page_metrics app.logger.info("{} : args {}".format(PAGE_URL, args)) # redirect to another page based on widget data... _redirect = redirect_lookup_table(args.get("sel_nexturl", None)) if _redirect: return redirect(_redirect) widgets.get("sel_nexturl").value = '99' doc_layout = layout(sizing_mode='scale_width') doc_layout.children.append( row(Div(text="""<h1>pywrapBokeh</h1><h2>Page A</h2>"""), Paragraph(text="""Play with all these widgets."""))) source = AjaxDataSource( data=dict(x=[], y=[]), adapter=CustomJS(code="return cb_data.response"), data_url="http://127.0.0.1:6800{}".format(PAGE_URL_GET_DATA), polling_interval=1000, mode='append') fig = figure(title="Streaming Example") fig.line('x', 'y', source=source) doc_layout.children.append(fig) doc_layout.children.append(row(widgets.get("sel_nexturl"))) return widgets.render(doc_layout)
def make_ajax_plot(): adapter = CustomJS(code=""" const result = {x: [], y: []} const pts = cb_data.response.points for (let i=0; i<pts.length; i++) { result.x.push(pts[i][0]) result.y.push(pts[i][1]) } return result """) source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=2000, adapter=adapter) plot = figure(plot_height=300, plot_width=800, background_fill_color="lightgrey", title="Streaming Noisy sin(x) via Ajax") plot.line('x', 'y', source=source) plot.x_range.follow = "end" plot.x_range.follow_interval = 10 script, div = components(plot) return script, div
def make_serverplot_ajax(caseid, plotnames=[['liftOP1', 'liftOP2', 'blue']], xlabel="LiftOp1", ylabel="LiftOp2", title="Lift"): source = AjaxDataSource(data_url=request.url_root[:-1] + url_for('simulation.server_load', caseid=caseid), polling_interval=1000) TOOLTIPS = [ ("DesignID", "$index"), ("LiftOp1", "@liftOP1"), ("LiftOp2", "@liftOP2"), ("DragOp1", "@dragOP1"), ("DragOp2", "@dragOP2"), ("R", "@R"), ("beta", "@beta"), ("a", "@a"), ] p = figure(plot_height=300, plot_width=800, title=title, sizing_mode='scale_width', x_axis_label=xlabel, y_axis_label=ylabel, toolbar_location="above", tooltips=TOOLTIPS) for var in plotnames: p.circle(var[0], var[1], source=source, color=var[2]) #p.x_range.follow = "end" return components(p)
from bokeh.models import AjaxDataSource, CustomJS from bokeh.plotting import figure, show # Bokeh related code adapter = CustomJS(code=""" const result = {x: [], y: []} const pts = cb_data.response.points for (let i=0; i<pts.length; i++) { result.x.push(pts[i][0]) result.y.push(pts[i][1]) } return result """) source = AjaxDataSource(data_url='http://localhost:5555/data', polling_interval=100, adapter=adapter) p = figure(plot_height=300, plot_width=800, background_fill_color="lightgrey", title="Streaming Noisy sin(x) via Ajax") p.circle('x', 'y', source=source) p.x_range.follow = "end" p.x_range.follow_interval = 10 # Flask related code app = Flask(__name__) def crossdomain(f): def wrapped_function(*args, **kwargs): resp = make_response(f(*args, **kwargs))
r = StrictRedis(host='localhost', decode_responses=True) p = r.pubsub() # Main Bokeh Doc doc = curdoc() # Bitcoin price datasource adapter = CustomJS(code=""" var price = cb_data.response['data']['amount'] var data = {x: [price], y: [0]} console.log(price) return data """) btc_price_source = AjaxDataSource( data_url='https://api.coinbase.com/v2/prices/BTC-USD/spot', method='GET', polling_interval=3000, adapter=adapter) # Controls expirys = get_expirys() expiry_keys, expiry_labels = zip(*expirys) option_type_radiobutton = RadioButtonGroup(labels=['Calls', 'Puts'], active=1) top_controls = row(option_type_radiobutton) # load id_table so we can generate our DataColumnSources from it # data_sources[<'put' | 'call'>][expiration][<'bid' | 'ask'>] retrieves a ColumnDataSource of scheme: # {'x': <strike prices>, 'y': <IV%>} data_sources = defaultdict(partial(defaultdict, dict)) id_table = load_id_table() for option_type in ['call', 'put']:
series_sele = {} series_mz = {} series_mz4k = {} series_mzsvg= {} peak_mz = {} peak_mz4k = {} peak_mzsvg = {} series_names = ['Series {:d}'.format(i_series + 1) for i_series in range(n_series)] for i_series in range(len(series_names)): series_cols[series_names[i_series]] = series_colours[i_series] series_cols['Background']='#000000' for i_series in series_names: series_data[i_series] = AjaxDataSource(data=dict(x_low=[], x_upp=[], x_max=[],max_int=[], charge=[]))# series_sele[i_series] = AjaxDataSource(data=dict(i_low=[], i_upp=[], i_max=[])) series_mz[i_series] = AjaxDataSource(data=dict(Intensity=[], mz=[])) series_mz4k[i_series] = AjaxDataSource(data=dict(Intensity=[], mz=[])) series_mzsvg[i_series]= AjaxDataSource(data=dict(Intensity=[], mz=[])) peak_mz[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) peak_mz4k[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) peak_mzsvg[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) series_masses = AjaxDataSource(data=dict(Series=[], Mass=[], Uncertainty=[], Colour=[])) aser_data = AjaxDataSource(data=dict(x_low=[], x_upp=[], x_max=[],max_int=[], charge=[])) series_dict = AjaxDataSource(data=dict(series=series_names, names=series_names)) groel_data=pd.read_csv('Testdata/siyun_groel.txt', skiprows=10, delimiter='\t') # groel_data.columns.values=[ 'Intensity'] groel_data.rename(columns={'1980.151514':'mz', '0.000000':'Intensity'}, inplace=True)
def build_components(self, is_closed): plot_dict = {} for table in self.tables: cp = table.__tablename__ url =f"http://*****:*****@{timestamp}{%d %b %Y %l:%M:%S:%N %P}'), ('rate', '@{rate}{%0.4f}'), ], formatters={ '@{timestamp}': 'datetime', '@{rate}': 'printf' } ) plot.add_tools(hover_tool) callback = CustomJS( args={'line':line, 'source':source, 'cp':cp}, code=""" var rates = source.data.rate; var first_val = rates[0]; var last_val = rates[rates.length-1]; var delta = Number.parseFloat(Math.abs(last_val-first_val)).toFixed(5); var increasing = first_val < last_val; if (increasing) { line.glyph.line_color = 'green'; } else { line.glyph.line_color = 'red'; } var card_class_dict = { true: { "card_class":"card-text text-center font-weight-lighter text-success", "new_color": "green", "arrow": "▲" }, false: { "card_class":"card-text text-center font-weight-lighter text-danger", "new_color": "red", "arrow": "▼" } } var formats = card_class_dict[increasing]; $('#delta_'+cp) .removeClass() .addClass( formats['card_class'] ) .html( formats["arrow"].concat(delta) ); $('#current_'+cp).html(last_val); """ ) source.js_on_change('change:data', callback) plot_dict[cp] = plot return components(plot_dict)
data = s.recv(1024) except socket.error as e: err = "Error receiving data 4: "+str(e) print(err) randomvar = alert(text="No data available", title="Error", button="OK") #s.close() continue connect = False break nan = float('nan') m = [] check2 = True #lightsOn = False source = AjaxDataSource(data_url='http://localhost:5050/data', polling_interval=1000) tools = ["hover", "pan", "wheel_zoom", "reset"] p = figure(plot_width=1200, plot_height=800, y_range=(10, 50), tools=tools, x_axis_label="Seconds Ago from current time", y_axis_label="Temp, °C", y_axis_location="right") p.multi_line(xs='x', ys='y', source=source, line_width=2) p.x_range.start = -305 p.x_range.end = 0 p.x_range.follow_interval = 10 try: from flask import Flask, jsonify, make_response, request, current_app except ImportError: raise ImportError("You need Flask to run this example!")
def index(): global pollfreq global range post = False if request.method == 'POST': range = request.form['range'] post = True # print("range:", range) # Initialize figure data and data source source = AjaxDataSource(data_url="/monitor/data", max_size=5000, polling_interval=pollfreq * 1000, mode='append') dates = [] tempfs = [] dates, tempfs = get_initial_data(range) source.data = dict(x=dates, y=tempfs) # Create the plot TOOLS = "pan,wheel_zoom,box_zoom,reset,save" fig = figure(title='DS18B20 Sensor', x_axis_type='datetime', tools=TOOLS, plot_height=280, sizing_mode='scale_width') hover = HoverTool( tooltips=[ ('temp', '@y{0.00}'), ('time', '@x{%F %T}'), ], formatters={ 'x': 'datetime', # use 'datetime' formatter for 'x' field }, mode='vline') fig.add_tools(hover) fig.xgrid.grid_line_color = None fig.ygrid.grid_line_alpha = 0.8 fig.xaxis.axis_label = 'Time' fig.yaxis.axis_label = 'Temperature' fig.y_range = Range1d(60, 90) fig.line('x', 'y', source=source, line_width=2) fig.add_layout(BoxAnnotation(top=70, fill_alpha=0.1, fill_color='blue')) fig.add_layout( BoxAnnotation(bottom=70, top=80, fill_alpha=0.1, line_color='green', fill_color='green')) fig.add_layout(BoxAnnotation(bottom=80, fill_alpha=0.1, fill_color='red')) plot_script, plot_div = components(fig) if post: return (jsonify(plotscript=plot_script, plotdiv=plot_div)) else: return render_template( "monitor/index.html", plot_script=plot_script, plot_div=plot_div, pollfreq=pollfreq, )
def make_ajax_plot(): source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=86400000, mode='append', max_size=300) source.data = dict(time=[], karma=[], daily_inc=[], ma_week=[]) global df, t for i in xrange(len(df.karma)): t += 1 source.data['karma'].append(df.karma[i]) # t2 = re.split(' .*', str(df.date[i]))[0] source.data['time'].append(t) if i == 0: source.data['daily_inc'].append(0) source.data['ma_week'].append(0) else: source.data['daily_inc'].append(df.karma[i] - df.karma[i - 1]) source.data['ma_week'].append(_moving_avg(list(df.karma[:i]))) p = figure(plot_height=500, tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None, y_axis_location="right") p.x_range.follow = "end" p.x_range.follow_interval = 100 p.x_range.range_padding_units = 'absolute' p.x_range.range_padding = 10 p.line(x='time', y='karma', alpha=0.2, line_width=3, color='orange', source=source, legend='Karma Trend') p.legend.location = "top_left" p2 = figure(plot_height=250, x_range=p.x_range, tools="xpan,xwheel_zoom,xbox_zoom,reset", y_axis_location="right") p2.segment(x0='time', y0=0, x1='time', y1='daily_inc', line_width=6, color='black', alpha=0.5, source=source, legend='Daily Increase') p2.line(x='time', y='ma_week', color='red', source=source, legend='Weekly Moving Average') p2.legend.location = "top_left" final_plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000) script, div = components(final_plot) return script, div
def graph(): ajax_input = dict(x_time=[], x1_time=[], y=[], y_female=[], y_male=[], x_female_proj=[], y_female_proj=[], x_male_proj=[], y_male_proj=[], y_female_avg_viewing=[], y_male_avg_viewing=[]) source = AjaxDataSource(data=ajax_input, data_url='http://127.0.0.1:5000/data', polling_interval=ajax_refresh_inter * 1000) #adapter=adapter) p = figure(plot_height=300, plot_width=800, x_axis_type="datetime", tools="wheel_zoom,reset", title="People Viewing Statistics") p.line(x='x_time', y='y', line_dash="4 4", line_width=3, color='gray', source=source) p.vbar(x='x_time', top='y_female', width=200, alpha=0.5, color='red', legend='female', source=source) #female p.vbar(x='x1_time', top='y_male', width=200, alpha=0.5, color='blue', legend='male', source=source) #male p.xaxis.formatter = DatetimeTickFormatter(milliseconds=["%X"], seconds=["%X"], minutes=["%X"], hours=["%X"]) p.y_range = DataRange1d(start=0, range_padding=5) #padding leave margin on the top p.legend.orientation = "horizontal" #legend horizontal p.xaxis.axis_label = 'Time' p.yaxis.axis_label = 'Number' # p.x_range.follow = "end" # p.x_range.follow_interval = timedelta(seconds=30) p2 = figure(plot_height=300, plot_width=800, tools="wheel_zoom,reset", title="Project Viewing Statistics") p2.vbar(x='x_female_proj', top='y_female_proj', width=f2_vbar_interval, alpha=0.5, color='red', legend='female', source=source) #female p2.vbar(x='x_male_proj', top='y_male_proj', width=f2_vbar_interval, alpha=0.5, color='blue', legend='male', source=source) #male p2.xaxis.ticker = [2, 6, 10, 14] p2.xaxis.major_label_overrides = {2: 'P1', 6: 'P2', 10: 'P3', 14: 'P4'} # avg_view_male = LabelSet(x='x_male_proj', y='y_male_proj', text='y_male_avg_viewing', level='glyph', # x_offset=0, y_offset=5, source=source, render_mode='canvas') # avg_view_female = LabelSet(x='x_female_proj', y='y_female_proj', text='y_female_avg_viewing', level='glyph', # x_offset=0, y_offset=5, source=source, render_mode='canvas') # # p2.add_layout(avg_view_male) # p2.add_layout(avg_view_female) p2.x_range = DataRange1d(start=0, end=16) #padding leave margin on the top p2.y_range = DataRange1d(start=0, range_padding=5) #padding leave margin on the top p2.legend.orientation = "horizontal" p2.xaxis.axis_label = 'Project' p2.yaxis.axis_label = 'Number' js_resources = INLINE.render_js() css_resources = INLINE.render_css() script, div = components((p, p2)) html = render_template( 'embed.html', plot_script=script, plot_div=div[0], plot_div2=div[1], js_resources=js_resources, css_resources=css_resources, ) return encode_utf8(html)
from bokeh.models import HoverTool, AjaxDataSource from bokeh.plotting import figure, show, output_file data = AjaxDataSource(data_url='./random.json', method='GET', content_type='application/json') output_file("bokeh.html", title="scatter 100k points (with WebGL)") p = figure(webgl=True, tools=[HoverTool(), 'pan', 'wheel_zoom'], plot_height=1000, plot_width=1000) p.circle('x', 'y', alpha=0.9, source=data, size=10, color='steelblue', hover_color='red') show(p)