def make_ajax_plot(observable, dim, network_ID): """This function is used to create a new Bokeh instance to send to the view. Inputs: -observable: a string containing the name of the observable to poll for. -network_ID: an int referring to the network whose observable need to be fetched. """ source = AjaxDataSource(method='GET', data_url=resolve_url('control') + "?method=get_observable&observable=" + str(observable) + "&network_ID=" + str(network_ID), polling_interval=3000, mode='replace') source.data = dict(x=[]) for i in range(dim): source.data["y" + str(i)] = [] plot = figure(plot_height=200, sizing_mode='scale_width') span = int(256 * 256 * 256 / (dim + 1)) + 1 a = (int(span / (255 * 255)), int(span / (255)) % 255, span % 255) print(a) for i in range(dim): plot.line('x', 'y' + str(i), source=source, line_width=2, line_color="#%02x%02x%02x" % (int(i * span / (255 * 255)) + 1, int(i * span / (255)) % (255) + 1, i * span % 255 + 1)) plot.xaxis.axis_label = "Iterations over time" script, div = components(plot, CDN) return script, div
def make_ajax_plot(): test = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=2000, mode='replace') test.data = dict(angle=[], country=[], value=[], color=[]) print(test.data) plot = figure(plot_height=350, title="Pie Chart", toolbar_location=None, tools="hover", tooltips="@country: @value") plot.annular_wedge(x=0, y=1, inner_radius=0.2, outer_radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color=None, fill_color='color', legend='country', source=test) plot.axis.axis_label = None plot.axis.visible = False plot.grid.grid_line_color = None script, div = components(plot) return script, div
def make_ajax_plot(): source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=2000, mode='append') source.data = dict(x=[], y=[]) plot = figure(plot_height=300, sizing_mode='scale_width') plot.line('x', 'y', source=source, line_width=4) script, div = components(plot) return script, div
def make_demo_plot(): source = AjaxDataSource(data_url=resolve_url('demo_data'), polling_interval=2000, mode='replace') source.data = dict(x=[], y=[]) plot = figure(plot_height=200, sizing_mode='scale_width') plot.line('x', 'y', source=source, line_width=4) script, div = components(plot, CDN) return script, div
def make_ajax_plot(): source = AjaxDataSource(data_url='http://localhost:9000/data/', polling_interval=2000, mode="append") source.data = dict(x=[], y=[]) plot = figure(plot_height=300, sizing_mode='scale_width') plot.line('x', 'y', source=source, line_width=4) script, div = components(plot, CDN) return script, div
def make_ajax_plot(traffic_scale, databrick): traffic_scale = traffic_scale databrick = databrick source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=3000, mode='replace') #source.data = dict(traffic=[], x=[], y=[], hitters=[], category=[]) source.data = create_source_live_ip(traffic_scale, databrick) # Map specific colors to each category value in the dataframe and set the tools to be suppplied with the visualization. mapper = CategoricalColorMapper(factors=('1', '5', '10'), palette=['#3a9244', '#f9cc10', '#b2282f']) TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom, crosshair" # create a 128 x 128 Bokeh figure entitled "Databrick." plot = figure(title="Databrick", tools=TOOLS, x_range=(0, 127), y_range=(0, 127), x_axis_label="source", y_axis_label="destination") # get rid of any grid, axis, or tick_line color. plot.grid.grid_line_color = None plot.axis.axis_line_color = None plot.axis.major_tick_line_color = None # Create 1 x 1 heatmap elements (rectangles) that visualize each piece of data in from source.data plot.rect(x="x", y="y", width=1, height=1, source=source, fill_color={ 'field': 'category', 'transform': mapper }, line_color=None) # Set the values to be displayed by the hover tool. plot.select_one(HoverTool).tooltips = [('Traffic', '@traffic'), ('source bin', '@x'), ('dest bin', '@y'), ('hitters', '@hitters')] script, div = components(plot) return script, div
def get_ajax_latest_source(user_id, data_id): data_url = "http://127.0.0.1:5000/d/{}/{}".format(user_id, data_id) latest_url = data_url + "/latest" latest_src = AjaxDataSource(dict(index=[], data=[]), data_url=latest_url, polling_interval=5000, method='GET') def on_latest_change(attr, old, new): print('on_latest_change {} old={} new={}'.format(attr, old, new)) latest_src.on_change('data', on_latest_change) return latest_src
def make_line_plot(dictionary, id): source = AjaxDataSource(data_url=request.url_root + 'data/' + id + "/", polling_interval=1000, mode='replace') source.data = dictionary plot = figure(plot_height=300, sizing_mode='scale_width', x_axis_type="datetime") for key in dictionary.keys(): if key == "time_stamp": continue plot.line('time_stamp', key, source=source, line_width=4) script, div = components(plot) return script, div
def make_ajax_plot(): streaming = True source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=1000, mode='replace') plot = plt.figure(plot_height=300, sizing_mode='scale_width') plot.line('x', 'y', source=source, line_width=4) script, div = components(plot) return script, div
def make_control_chart(dictionary, id): source = AjaxDataSource(data_url=request.url_root + 'control-chart/' + id + "/", polling_interval=1000, mode='replace') source.data = dictionary keys = [ key for key in dictionary if not (key.endswith("_lower") or (key.endswith("_upper"))) ] figures = [] for key in keys: if key == "time_stamp": continue plot = figure(plot_height=300, sizing_mode='scale_width', x_axis_type="datetime") band = Band( base="time_stamp", lower=key + '_lower', upper=key + '_upper', source=source, level='underlay', fill_alpha=0.4, line_width=1, fill_color='#55FF88', line_color='red', line_dash='dashed', ) plot.add_layout(band) plot.line('time_stamp', key, source=source, line_width=4) plot.circle('time_stamp', key, source=source, line_width=4, color="red") figures.append(plot) script, div = components(column(figures)) return script, div
def make_ajax_plot(sensor_data: SensorType): colours = bokeh.palettes.Category10[10] plot = figure(plot_height=300, sizing_mode='scale_width') i = 0 for sensor_instance_name, sensor_instance_data in sensor_data.series_data.items( ): update_path = 'data/{}/{}'.format(sensor_data.sensor_type, sensor_instance_name) source = AjaxDataSource(data_url=request.url_root + update_path, polling_interval=30000, mode='replace') source.data = dict(x=sensor_instance_data.x_data, y=sensor_instance_data.y_data) plot.line('x', 'y', source=source, line_width=4, legend_label=sensor_instance_name, color=colours[i % 10]) i += 1 plot.title.text = sensor_data.sensor_type plot.title.text_font_size = '20px' plot.legend.location = "top_left" plot.legend.click_policy = "hide" fs_days = "%Y-%m-%d" fs_hours = "%Y-%m-%d %H" fs_mins = "%Y-%m-%d %H:%M" fs_secs = "%Y-%m-%d %H:%M:%S" plot.xaxis.formatter = DatetimeTickFormatter( seconds=[fs_secs], minutes=[fs_mins], hours=[fs_hours], days=[fs_days], months=[fs_days], years=[fs_days], ) script, div = components(plot) return script, div
def get_api(datatitle, datapoint, yrange, color, horse, refreshrate, mode): if mode == "server": msg = {"meta": datapoint} timeformat = "%H:%M:%S" adapter = CustomJS(code=""" const result = {x: [cb_data.response.x * 1000], y: [cb_data.response.y]} console.log("[=>] Updated Ajax for " + cb_data.response.dp + ":", result) return result """) source = AjaxDataSource( data_url=request.url_root + "api" + "/", http_headers=msg, polling_interval=refreshrate, data=dict(y=[], x=[]), mode="append", adapter=adapter, ) # create an AJAX source fig = figure( title=datatitle, plot_width=1000, plot_height=300, x_axis_type="datetime", sizing_mode="stretch_width", ) # get the figure fig.line(x="x", y="y", source=source, color=color, line_width=4) # add plot to figure # get desired timeformat fig.xaxis.formatter = DatetimeTickFormatter( seconds=[timeformat], minutes=[timeformat], minsec=[timeformat], hours=[timeformat], ) if yrange != "dynamic": fig.y_range = Range1d(float(yrange[1]), float(yrange[0])) fig.title.text_font_size = "12pt" return fig
import numpy as np from datetime import timedelta from functools import update_wrapper, wraps from six import string_types from bokeh.plotting import figure, show, output_file from bokeh.models.sources import AjaxDataSource output_file("ajax_source_realtime.html", title="ajax_source_realtime.py example") source = AjaxDataSource(data_url='http://localhost:5050/data', mode="append", if_modified=True, polling_interval=1000, max_size=125) p = figure() p.line('x', 'y', source=source) import time from threading import Thread from collections import namedtuple, deque import json Entry = namedtuple('Entry', ['x', 'y', 'creation']) entries = deque(maxlen=120) def gen_entry(): global entries
def make_plot(data_url): def make_unit_poly_vertices(dist): x0, y0 = 0, 0 theta = np.linspace(0, 2 * np.pi, 101, endpoint=True) theta += np.pi / 2 # start zero at top result = [(dist * np.cos(t) + x0, dist * np.sin(t) + y0) for t in theta] return result p = figure(plot_width=SIZE, plot_height=SIZE, x_range=(-1 - PAD, 1 + PAD), y_range=(-1 - PAD, 1 + PAD), min_border=0, background_fill_color="#000000") p.xgrid.visible = False p.ygrid.visible = False p.xaxis.axis_label = 'Distance ({})'.format(DISTANCE_UNITS) p.xaxis.axis_label = 'Distance ({})'.format(DISTANCE_UNITS) p.xaxis.ticker = [-1, 0, 1] p.yaxis.ticker = [-1, 0, 1] p.xaxis.major_label_overrides = {-1: str(-SENSOR_RANGE[-1]), 0: 'Zero', 1: str(SENSOR_RANGE[-1])} p.yaxis.major_label_overrides = {-1: str(-SENSOR_RANGE[-1]), 0: 'Zero', 1: str(SENSOR_RANGE[-1])} p.toolbar.logo = None p.toolbar_location = None # concentric lines distances_to_line = np.linspace(0, 1, NUM_LINES, endpoint=True) for d in distances_to_line: vertices = make_unit_poly_vertices(d) # TODO make circle instead line_x = [v[0] for v in vertices] line_y = [v[1] for v in vertices] line_source = ColumnDataSource({'x': line_x, 'y': line_y}) p.line(x='x', y='y', source=line_source, line_width=LINE_WIDTH, line_color='#43ff00') # radial axes num_axes = 4 big_angle = 2.0 * np.pi / num_axes angles = np.arange(num_axes) * big_angle - np.pi / 2 p.annular_wedge(x=0, y=0, inner_radius=distances_to_line[0], outer_radius=distances_to_line[-1], start_angle=angles, end_angle=angles, color='#43ff00') # scatter scatter_source = AjaxDataSource(data_url=data_url, polling_interval=MS_PER_STEP, max_size=ROLLOVER, mode='replace') scatter_source.data = {'x': [], 'y': []} p.scatter(x='x', y='y', source=scatter_source, line_color=None, fill_color='#43ff00', radius=SCATTER_RADIUS) return p
def bokeh_ajax(request): startDt = dfDict['time'][0].to_pydatetime() endDt = dfStatic['time'].iloc[-1].to_pydatetime() # plot used for continually adding points to graph # note: if want to manipulate axis ranges later on need to set some sort of starting range or else when # try to change via figure.x_range.start or figure.x_range.end will get weird incorrect behavior source = AjaxDataSource(data={"time": [], "temperature": [], "id": []}, data_url='http://localhost:6543/AJAXdata', polling_interval=100, mode='append') livePlot = figure(x_axis_type="datetime", x_range=[startDt, endDt], y_range=(0,25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43", plot_width=800) livePlot.line("time", "temperature", source=source) # note: need the below in order to display the bokeh plot jsResources = INLINE.render_js() # need the below in order to be able to properly interact with the plot and have the default bokeh plot # interaction tool to display cssResources = INLINE.render_css() updateStartJS = CustomJS(args=dict(plotRange=livePlot.x_range), code=""" var newStart = Date.parse(cb_obj.value) plotRange.start = newStart plotRange.change.emit() """) updateEndJS = CustomJS(args=dict(plotRange=livePlot.x_range), code=""" var newEnd = Date.parse(cb_obj.value) plotRange.end = newEnd plotRange.change.emit() """) startInput = TextInput(value=startDt.strftime(dateFmt), title="Enter Date in format: YYYY-mm-dd") startInput.js_on_change('value', updateStartJS) endInput = TextInput(value=endDt.strftime(dateFmt), title="Enter Date in format: YYYY-mm-dd") endInput.js_on_change('value', updateEndJS) textWidgets = row(startInput, endInput) layout = column(textWidgets, livePlot) script, div = components(layout) source2 = ColumnDataSource(data={"time": [], "temperature": [], "id": []}) livePlot2 = figure(x_axis_type="datetime", x_range=[startDt, endDt], y_range=(0,25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43", plot_width=800) livePlot2.line("time", "temperature", source=source2) # https://stackoverflow.com/questions/37083998/flask-bokeh-ajaxdatasource # above stackoverflow helped a lot and is what the below CustomJS is based on callback = CustomJS(args=dict(source=source2), code=""" var time_values = "time"; var temperatures = "temperature"; var plot_data = source.data; jQuery.ajax({ type: 'POST', url: '/AJAXdata2', data: {}, dataType: 'json', success: function (json_from_server) { plot_data['temperature'] = plot_data['temperature'].concat(json_from_server['temperature']); plot_data['time'] = plot_data['time'].concat(json_from_server['time']); plot_data['id'] = plot_data['id'].concat(json_from_server['id']); source.change.emit(); }, error: function() { alert("Oh no, something went wrong. Search for an error " + "message in Flask log and browser developer tools."); } }); """) manualUpdate = Button(label="update graph", callback=callback) widgets = widgetbox([manualUpdate]) # IMPORTANT: key is that the widget you want to control plot X has to be in the same layout object as # said plot X . Therefore, when you call the components() method on it both widget and plot live within the # object, if they are not then the JS callbacks don't work because I think they do not know how to communicate # with one another layout2 = column(widgets, livePlot2) script2, div2 = components(layout2) return {'script': script, 'div': div, 'someword': "hello", 'jsResources': jsResources, 'cssResources': cssResources, 'script2': script2, 'div2': div2}
''' Present a scatter plot with linked histograms on both axes. bokeh serve selection_histogram.py http://localhost:5006/selection_histogram ''' import numpy as np from bokeh.models import BoxSelectTool, LassoSelectTool, Paragraph, Slider, CustomJS from bokeh.plotting import figure, hplot, vplot, output_file, show from bokeh.models.sources import AjaxDataSource source = AjaxDataSource(data_url='http://localhost:5000/data/10', method='GET',polling_interval=10000) ph = figure(plot_height=600,plot_width=600,x_range=(-100,100),y_range=(0, 1000), title=None, min_border=10, min_border_left=50) ph.xgrid.grid_line_color = None ph.select(BoxSelectTool).select_every_mousemove = False ph.select(LassoSelectTool).select_every_mousemove = False #hist = ph.quad(bottom=0, left=0, right=0, top=0, color="white", line_color="#3A5785") hist = ph.quad(bottom=0, left=[0]*80, right=[0]*80, top=[0]*80, color="white", line_color="#3A5785") txt = ph.text(70, 900, text=['speed: null'],text_color="firebrick",text_align="center",text_font_size="10pt") txtMinWL = ph.text(70, 850, text=['minWL: null'],text_color="firebrick",text_align="center",text_font_size="10pt") txtMaxWL = ph.text(70, 800, text=['maxWL: null'],text_color="firebrick",text_align="center",text_font_size="10pt") ph.min_border_top = 10 ph.min_border_right = 10 sliderPDE = Slider(start=10, end=100, value=100, step=5, title="PDE") sliderMinWL = Slider(start=150, end=450, value=150, step=50, title="min wl") sliderASIC = Slider(start=0, end=30, value=0, step=10, title="asic") sliderSPTR = Slider(start=0, end=80, value=0, step=10, title="sptr")
def make_plot(): # Initialize Plot plot = figure(x_range=(-9790000, -9745000), y_range=(5120000, 5170000), x_axis_type="mercator", y_axis_type="mercator", tools=['pan'], sizing_mode='stretch_both') plot.add_tile(CARTODBPOSITRON) plot.toolbar.active_scroll = "auto" plot.xaxis.major_tick_line_color = None # turn off x-axis major ticks plot.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels plot.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels plot.toolbar.logo = None plot.toolbar_location = None # Read in train line data sf = shapefile.Reader("CTA_New/CTA_New") features = sf.shapeRecords() Lines = [] Coords_x = [] Coords_y = [] for shape in features: Line = shape.record[5] Coord = shape.shape.points X_s = [] Y_s = [] for coord in Coord: Trans = merc(tuple(reversed(coord))) X_s.append(Trans[0]) Y_s.append(Trans[1]) Coords_x.append(X_s) Coords_y.append(Y_s) CTA_Lines = ['Red', 'G', 'Blue', 'P', 'Brn', 'Pink', 'Org', 'Y'] # Set up data sources # - Live CTA Data source = AjaxDataSource(data_url=request.url_root + 'cta_data/', polling_interval=5000, mode='replace') source.data = dict(x=[], y=[], next_station=[], destination=[], direction=[], color=[], line_name=[]) # - Station Coordinate Data L_Map = pd.read_csv('Stations.csv') station_source = ColumnDataSource( dict(x=L_Map['coords_x'], y=L_Map['coords_y'], name=L_Map['STATION_NAME'])) # Color Map for trains color_mapper = CategoricalColorMapper(factors=CTA_Lines, palette=[ 'Red', 'Green', 'Blue', 'Purple', 'Brown', 'Pink', 'Orange', 'Yellow' ]) # Plot Glyphs for i in range(len(Coords_x)): plot.line(x=Coords_x[i], y=Coords_y[i], line_color="black", alpha=0.7) stations = plot.circle(x='x', y='y', source=station_source, size=5, line_color="black", fill_color='white') circles = plot.circle(x='x', y='y', angle='heading', source=source, color={ 'field': 'color', 'transform': color_mapper }, size=14, line_color="black", line_width=0.8, legend='line_name') triangles = plot.triangle(x='x', y='y', angle='heading', source=source, size=8, color='white') # Set Up Tools hover = HoverTool(tooltips=[("Next Stop", "@next_station"), ("Destination", "@destination")], renderers=[circles]) station_hover = HoverTool(tooltips=[("Station", "@name")], renderers=[stations]) wheel = WheelZoomTool() plot.add_tools(hover) plot.add_tools(station_hover) plot.add_tools(wheel) plot.toolbar.active_scroll = wheel plot.legend.location = "top_left" script, div = components(plot) return script, div
def ajax_getplot(x, y, y_bottom, ref_value): #fi,ff,y_bottom,ref_value,x,y): # En la ventana del plot graf = figure(tools="save", x_axis_label="Frequency [Hz]", y_axis_label='Power [dBm]', width=700, height=400, sizing_mode='stretch_width', x_range=(x[0], x[-1]), y_range=(float(y_bottom), float(ref_value))) graf.toolbar.logo = None graf.toolbar.active_drag = None graf.toolbar.active_scroll = None graf.yaxis.major_label_text_font_style = 'bold' graf.xaxis.major_label_text_font_style = 'bold' graf.xaxis.axis_label_text_font_style = 'bold' graf.yaxis.axis_label_text_font_style = 'bold' graf.xaxis[0].formatter.use_scientific = True graf.xaxis[0].ticker.desired_num_ticks = 15 graf.yaxis[0].ticker.desired_num_ticks = 10 graf.ygrid.grid_line_alpha = 0.4 graf.ygrid.grid_line_dash = [6, 4] graf.xgrid.grid_line_alpha = 0.4 graf.xgrid.grid_line_dash = [6, 4] # graf.ygrid.minor_grid_line_alpha = 0.1 # graf.ygrid.minor_grid_line_color = 'navy' # graf.xgrid.minor_grid_line_alpha = 0.1 graf.background_fill_color = "black" graf.border_fill_color = "black" graf.border_fill_alpha = 0 graf.xaxis.axis_line_color = "white" graf.yaxis.axis_line_color = "white" props = dict(line_width=4, line_alpha=0.7) # source for (marker_abs, markers [CANT_MARKERS]) source_markers = ColumnDataSource(data={}) # source for table of graf's markers source_table = ColumnDataSource() # strings for table of graf's markers source_table_share = ColumnDataSource( ) # only for share strings of table's rows between graf_adapter.js, checkbox_callback.js ################################################################################################################################################################# # # -------------------------------------------------------------------------------------- # button_height = 30 # button_width = 70 #SLIDER_WIDTH = 500 # px CHECKBOX_WIDTH = 100 # -------------------------------------------------------------------------------------- if x != 0 and y != 0: max_abs_y = max(y) max_abs_x = argmax(y) #x_npa=asarray(x) y_npa = asarray(y) x_axis = linspace(x[0], x[-1], len(x)) else: y_bottom = -100 ref_value = -60 y_npa = asarray([0, 0]) x_axis = [0, 0] max_abs_y = 0 max_abs_x = 0 ################################################################################################################################################################# # Sliders de marcadores # solicitar frecuencias al analizador sliders = [] if x[0] != x[-1]: step = (x[-1] - x[0]) / len(x) if step <= 0: step = 1 init = (max_abs_x * step) + x[0] for i in range(0, CANT_MARKERS): sliders.append( Slider(start=x[0], end=x[-1], value=init, step=step, title="MARKER " + str(i + 1))) else: for i in range(0, CANT_MARKERS): sliders.append( Slider(start=0, end=1, value=0, step=1, title="MARKER " + str(i + 1))) ################################################################################################################################################################# # Tablas de configuracion (las de solo lectura) source_set_an = ColumnDataSource() source_set_gen = ColumnDataSource() source_set_powm = ColumnDataSource() ################################################################################################################################################################# # preparo el marcador movil # ve posibilidad de agregar PointDrawTool de hovertools # http://docs.bokeh.org/en/1.0.0/docs/user_guide/tools.html#click-tap-tools graf.add_tools( HoverTool( tooltips=[ ('frec', '@x{0,0} Hz'), ('amp', '@y dBm'), # use @{ } for field names with spaces ], point_policy='follow_mouse', mode='vline')) with open("static/js/graf_adapter.js", "r") as f: code = f.read() adapter = CustomJS(args=dict(graf=graf, sliders=sliders, source_markers=source_markers, source_table=source_table, source_table_share=source_table_share, source_set_an=source_set_an, source_set_gen=source_set_gen, source_set_powm=source_set_powm), code=code) source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=1000, mode='replace', adapter=adapter) source.data = dict(x=[], y=[], y_bottom=[], ref_value=[], start_freq=[], stop_freq=[]) #, power = [] ) # span = [], center_freq = [], demod_time = [], ref_level = [], # ANALIZADOR # lf_freq = [], lf_level = [], rf_freq = [], rf_level = [], fm_mod_freq = [], am_mod_freq = [],am_mod_index= [],fm_mod_index= [],pm_mod_index= [], power = []) # GENERADOR graf.line('x', 'y', source=source, line_color="cyan") ############################################################################### # maximos relativos max_rel_x = argrelextrema(y_npa, greater) #dato pasado a numpy array ############################################################################### # datos para la tabla de datos info = [] value = [] # tabla de datos source_table.data = dict(x_data=info, y_data=value) source_table_share.data = dict(x_data=info, y_data=value) #source_table = source columns = [ TableColumn(field="x_data", title="Information"), TableColumn(field="y_data", title="Value") ] data_table = DataTable(source=source_table, columns=columns, height=200, width=400) ############################################################################### set_div = Div(text="<b>Current Settings</b>") # tabla de valores seteados actualmente del analizador source_set_an.data = dict( configuration=[ "X scale", "Y scale", "Start freq", "Stop freq", "Span", "Center freq", "Ref level", "Demod time", "Demod type", "Input att", "Resolution BW", "Scale div", "Avg state", "Avg times" ], value=[ "LIN", "LOG", "0.0", "1.0", "1.0", "1.0", "0.0", "0.0", "FM", "10", "100000", "10.0", "WRITe", "1" ], ) columns_set_an = [ TableColumn(field="configuration", title="Analizer"), TableColumn(field="value", title="value"), ] info_table_an = DataTable(source=source_set_an, columns=columns_set_an, width=220, height=180) # tabla de valuees seteados actualmente en el generador source_set_gen.data = dict( configuration=[ "LF state", "LF freq", "LF level", "LF waveform", "RF state", "RF freq", "RF level", "AM state", "AM source", "AM mod freq", "AM mod index", "AM waveform", "Modulation type", "Modulation state", "FM mod freq", "FM mod index", "FM waveform", "PM mod freq", "PM mod index", "PM waveform" ], value=[ "OFF", "0.0", "0.0", "SINE", "0.0", "0.0", "0.0", "OFF", "INT", "0.0", "0.0", "SINE", "FM", "OFF", "0.0", "0.0", "SINE", "0.0", "0.0", "0.0" ], ) columns_set_gen = [ TableColumn(field="configuration", title="Generator"), TableColumn(field="value", title="value"), ] info_table_gen = DataTable(source=source_set_gen, columns=columns_set_gen, width=220, height=180) # tabla de valuees seteados actualmente en el generador source_set_powm.data = dict( configuration=["Duty cycle", "Average"], value=["50", "1"], ) columns_set_powm = [ TableColumn(field="configuration", title="Power meter"), TableColumn(field="value", title="value"), ] info_table_powm = DataTable(source=source_set_powm, columns=columns_set_powm, width=200, height=180) #source_table = source ############################################################################### ## cosas a graficar # source5 = ColumnDataSource(data=dict(x5=[x_axis[max_abs_x]], y5=[max_abs_y])) # source4 = ColumnDataSource(data=dict(x4=[x_axis[max_abs_x]], y4=[max_abs_y])) # source3 = ColumnDataSource(data=dict(x3=[x_axis[max_abs_x]], y3=[max_abs_y])) # source2 = ColumnDataSource(data=dict(x2=[x_axis[max_abs_x]], y2=[max_abs_y])) # source5 = ColumnDataSource(data=dict(x5=[], y5=[])) # source4 = ColumnDataSource(data=dict(x4=[], y4=[])) # source3 = ColumnDataSource(data=dict(x3=[], y3=[])) # source2 = ColumnDataSource(data=dict(x2=[], y2=[])) # marcadores moviles que arrancan en el absolute maximum # l5=graf.circle('x5', 'y5', source=source5, color="lawngreen", line_width=8, line_alpha=0.7 ) # l4=graf.circle('x4', 'y4', source=source4, color="lime", line_width=8, line_alpha=0.7) # l3=graf.circle('x3', 'y3', source=source3, color="yellow", line_width=8, line_alpha=0.7) # l2=graf.circle('x2', 'y2', source=source2, color="blue", line_width=8, line_alpha=0.7) # custom markers #markers_rel_dict = {} markers = [] colors = ["yellow", "red", "pink", "lime"] for i in range(0, CANT_MARKERS): x_label = 'x_mark_' + str(i + 1) y_label = 'y_mark_' + str(i + 1) source_markers.data[x_label] = [x_axis[max_abs_x]] source_markers.data[y_label] = [max_abs_y] markers.append( graf.circle(x_label, y_label, source=source_markers, color=colors[i], line_width=8, line_alpha=0.7)) #l1=graf.circle(x_axis[max_rel_x[0]] , y_npa[max_rel_x[0]], color="yellowgreen", **props) # max abs marker source_markers.data['x_abs'] = [x_axis[max_abs_x]] source_markers.data['y_abs'] = [max_abs_y] marker_abs = graf.circle(x='x_abs', y='y_abs', source=source_markers, color="red", line_width=8, line_alpha=0.7) #marker_abs=graf.circle(x_axis[max_abs_x],max_abs_y, color="green", **props) ############################################################################### # presentacion del maximo #maximo=str('%.2f' % max_abs_y)+"V @ "+str('%.2f' % x_axis[max_abs_x]+" rad") # presentacion de maximos relativos max_rel = ["a" for i in range(len(max_rel_x[0]))] for i in range(len((max_rel_x[0]))): max_rel[i] = (str('%.2f' % y_npa[max_rel_x[0][i]]) + "V @ " + str('%.2f' % x_axis[max_rel_x[0][i]] + " rad")) ############################################################################### # Sliders de marcadores #callback unico para todos los sliders with open("static/js/callback_sm.js", "r") as f: callback_sm_code = f.read() callback_sm = CustomJS(args=dict(source_table=source_table, source=source, source_markers=source_markers, sliders=sliders, markers=markers, graf=graf, props=props), code=callback_sm_code) for i in range(0, CANT_MARKERS): sliders[i].js_on_change('value', callback_sm) ############################################################################### # Acciones relativas a los checkbox checkbox_labels = ["Max. Abs"] # checkbox_labels = ["Max. Abs", "Max. Rel"] checkbox_preset = CheckboxGroup(labels=checkbox_labels, active=[], width=CHECKBOX_WIDTH) checkbox_mark = CheckboxGroup( labels=["Mark 1", "Mark 2", "Mark 3", "Mark 4"], active=[], width=CHECKBOX_WIDTH) #checkbox.active=[] <- indica los índices de los elementos "activados" (para activar el 1: [1], para activar el 0 y el 3: [0 3]) #checkbox.active=[] #checkbox.active[0]=False marker_abs.visible = False #checkbox.active[1]=False for i in range(0, CANT_MARKERS): markers[i].visible = False pass #checkbox_mark.active=[] #checkbox_mark.active[0]=False # marker[i].visible=False #checkbox_mark.active[1]=False # marker[i].visible=False #checkbox_mark.active[2]=False # marker[i].visible=False #checkbox_mark.active[3]=False # marker[i].visible=False ##---------------------------------------------------------------------------## with open("static/js/checkbox_callback.js", "r") as f: checkbox_code = f.read() cjs = CustomJS(args=dict(marker_abs=marker_abs, markers=markers, checkbox_preset=checkbox_preset, checkbox_mark=checkbox_mark, source_table=source_table, source=source, source_markers=source_markers, source_table_share=source_table_share, sliders=sliders), code=checkbox_code) checkbox_preset.js_on_click(cjs) checkbox_mark.js_on_click(cjs) ##---------------------------------------------------------------------------## sliders_col = column(sliders) # Ploteos layout_graf = gridplot([[graf]], sizing_mode='scale_width', toolbar_location="right") layout_widgets = widgetbox(row(checkbox_preset, checkbox_mark, sliders_col, data_table), sizing_mode='scale_width') layout_seteos = widgetbox(row(info_table_an, info_table_gen, info_table_powm), sizing_mode='scale_width') analyzer_layout = layout( [layout_graf, layout_widgets, set_div, layout_seteos], sizing_mode='scale_width') return components(analyzer_layout)
def build_html(): """Build the html, to be served by IndexHandler""" source = AjaxDataSource(data_url='./data', polling_interval=INTERVAL, method='GET') # OHLC plot p = figure(plot_height=400, title='OHLC', sizing_mode='scale_width', tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None, y_axis_location="right", y_axis_label="Price ($)") p.x_range.follow = "end" p.x_range.follow_interval = 100 p.x_range.range_padding = 0 p.line(x='time', y='average', alpha=0.25, line_width=3, color='black', source=source) p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue', source=source) p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2, color='black', source=source) p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source, alpha=0.8) # MACD plot p2 = figure(plot_height=200, title='MACD', sizing_mode='scale_width', x_range=p.x_range, x_axis_label='Time (s)', tools="xpan,xwheel_zoom,xbox_zoom,reset", y_axis_location="right") p2.line(x='time', y='macd', color='darkred', line_width=2, source=source) p2.line(x='time', y='macd9', color='navy', line_width=2, source=source) p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue', alpha=0.5, source=source) # Combine plots together plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000) # Compose html from plots and template script, div = components(plot, theme=theme) html = template.render(resources=CDN.render(), script=script, div=div) return html
def style_main_plot(p, theme='default'): style_axis(p, theme) if theme == 'default': p.background_fill = "white" p.border_fill = "white" elif theme == 'dark': p.background_fill = "#333333" p.border_fill = "#191919" p.grid.grid_line_color = "#4D4D4D" source = AjaxDataSource(data_url='http://localhost:5000/data', polling_interval=1000) # Get the data for the entire time period (so that we can use on th upper plot) url = "http://127.0.0.1:5000/alldata" res = requests.get(url, timeout=20) data = res.json() def create_main_plot(theme): p = figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave", height=500, toolbar_location='right') p.line('Date', 'Price', color='#A6CEE3', source=source) style_main_plot(p, theme)
import numpy as np from datetime import timedelta from functools import update_wrapper, wraps from math import sin from random import random from six import string_types from bokeh.plotting import figure, show, output_file from bokeh.models.sources import AjaxDataSource output_file("ajax_source.html", title="ajax_source.py example") source = AjaxDataSource(data=dict(x=[], y=[]), data_url='http://localhost:5050/data', polling_interval=100) p = figure() p.circle('x', 'y', source=source) p.x_range.follow = "end" 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!") show(p) ######################################################### # Flask server related # # The following code has no relation to bokeh and it's only
class PGMonitor(TemplateView): template_name = 'shdky/pg_monitor.html' from bokeh.layouts import column from bokeh.models import CustomJS, ColumnDataSource, Slider, CDSView, IndexFilter, HoverTool from bokeh.plotting import Figure, output_file, show from bokeh.embed import components from bokeh.models.sources import AjaxDataSource from bokeh.models import DatetimeTickFormatter ### add adatper func to adjust timezone for browsers adapter = CustomJS(code=""" var offset = new Date().getTimezoneOffset()* 60 * 1000; var result = {time: [], AMBIENT_TEMPERATURE: [], AMBIENT_TEMPERATURE_simu: [], AMBIENT_TEMPERATURE_dif: []}; const rps = cb_data.response; for (var i = 0; i < rps.time.length; i++) { result.time.push((rps.time[i]-offset)) } result.AMBIENT_TEMPERATURE = rps.AMBIENT_TEMPERATURE; result.AMBIENT_TEMPERATURE_simu = rps.AMBIENT_TEMPERATURE_simu; result.AMBIENT_TEMPERATURE_dif = rps.AMBIENT_TEMPERATURE_dif; return result """) #source = AjaxDataSource(data_url='https://182.150.63.68:10443/static/test.json',method='GET') # failed #source = AjaxDataSource(data_url='http://localhost:9090/static/test.json',method='GET') # failed, it seems unsuccessful when serving files directly source = AjaxDataSource( data_url='https://182.150.63.68:10443/shdky/pg_ajax', method="GET", polling_interval=5000, adapter=adapter) #source.js_onchange('data', adapter) #data = { # 'x' : [1, 2, 3], # 'y' : [9, 3, 2] # } #source = ColumnDataSource(data=data) p = Figure(plot_width=800, plot_height=300, x_axis_type="datetime", title='AMBIENT_TEMPERATURE') p.line('time', 'AMBIENT_TEMPERATURE', source=source, line_width=2, line_alpha=0.3, line_color="red") p.line('time', 'AMBIENT_TEMPERATURE_simu', source=source, line_width=2, line_alpha=0.3, line_color="blue") p.line('time', 'AMBIENT_TEMPERATURE_dif', source=source, line_width=2, line_alpha=0.3, line_color="yellow") p.title.align = "center" p.yaxis.axis_label = 'AMBIENT_TEMPERATURE' p.xaxis.axis_label = 'TIME' p.xaxis[0].formatter = DatetimeTickFormatter(minutes=["%X"]) layout = column(p) script, div = components(layout) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['script'] = self.script context['div'] = self.div return context
from bokeh.models.sources import RemoteSource, AjaxDataSource import requests import os, glob, json import pandas as pd import numpy as np ### from elasticsearch import Elasticsearch import datetime import pandas as pd #es = Elasticsearch('http://localhost:9200') print('GET DATA') <<<<<<< HEAD all_data = AjaxDataSource(data_url='http://localhost:8000/api/_bokeh_data', method="POST", polling_interval=2000, if_modified=True, mode="replace") # Set up worldmap data # from: https://gist.github.com/tonyfast/994f37c4540ce91c6784 countries = requests.get('https://rawgit.com/johan/world.geo.json/master/countries.geo.json').json() countryObject = {} for country in countries['features']: countryObject[country['properties']['name']] = { 'x': [x[0] for x in country['geometry']['coordinates'][0]], 'y': [x[1] for x in country['geometry']['coordinates'][0]], } worldmapdata = pd.DataFrame(countryObject) ======= all_data = pd.read_json("code/app/data.json")
def get_data_source(url, polling_interval=1000): return AjaxDataSource(data_url=url, polling_interval=polling_interval)