def init_time_series_plot(hover): """ Defaults for time series plot """ plot = Figure( plot_height=400, plot_width=1000, sizing_mode="scale_width", toolbar_location="above", tools="pan, wheel_zoom, xbox_zoom, reset, tap", active_scroll='wheel_zoom', x_axis_type="datetime", min_border_top=0, min_border_right=10, min_border_bottom=50, min_border_left=50, outline_line_color=None, ) plot.add_tools(hover) plot.x_range.follow = "end" plot.x_range.range_padding = 0 plot.xaxis.axis_label = "Time" plot.xaxis.axis_label_text_font_style = "normal" plot.xaxis.axis_label_text_font_size = "14pt" plot.yaxis.axis_label_text_font_style = "normal" plot.yaxis.axis_label_text_font_size = "14pt" return plot
def make_plot(cityData): hover = HoverTool( tooltips=[ ("GDD", "$y"), ("Date", "@dateStr") ] ) TOOLS = [BoxSelectTool(), hover] plot = Figure(x_axis_type="datetime", plot_width=1000, tools=TOOLS) plot.title = "Accumulated GDD of cities of Canada" colors = Spectral11[0:len(cityData)] index = 0 for src in cityData: plot.line(x='date', y='GDD',source=cityData[src], color=colors[index], line_width=4, legend=src) index = index + 1 # plot.quad(top='max', bottom='min', left='left', right='right', color=colors[2], source=src, legend="Record") # fixed attributes plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = None plot.yaxis.axis_label = "Accumulated GDD" plot.axis.major_label_text_font_size = "8pt" plot.axis.axis_label_text_font_size = "8pt" plot.axis.axis_label_text_font_style = "bold" plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def get_bokeh_fig(): from bokeh.plotting import Figure # , gridplot from bokeh.models import ColumnDataSource, HoverTool results, varied_keys, varied_vals = read() include_keys = varied_keys + [ 'nfev', 'njev', 'nprec_setup', 'nprec_solve', 'njacvec_dot', 'nprec_solve_ilu', 'nprec_solve_lu', "n_steps", "n_rhs_evals", "n_lin_solv_setups", "n_err_test_fails", "n_nonlin_solv_iters", "n_nonlin_solv_conv_fails", "krylov_n_lin_iters", "krylov_n_prec_evals", "krylov_n_prec_solves", "krylov_n_conv_fails", "krylov_n_jac_times_evals", "krylov_n_iter_rhs" ] cols = [xkey, ykey, 'color'] + include_keys sources = {} varied3 = varied_vals[2] keys = list(results.keys()) vals = list(results.values()) for val in varied3: sources[val] = ColumnDataSource(data={k: [] for k in cols}) for k in cols: sources[val].data[k] = [vals[idx].get(k, None) for idx in range(len(vals)) if keys[idx][2] == val] hover = HoverTool(tooltips=[(k, '@'+k) for k in include_keys]) top = Figure( plot_height=600, plot_width=800, title="%s vs. %s" % (ykey, xkey), x_axis_type="linear", y_axis_type="log", tools=[ hover, 'pan', 'reset', 'box_zoom', 'wheel_zoom', 'save']) top.xaxis.axis_label = xkey top.yaxis.axis_label = ykey for source, marker in zip(sources.values(), ['circle', 'diamond']): top.scatter(x=xkey, y=ykey, source=source, size=9, color="color", line_color=None, marker=marker) return top
class MapPlot(object): def __init__(self): self.map_plot = Figure( tools="pan,wheel_zoom,tap", toolbar_location="right", logo=None, min_border=0, min_border_left=0, **get_paris_extent(0.6), # x_range & y_range plot_width=1100, plot_height=650) self.map_plot.add_tile(tile_source=OSM_TILE_SOURCE) self.map_plot_renderer = self.map_plot.patches( source=geo_source, xs="xs", ys="ys", line_width=2, line_color=None, selection_line_color="firebrick", nonselection_line_color=None, fill_color="colors", selection_fill_color="colors", nonselection_fill_color="colors", alpha=0.85, selection_alpha=0.9, nonselection_alpha=0.85) self.map_plot.axis.visible = None self.map_plot_ds = self.map_plot_renderer.data_source def get_plot(self): return self.map_plot def get_data_source(self): return self.map_plot_ds
def layout_padding(plots): """ Temporary workaround to allow empty plots in a row of a bokeh GridPlot type. Should be removed when https://github.com/bokeh/bokeh/issues/2891 is resolved. """ widths, heights = defaultdict(int), defaultdict(int) for r, row in enumerate(plots): for c, p in enumerate(row): if p is not None: width = p.plot_width if isinstance(p, Plot) else p.width height = p.plot_height if isinstance(p, Plot) else p.height widths[c] = max(widths[c], width) heights[r] = max(heights[r], height) expanded_plots = [] for r, row in enumerate(plots): expanded_plots.append([]) for c, p in enumerate(row): if p is None: p = Figure(plot_width=widths[c], plot_height=heights[r]) p.text(x=0, y=0, text=[' ']) p.xaxis.visible = False p.yaxis.visible = False p.outline_line_color = None p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None expanded_plots[r].append(p) return expanded_plots
def make_plot(cityData): # Hover option to make the plot interactive hover = HoverTool( tooltips=[ ("GDD", "$y"), ("Date", "@dateStr") ] ) TOOLS = [BoxSelectTool(), hover] plot = Figure(x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools=TOOLS) plot.title = "Accumulated GDD of cities of Canada" colors = Spectral11[0:len(cityData)] index = 0 for src in cityData: plot.line(x='date', y='GDD',source=cityData[src], color=colors[index], line_width=4, legend=src) index = index + 1 plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = "Months" plot.yaxis.axis_label = "Accumulated GDD" plot.axis.major_label_text_font_size = "10pt" plot.axis.axis_label_text_font_size = "12pt" plot.axis.axis_label_text_font_style = "bold" plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def landscape_plot(landscape, states, timesteps, height, width, patch_colors): '''Plot fitness landscape''' from bokeh.plotting import Figure # Append extra state and timestep for index bounds of quad objects states = numpy.append(states, states[-1]+1) timesteps = numpy.append(timesteps, timesteps[-1]+1) # Create points for each cell of grid tops = list() bottoms = list() lefts = list() rights = list() for top, bottom in zip(states[1:], states[:-1]): for left, right in zip(timesteps[:-1], timesteps[1:]): tops.append(top) bottoms.append(bottom) lefts.append(left) rights.append(right) # Create array of color values corresponding to each cell's assoc. patch grid_colors = list() for i in range(len(tops)): idx = (landscape['state']==bottoms[i]) & (landscape['t']==lefts[i]) patch = int(landscape[idx]['patch']) grid_colors.append(patch_colors[patch]) # Create landscape object grid_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) grid_obj.quad(top=tops, bottom=bottoms, left=lefts, right=rights, line_color='black', fill_color=grid_colors) return grid_obj
def init_time_series_plot(hover): """ Defaults for time series plot """ plot = Figure( plot_height=300, plot_width=900, responsive=True, tools="xpan,xwheel_zoom,xbox_zoom,reset,tap", x_axis_type='datetime', min_border_top=0, min_border_right=10, min_border_bottom=50, min_border_left=50, outline_line_color=None, ) plot.add_tools(hover) plot.x_range.follow = "end" plot.x_range.range_padding = 0 plot.xaxis.axis_label = "Time" plot.xaxis.major_label_orientation = pi/4 plot.xaxis.formatter = DatetimeTickFormatter(formats=dict( hours=["%d %B"], days=["%d %B"], months=["%d %B"], years=["%d %B"], )) return plot
def __plot_histogram(self): plot = Figure(plot_height=500, plot_width=300) plot.title.text = 'Histogram' hist_data = self.calc_histogram_data(self.__values) plot.toolbar.logo = None plot.quad(top='hist', bottom=0, left='edges_left', right='edges_right', source=hist_data, fill_color="#036564", line_color="#033649") return plot
def create_figure(): xs, ys, colors, sizes = model.get_axes_values() fig_args = dict(tools='pan', plot_height=600, plot_width=800) if model.x_field in model.discrete_column_names and model.y_field in model.discrete_column_names: figure = Figure(x_range=xs, y_range=ys, **fig_args) figure.axis.major_label_orientation = math.pi / 4 elif model.x_field in model.discrete_column_names: figure = Figure(x_range=xs, **fig_args) figure.xaxis.major_label_orientation = math.pi / 4 elif model.y_field in model.discrete_column_names: figure = Figure(y_range=ys, **fig_args) figure.yaxis.major_label_orientation = math.pi / 4 else: figure = Figure(**fig_args) figure.circle(x=xs, y=ys, color=colors, size=sizes, line_color="white", alpha=0.8) figure.toolbar_location = None figure.xaxis.axis_label = model.x_field figure.yaxis.axis_label = model.y_field figure.background_fill_color = model.background_fill figure.border_fill_color = model.background_fill figure.axis.axis_line_color = "white" figure.axis.axis_label_text_color = "white" figure.axis.major_label_text_color = "white" figure.axis.major_tick_line_color = "white" figure.axis.minor_tick_line_color = "white" figure.axis.minor_tick_line_color = "white" figure.grid.grid_line_dash = [6, 4] figure.grid.grid_line_alpha = .3 return figure
def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'): source = ColumnDataSource(data=initData) selectDOW = Select(title="Days:", value="Monday", options=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]) selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"]) model = dict(source=source, select_dow = selectDOW, select_ut = selectUT) plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime") plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=model, code=""" var dayOfWeek = select_dow.get('value') var userType = select_ut.get('value') var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if(xmlhttp.status == 200){ var data = source.get('data'); var result = JSON.parse(xmlhttp.responseText); var temp=[]; for(var date in result.x) { temp.push(new Date(result.x[date])); } data['x'] = temp; data['y'] = result.y; source.trigger('change'); } else if(xmlhttp.status == 400) { alert(400); } else { alert(xmlhttp.status); } } }; var params = {dow:dayOfWeek, ut:userType}; url = "/select?" + jQuery.param( params ); xmlhttp.open("GET", url, true); xmlhttp.send(); """) selectDOW.callback = callback selectUT.callback = callback layout = vform(selectDOW, selectUT, plot) script, div = components(layout) html = readHtmlFile(fileName) html = insertScriptIntoHeader(html, script) html = appendElementContent(html, div, "div", "bokehContent") return html
def plotnorm(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400): """ Make a light-weight norm figure """ fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs'] if not circleinds: circleinds = range(len(data['snrs'])) source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) for (key, value) in data.iteritems() if key in fields})) norm = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='SNR observed', y_axis_label='SNR expected', tools=tools, webgl=True) norm.circle('abssnr', 'zs', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source) if crossinds: sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds])) for (key, value) in data.iteritems() if key in fields})) norm.cross('abssnr', 'zs', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg) if edgeinds: sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds])) for (key, value) in data.iteritems() if key in fields})) norm.circle('abssnr', 'zs', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2) hover = norm.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')]) if url_path and fileroot: url = '{}/cands_{}[email protected]'.format(url_path, fileroot) taptool = norm.select(type=TapTool) taptool.callback = OpenURL(url=url) return norm
def timeplot(data): #input data is a DataFrame time = pd.DatetimeIndex(data['ltime']) #String list to store column names from the third column of the dataframe columns = [] for x in data.columns[1:]: columns.append(x) #change string to float in the data for x in columns[0:(len(columns)-2)]: if (type(data[x][0]) is str): for i in range(len(data[x])): data[x][i] = float(data[x][i].replace(',','')) output_notebook() y = data[columns[1]] x = time p = Figure(x_axis_type = 'datetime', title = "TimeSeries Plotting") source = ColumnDataSource(data=dict(x=x, y=y, d=data)) #create a new columndatasoure to pass column name to CustomJS source2 = ColumnDataSource(data = dict(columns = columns)) p.line('x', 'y', source = source) p.xaxis.axis_label = "Time" p.yaxis.axis_label = "Selected Y" callback = CustomJS(args = dict(source = source, columns=source2), code=""" var data = source.get('data'); var columns = columns.get('data')['columns']; var f = cb_obj.get('value'); y = data['y']; console.log('y'); console.log(y); var d = data['d']; //get the index of the chosen column from the widget for(i = 0; i<columns.length;i++){ if(f[0]==columns[i]){ index = i; } } //make the column transpose since the CustomJS //takes dataframe as an array of arrays which is //a row of the DataFrame for (i = 0; i < d.length; i++) { y[i] = d[i][index+1]; } console.log('y'); console.log(y.length); source.trigger('change'); """) select = MultiSelect(title="Y_Option:", value=[columns[0]], options=columns, callback=callback) layout = vform(select, p) show(layout)
def makeplot(): p = Figure(plot_width=800, plot_height=200,tools="hover,pan",title=None) p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color='gray', source=source) hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("radius", "@radius")]) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None return p
def plotMap(lat, lon, axis_range): x_offset, y_offset = convLL_XY(lat, lon) x_axis_range = [-axis_range+x_offset, axis_range+x_offset] y_axis_range = [-axis_range+y_offset, axis_range+y_offset] x_range = Range1d(start=x_axis_range[0], end=x_axis_range[1]) y_range = Range1d(start=y_axis_range[0], end=y_axis_range[1]) p = Figure(tools='pan,wheel_zoom', x_range=x_range, y_range=y_range, plot_height=800, plot_width=800) p.axis.visible = False STAMEN_TONER.url = 'http://tile.stamen.com/toner-lite/{Z}/{X}/{Y}.png' p.add_tile(STAMEN_TONER) return p
def __init__(self, N=200): self.document = Document() self.params = {'amplitude': 1, 'frequency': 1, 'phase': 0, 'offset': 0 } self.param_limits = {'amplitude': [-5.0, 5.0, 0.2], 'frequency': [0.1, 5.1, 0.1], 'phase': [0, 2*np.pi, 2*np.pi/50], 'offset': [-5.0, 5.0, 0.1] } keys = self.params.keys() self.selectors = {n: Select(title="Parameter %i" % (n+1), value=keys[n], options=keys) for n in range(2) } self.sliders = {n: Slider(value=self.params[keys[n]], start=self.param_limits[keys[n]][0], end=self.param_limits[keys[n]][1], step=self.param_limits[keys[n]][2] ) for n in range(2) } selection_layout = VBoxForm(children=[VBoxForm(children=[self.selectors[n], self.sliders[n] ] ) for n in range(2) ] ) for slider in self.sliders.values(): slider.on_change('value', self.update_sliders) self.selector_values = {} for num, selector in self.selectors.items(): selector.on_change('value', self.update_selectors) self.selector_values[num] = selector.value self.resetting_selectors = False # keeps from updating plot when we update selection self.N = N self.source = ColumnDataSource() self.update_data() plot = Figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=[0, 4*np.pi], y_range=[-2.5, 2.5] ) plot.line('x', 'y', source=self.source, line_width=3, line_alpha=0.6) self.document.add_root(HBox(selection_layout, plot)) self.session = push_session(self.document)
def prediction(): img_path = os.path.join(os.getcwd(), 'upload_folder', os.listdir('upload_folder')[0]) model_path = os.path.join('models', 'plant_disease.model') binarizer_path = os.path.join('models', 'plant_disease.pickle') # reading only the first image from the upload_folder image = cv2.imread(img_path) output = image.copy() # pre-process the image for classification image = cv2.resize(image, (80, 80)) image = image.astype("float") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) # load the trained convolutional neural network and the label # binarizer print("[INFO] loading network...") model = load_model(model_path) lb = pickle.loads(open(binarizer_path, "rb").read()) # classify the input image print("[INFO] classifying image...") proba = model.predict(image)[0] idx = np.argmax(proba) label = lb.classes_[idx] probability = str(np.max(proba)) # show the output image classes = lb.classes_ source = ColumnDataSource(data=dict(classes=classes, probability=proba, color=Spectral6)) plot_height = 600 plot_width = 800 color_mapper = None # barplot p = Figure(x_range=classes, y_range=(0,1), plot_height=plot_height, plot_width=plot_width, title="Class Probabilites") p.vbar(x='classes', top='probability', width=0.9, source=source) p.xgrid.grid_line_color = None p.xaxis.major_label_orientation = "vertical" p.xaxis.major_label_text_font_style = "italic" p.xaxis.major_label_text_font_size = "12pt" p.yaxis.major_label_text_font_size = "12pt" # image p1 = figure(x_range=(0,1), y_range=(0,1)) print(img_path) p1.image_url(url=[img_path], x=0, y=1, h=1, w=1) # plotting it altogether show(column(p1, p)) # prediction()
def plot(): # Set up data N = 200 x = np.linspace(0, 4*np.pi, N) y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) # Set up plots plot = Figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=[0, 4*np.pi], y_range=[-2.5, 2.5]) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets text = TextInput(title="title", value='my sine wave') offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1) amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0) phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi) freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1) # Set up callbacks def update_title(attrname, old, new): plot.title = 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 = VBoxForm(children=[text, offset, amplitude, phase, freq]) fullformat = HBox(children=[inputs, plot], width=800) return fullformat, []
def create_plot(): axis_range = [-10000000, 10000000] p = Figure(tools='pan,wheel_zoom', x_range=axis_range, y_range=axis_range, plot_height=800, plot_width=800) p.axis.visible = False tile_source = RandomTileSource() tile_source.urls = [] tile_source.attribution = STAMEN_TONER.attribution tile_source.urls.append(STAMEN_TONER.url) tile_source.urls.append('http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png') tile_source.urls.append('http://otile1.mqcdn.com/tiles/1.0.0/sat/{Z}/{X}/{Y}.jpg') p.add_tile(tile_source) return p
def make_plot(): plot = Figure( plot_height=400, plot_width=800, responsive=True, tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type='datetime' ) plot.x_range.follow = "end" plot.x_range.follow_interval = 120 * 24 * 60 * 60 * 1000 plot.x_range.range_padding = 0 plot.y_range = Range1d(0, 12) return plot
def empty_plot(width, height): """ Creates an empty and invisible plot of the specified size. """ x_range = Range1d(start=0, end=1) y_range = Range1d(start=0, end=1) p = Figure(plot_width=width, plot_height=height, x_range=x_range, y_range=y_range) p.xaxis.visible = False p.yaxis.visible = False p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 return p
def createPlot(df, boundaryDF): p = Figure(plot_height=900, plot_width=PLOT_WIDTH, title="", y_range=[], title_text_font_size=TITLE_FONT_SIZE) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None quad = p.quad( top="top", bottom="bottom", left="left", right="right", source=blockSource, fill_color="grey", hover_fill_color="firebrick", fill_alpha=0.05, hover_alpha=0.3, line_color=None, hover_line_color="white", ) p.multi_line(xs="xs", ys="ys", source=blockSource, color="black", line_width=2, line_alpha=0.4, line_dash="dotted") p.multi_line(xs="xs", ys="ys", source=source, color="color", line_width="width", line_alpha="line_alpha") p.add_tools( HoverTool( tooltips=[("chromosome", "@chromosome"), ("exon", "@exon"), ("start", "@start"), ("end", "@end")], renderers=[quad], ) ) return p
def create_component_spec(result_dict): """Generate front end plots of modeling Function that is responsible for generating the front-end spectra plots. Parameters ---------- result_dict : dict the dictionary returned from a PandExo run Returns ------- tuple A tuple containing `(script, div)`, where the `script` is the front-end javascript required, and `div` is a dictionary of plot objects. """ num = -1 color = ["red", "blue", "green", "purple", "black", "yellow", "orange", "pink","cyan","brown"] TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save" plot1 = Figure(plot_width=800, plot_height=350, tools=TOOLS, responsive =False, x_axis_label='Wavelength [um]', x_axis_type="log", y_axis_label='Alpha Lambda', y_range = [min(result_dict['alpha']), max(result_dict['alpha'])]) plot1.line(result_dict['w'], result_dict['alpha'], alpha = 0.5, line_width = 3) plot2 = Figure(plot_width=800, plot_height=350, tools=TOOLS, responsive =False, y_axis_type="log", x_axis_label='Wavelength [um]', x_axis_type="log", y_axis_label='Weighted Cross Section', y_range = [1e-29, 1e-17]) alpha = result_dict['alpha'] squig = result_dict['mols'] xsec = result_dict['xsec'] waves = result_dict['w'] for i in squig.keys(): if i=="H2": num +=1 plot2.line(waves,squig[i]*xsec[i][alpha> 0.0]*squig["H2"], color = color[num], legend = i) elif i=="He": num +=1 plot2.line(waves,squig[i]*xsec[i][alpha> 0.0]*squig["H2"], color = color[num], legend = i) else: num +=1 plot2.line(waves,squig[i]*xsec[i][alpha> 0.0], color = color[num], legend = i) result_comp = components({'plot1':plot1, 'plot2': plot2}) return result_comp
def __init__(self): self.conso_plot = Figure( title="Consommation", toolbar_location="right", tools="pan,box_zoom,wheel_zoom,reset", logo=None, min_border=0, plot_width=1200, plot_height=250, x_axis_type="datetime", x_range=(dates.min(), dates.max()), y_range=(0., conso_bounds[1])) self.sector_renderer = self.conso_plot.line( source=conso_source, x="date", y="conso", color="navy", alpha=0.7, line_width=1.5) self.signal_renderer = self.conso_plot.line( source=conso_source, x="date", y="diff", color="green", alpha=0.7, line_width=2) self.conso_plot.line(source=datetime_source, x="date", y="conso", color="firebrick", line_width=2) self.conso_plot.xaxis[0].formatter = DatetimeTickFormatter( formats=dict( hours=["%d/%m"], days=["%d/%m"], months=["%d/%m"], years=["%d/%m"], ) ) self.conso_plot.xaxis.axis_label = "Date"
def plotConserved(stats): from bokeh.models import HoverTool,ColumnDataSource from bokeh.plotting import Figure width=500 height=500 plot = Figure(title='',title_text_font_size="11pt", plot_width=width, plot_height=height, x_axis_label='identity',y_axis_label='perc_cons', tools="pan, wheel_zoom, resize, hover, reset, save", background_fill="#FAFAFA") x=stats.index for c in stats.columns: print x, stats[c] plot.line(x,stats[c], line_color='blue',line_width=1.5,legend=c) js,html = embedPlot(plot) return html
def performance(): plot = Figure(x_axis_type="datetime", tools="save", toolbar_location=None, plot_width=1000, plot_height=300) l1 = plot.line(x="time", y="power_out", source=source_perfomance, line_color="green", name="local") plot.add_tools(HoverTool(renderers=[l1])) plot.select(dict(type=HoverTool)).tooltips = [("Date", "@hover_time"), ("Performance", "@power_out")] l2 = plot.line(x="time", y="avg_perf", source=source_perfomance, line_color="red", name="global") plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.title = "Plant Performance" return plot
class ColorBar(object): def __init__(self): self.map_colorbar = Figure(tools="", toolbar_location=None, min_border=0, min_border_right=0, plot_width=80, plot_height=650, x_range=(0., 1.), y_range=conso_bounds) self.map_colorbar.xaxis.visible = None self.map_colorbar.grid.grid_line_color = None colorbar_ys = np.linspace(conso_bounds[0], conso_bounds[1], 12) colorbar_colors = scales_to_hex(np.linspace(0., 1., 11)) self.map_colorbar.quad(bottom=colorbar_ys[:-1], top=colorbar_ys[1:], left=0., right=1., fill_color=colorbar_colors, line_color=None, alpha=0.9) def get_plot(self): return self.map_colorbar
def create_legend(self, img, x, y, dw, dh, x_start, x_end, y_range): x_axis_type = 'linear' if self.transfer_function == 'linear' else 'log' legend_fig = Figure(x_range=(x_start, x_end), plot_height=max(dh, 50), plot_width=self.plot_width, lod_threshold=None, toolbar_location=None, y_range=y_range, x_axis_type=x_axis_type) legend_fig.min_border_top = 0 legend_fig.min_border_bottom = 10 legend_fig.min_border_left = 15 legend_fig.min_border_right = 15 legend_fig.yaxis.visible = False legend_fig.grid.grid_line_alpha = 0 legend_fig.image_rgba(image=[img], x=[x], y=[y], dw=[dw], dh=[dh], dw_units='screen') return legend_fig
def __plot_control_chart(self, index): plot_args = self.__conf.plot_args[index] annotations = self.__conf.annotations[index] if not annotations: annotations = PlotAnnotationContainer() plot = Figure(plot_height=500, plot_width=600, x_range=FactorRange(factors=self.__factors, name='x_factors')) plot.toolbar.logo = None plot.title.text = 'Control chart' hover_tool = self.__create_tooltips() plot.add_tools(hover_tool) plot.xaxis.major_label_orientation = pi / 4 plot.xaxis.major_label_standoff = 10 if not self.__values['_calc_value'].empty: if 'color' not in plot_args: plot_args['color'] = 'navy' if 'alpha' not in plot_args: plot_args['alpha'] = 0.5 self.__values['s_fac'] = self.__factors col_ds = ColumnDataSource(self.__values, name='control_data') col_ds.js_on_change('data', CustomJS(code="refresh_maps();")) plot.circle('s_fac', '_calc_value', source=col_ds, name='circle', **plot_args) plot.line('s_fac', '_calc_value', source=col_ds, name='line', **plot_args) min_anno, max_anno = annotations.calc_min_max_annotation( self.__values['_calc_value']) annotations.plot(plot, self.__values['_calc_value']) anno_range = max_anno - min_anno if anno_range and not isnan(anno_range): plot.y_range.start = min_anno - anno_range plot.y_range.end = max_anno + anno_range return plot
def make_plot(src, city): TOOLS = [BoxSelectTool()] global plot plot = Figure(x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools=TOOLS) plot.title = city colors = Blues4[0:3] plot.line(x='date', y='GDD',source=src, line_width=4) plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = "Months" plot.yaxis.axis_label = "Accumulated GDD" plot.axis.major_label_text_font_size = "10pt" plot.axis.axis_label_text_font_size = "12pt" plot.axis.axis_label_text_font_style = "bold" plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
source = ColumnDataSource(data=dict(min_GDD=[], max_GDD=[], mean_GDD=[], q1_GDD=[], q3_GDD=[], time=[], timer=[], timel=[], date_str=[])) # Create Input controls current_year = datetime.today().year min_year = Slider(title="Year Start", start=1900, end=current_year, value=1900, step=1) max_year = Slider(title="Year End", start=1900, end=current_year, value=current_year, step=1) station_IDs_str = TextInput(title="Station ID", value='6551') base_temp = Slider(title="Base Temperature (C)", start=0, end=25, value=10, step=1) # Create Figure and Plot hover = HoverTool(tooltips=[ ("Date","@date_str")]) p = Figure(x_axis_type="datetime", plot_width=800, tools=[hover]) p.quad(top='max_GDD', bottom='min_GDD', left='timel', right='timer', source=source, alpha=0.5, color='mediumslateblue', line_color="black", line_alpha=0.5, legend='Min/Max') p.quad(top='q3_GDD', bottom='q1_GDD', left='timel', right='timer', source=source, alpha=0.5, color='black', line_color="black", line_alpha=0.5, legend='25-75 Percentile') p.line(x='time', y='mean_GDD', source = source, color='red', line_width = 2, alpha=0.8, legend='Average' ) p.x_range = DataRange1d(range_padding=0, bounds=None) p.yaxis.axis_label = "GDD" p.xaxis.axis_label = 'Month' # p.xaxis[0].formatter = DatetimeTickFormatter(formats=dict(days=["%B %d"], months=["%B"], years=["%Y"])) # Select Data based on input info def select_data(): # p.title = p.title + str(' (Wait..)') global station_IDs # Make Stations ID's as a list station_IDs=[]
def periodic_plot(cds, title="Periodic Table", width=PLOT_WIDTH, height=PLOT_HEIGHT, cmap="viridis", showfblock=True, long_version=False, color_mapper=None): """ Create the periodic plot Args: df : DataFrame Pandas DataFrame with the data on elements tile : str Title to appear above the periodic table colorby : str Name of the column containig the colors width : int Width of the figure in pixels height : int Height of the figure in pixels cmap : str Colormap to use, see matplotlib colormaps long_version : bool Show the long version of the periodic table with the f block between the s and d blocks showfblock : bool Show the elements from the f block .. note:: `property` attribute holds the current property to be displayed """ fig = Figure(title=title, x_axis_location="above", x_range=(0.5, 18.5), y_range=(10.0, 0.5), plot_width=width, plot_height=height, tools="box_zoom,pan,resize,save,reset", toolbar_location="above", toolbar_sticky=False, ) if color_mapper is None: color_dict = "#1F77B4" else: color_dict = {"field": "value", "transform": color_mapper} fig.rect("x", "y", 0.9, 0.9, source=cds, fill_alpha=0.6, fill_color=color_dict, line_color=color_dict) # adjust the ticks and axis bounds fig.yaxis.bounds = (1, 7) fig.axis[1].ticker.num_minor_ticks = 0 fig.axis[0].ticker = FixedTicker(ticks=list(range(1, 19))) text_props = { "source": cds, "angle": 0, "color": "black", "text_align": "center", "text_baseline": "middle" } fig.text(x="x", y="y_symbol", text="symbol", text_font_style="bold", text_font_size="15pt", **text_props) fig.text(x="x", y="y_anumber", text="atomic_number", text_font_size="9pt", **text_props) fig.text(x="x", y="y_name", text="name", text_font_size="7pt", **text_props) fig.text(x="x", y="y_prop", text="value_str", text_font_size="8pt", **text_props) fig.grid.grid_line_color = None hover = HoverTool(tooltips=HOVER_TOOLTIPS) fig.add_tools(hover) return fig
def correlation(): "the scatter plot" args = flask.request.args xattr = args.get("x", "atomic_number") yattr = args.get("y", "covalent_radius_pyykko") categ = args.get("categ", "name_series") data = get_data() properties = get_property_names(data) categories = get_category_names() fig = Figure(title="{} vs {}".format(properties[xattr], properties[yattr]), plot_width=PLOT_WIDTH, plot_height=PLOT_HEIGHT, tools="box_zoom,pan,resize,save,reset", toolbar_location="above", toolbar_sticky=False, ) fig.xaxis.axis_label = properties[xattr] fig.yaxis.axis_label = properties[yattr] ccm = get_color_mapper(categ, data) if categ == "None": legend = None color_dict = "#1F77B4" else: legend = categ color_dict = {"field": categ, "transform": ccm} fig.circle(x=xattr, y=yattr, fill_alpha=0.7, size=10, source=ColumnDataSource(data=data), fill_color=color_dict, line_color=color_dict, legend=legend) if categ != "None": fig.legend.location = (0, 0) fig.legend.plot = None fig.add_layout(fig.legend[0], "right") hover = HoverTool(tooltips=HOVER_TOOLTIPS) fig.add_tools(hover) script, div = components(fig) js_resources = INLINE.render_js() css_resources = INLINE.render_css() html = render_template( "correlations.html", plot_script=script, plot_div=div, properties=properties, categories=categories, xselected=xattr, yselected=yattr, catselected=categ, js_resources=js_resources, css_resources=css_resources, ) return encode_utf8(html)
def __init__(self, fig: Figure): """ Constructs a new PassGeneratorPlotter associated to fig. :param fig: A Bokeh figure """ self.fig = fig self.zones_source = ColumnDataSource( dict(center_xs=[], center_ys=[], widths=[], heights=[])) self.fig.rect( source=self.zones_source, x="center_xs", y="center_ys", width="widths", height="heights", fill_alpha=0, line_color="blue", line_width=1.2, legend_label="Pass Generator zones", ) self.passes_source = ColumnDataSource( dict( receiver_xs=[], receiver_ys=[], pass_line_xs=[], pass_line_ys=[], pass_rating=[], line_width=[], )) self.pass_color_mapper = LinearColorMapper(palette=mpl["Plasma"][256], low=0, high=1) color_bar = ColorBar( color_mapper=self.pass_color_mapper, width=8, height=400, location="bottom_right", title="Pass rating", ) self.fig.add_layout(color_bar, "right") self.fig.multi_line( source=self.passes_source, xs="pass_line_xs", ys="pass_line_ys", line_width="line_width", line_color=dict(field="pass_rating", transform=self.pass_color_mapper), ) receiver_point_glyph = self.fig.circle_cross( source=self.passes_source, x="receiver_xs", y="receiver_ys", size=10, fill_alpha=0.0, legend_label="Receiver points", ) pass_rating_tooltip = ("Pass rating", "@pass_rating") hover_tool = HoverTool(tooltips=[pass_rating_tooltip], renderers=[receiver_point_glyph]) fig.add_tools(hover_tool)
def plot(width, height): ###################################################################################################################### source_normal = ColumnDataSource(data = get_normal(0,1,10000)) plot_normal = Figure(plot_width = width, plot_height = height, x_range = (-6,6), title = 'Normal') plot_normal.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_normal, fill_color="navy") def update_plot_normal(attrname, old , new): source_normal.data = get_normal(mu_slider.value, sigma_slider.value, 100000) mu_slider = Slider(start = -5, end = 5, value = 0, step = 0.2, title = 'Mean') mu_slider.on_change('value', update_plot_normal) sigma_slider = Slider(start = 0.1, end = 5, value = 1, step = 0.2, title = 'Std_Dev') sigma_slider.on_change('value', update_plot_normal) ###################################################################################################################### source_weibull = ColumnDataSource(data = get_weibull(1.5, 1, 10000)) plot_weibull = Figure(plot_width = width, plot_height = height, x_range = (0,6), title = 'Weibull') plot_weibull.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_weibull, fill_color="navy") def update_plot_weibull(attrname, old , new): source_weibull.data = get_weibull(shape_slider.value,lambda_slider.value,100000) shape_slider = Slider(start = 0.4, end = 5, value = 1.5, step = 0.1, title = 'Shape a') shape_slider.on_change('value', update_plot_weibull) lambda_slider = Slider(start = 0.5, end = 3, value = 1, step = 0.5, title = 'Lambda') lambda_slider.on_change('value', update_plot_weibull) ###################################################################################################################### source_lognormal = ColumnDataSource(data = get_lognormal(0.9, 0.16, 10000)) plot_lognormal = Figure(plot_width = width, plot_height = height, title = 'Lognormal', y_range=(0,2), x_range = (0,10)) plot_lognormal.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_lognormal, fill_color="navy") def update_plot_lognormal(attrname, old , new): source_lognormal.data = get_lognormal(mean_slider_lognormal.value, sigma_slider_lognormal.value,100000) mean_slider_lognormal = Slider(start = 0, end = 5, value =0.9, step = 0.1, title = 'Mean') mean_slider_lognormal.on_change('value', update_plot_lognormal) sigma_slider_lognormal = Slider(start = 0.01, end = 1, value = 0.16, step = 0.01, title = 'Std_dev') sigma_slider_lognormal.on_change('value', update_plot_lognormal) ###################################################################################################################### source_exponential = ColumnDataSource(data = get_exponential(3, 1000)) plot_exponential = Figure(plot_width = width, plot_height = height, title = 'Exponential', x_range=(0,50), y_range =(0,1) ) plot_exponential.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_exponential, fill_color="green") def update_plot_exponential(attrname, old , new): source_exponential.data = get_exponential(scale_slider_exponential.value, 10000) scale_slider_exponential = Slider(start = 0.1, end = 10, value = 3, step = 0.1, title = 'Scale') scale_slider_exponential.on_change('value', update_plot_exponential) layout1 = column(plot_normal, column(mu_slider, sigma_slider)) layout2 = column(plot_weibull, column(shape_slider, lambda_slider)) layout3 = column(plot_lognormal, column(mean_slider_lognormal, sigma_slider_lognormal)) layout4 = column(plot_exponential, scale_slider_exponential) top = row(layout1, layout2) bottom = row(layout3, layout4) return (row(top, bottom))
source.data = dict(x=xs, y=ys) except ValueError: pass # default values phi = np.linspace(-30.0, 30.0, 1000) xs = 1.0 * phi - 2.0 * np.sin(phi) ys = 1.0 - 2.0 * np.cos(phi) source = ColumnDataSource(data=dict(x=xs, y=ys)) plot = Figure(plot_width=800, title='Lab1', x_range=(-20, 20), y_range=(-10, 10), tools='crosshair,pan,reset,wheel_zoom', active_scroll='wheel_zoom', toolbar_location=None, x_axis_label='x', y_axis_label='y') plot.line(x='x', y='y', source=source, line_width=2, line_color='green', legend='x = a*phi - b*sin(phi) y = a - b*cos(phi)') a = TextInput(title='a', value='1.0') b = TextInput(title='b', value='2.0') A = TextInput(title='A', value='-30.0') B = TextInput(title='B', value='30.0')
def make_axis(axis, size, factors, dim, flip=False, rotation=0, label_size=None, tick_size=None, axis_height=35): factors = list(map(dim.pprint_value, factors)) nchars = np.max([len(f) for f in factors]) ranges = FactorRange(factors=factors) ranges2 = Range1d(start=0, end=1) axis_label = dim_axis_label(dim) reset = "range.setv({start: 0, end: range.factors.length})" ranges.callback = CustomJS(args=dict(range=ranges), code=reset) axis_props = {} if label_size: axis_props['axis_label_text_font_size'] = value(label_size) if tick_size: axis_props['major_label_text_font_size'] = value(tick_size) tick_px = font_size_to_pixels(tick_size) if tick_px is None: tick_px = 8 label_px = font_size_to_pixels(label_size) if label_px is None: label_px = 10 rotation = np.radians(rotation) if axis == 'x': align = 'center' # Adjust height to compensate for label rotation height = int(axis_height + np.abs(np.sin(rotation)) * ((nchars * tick_px) * 0.82)) + tick_px + label_px opts = dict(x_axis_type='auto', x_axis_label=axis_label, x_range=ranges, y_range=ranges2, plot_height=height, plot_width=size) else: # Adjust width to compensate for label rotation align = 'left' if flip else 'right' width = int(axis_height + np.abs(np.cos(rotation)) * ((nchars * tick_px) * 0.82)) + tick_px + label_px opts = dict(y_axis_label=axis_label, x_range=ranges2, y_range=ranges, plot_width=width, plot_height=size) p = Figure(toolbar_location=None, tools=[], **opts) p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 if axis == 'x': p.yaxis.visible = False axis = p.xaxis[0] if flip: p.above = p.below p.below = [] p.xaxis[:] = p.above else: p.xaxis.visible = False axis = p.yaxis[0] if flip: p.right = p.left p.left = [] p.yaxis[:] = p.right axis.major_label_orientation = rotation axis.major_label_text_align = align axis.major_label_text_baseline = 'middle' axis.update(**axis_props) return p
def integration_with_sliders( rsys, tend, c0, parameters, fig_kwargs=None, slider_kwargs=None, conc_bounds=None, x_axis_type="linear", y_axis_type="linear", integrate_kwargs=None, odesys_extra=None, get_odesys_kw=None, integrate=None, ): """ Parameters ---------- rsys : ReactionSystem tend : float like c0 : dict Initial concentrations. parameters : dict Parameter values. fig_kwargs : dict Keyword-arguments passed to bokeh's ``Figure``. slider_kwargs : dict Keyword-arguments passed to bokeh's ``Slider``. conc_bounds : dict of dicts Mapping substance key to dict of bounds ('start', 'end', 'step'). x_axis_type : str y_axis_type : str integrate_kwargs : dict Keyword-arguments passed to integrate. odesys_extra : tuple If odesys & extra have already been generated (avoids call to ``get_odesys``). get_odesys_kw : dict Keyword-arguments passed to ``get_odesys``. integrate : callback Defaults to ``odesys.integrate``. """ import numpy as np from bokeh.plotting import Figure from bokeh.models import ColumnDataSource, Column, Row from bokeh.models.widgets import Slider if slider_kwargs is None: slider_kwargs = {} if get_odesys_kw is None: get_odesys_kw = {} if odesys_extra is None: odesys, extra = get_odesys(rsys, **get_odesys_kw) else: odesys, extra = odesys_extra if integrate is None: integrate = odesys.integrate state_keys, rarg_keys, p_units = [ extra[k] for k in ("param_keys", "unique", "p_units") ] output_conc_unit = get_odesys_kw.get("output_conc_unit", None) output_time_unit = get_odesys_kw.get("output_time_unit", None) unit_registry = get_odesys_kw.get("unit_registry", None) if output_conc_unit is None: if unit_registry is not None: raise ValueError( "if unit_registry is given, output_conc_unit must also be given" ) output_conc_unit = 1 if output_time_unit is None: if unit_registry is not None: raise ValueError( "if unit_registry is given, output_time_unit must also be given" ) output_conc_unit = 1 param_keys = list(chain(state_keys, rarg_keys)) if x_axis_type == "linear": tout = linspace(tend * 0, tend) elif x_axis_type == "log": tout = logspace_from_lin(tend * 1e-9, tend) else: raise NotImplementedError("Unknown x_axis_type: %s" % x_axis_type) result = integrate(tout, c0, parameters, **(integrate_kwargs or {})) sources = [ ColumnDataSource( data={ "tout": to_unitless(result.xout, output_time_unit), k: to_unitless(result.yout[:, idx], output_conc_unit), }) for idx, k in enumerate(rsys.substances) ] if fig_kwargs is None: Cmax = np.max(result.yout) x_range = list( to_unitless([result.xout[0], result.xout[-1]], output_time_unit)) y_range = list(to_unitless([Cmax * 0, Cmax * 1.1], output_conc_unit)) fig_kwargs = dict( plot_height=400, plot_width=400, title="C vs t", tools="crosshair,pan,reset,save,wheel_zoom", x_range=x_range, y_range=y_range, x_axis_type=x_axis_type, y_axis_type=y_axis_type, ) plot = Figure(**fig_kwargs) colors = "red green blue black cyan magenta".split() for idx, k in enumerate(rsys.substances): plot.line( "tout", k, source=sources[idx], line_width=3, line_alpha=0.6, color=colors[idx % len(colors)], ) def _C(k): return to_unitless(c0[k], output_conc_unit) if p_units is None: p_units = [None] * len(param_keys) p_ul = [ to_unitless(parameters[k], _u) for k, _u in zip(param_keys, p_units) ] def _dict_to_unitless(d, u): return {k: to_unitless(v, u) for k, v in d.items()} c0_widgets = OrderedDict() for k in rsys.substances: if conc_bounds is not None and k in conc_bounds: if k in slider_kwargs: raise ValueError( "Key '%s' both in slider_kwargs and conc_bounds" % k) slider_defaults = _dict_to_unitless(conc_bounds[k], output_conc_unit) else: ck = _C(k) if ck == 0: max_ = max(*[_C(k) for k in rsys.substances]) slider_defaults = dict(start=0, end=max_, step=max_ / 100) else: slider_defaults = dict(start=_C(k) / 2, end=_C(k) * 2, step=_C(k) / 10) c0_widgets[k] = Slider( title=(k + " / " + output_conc_unit.dimensionality.unicode) if hasattr(output_conc_unit, "dimensionality") else k, value=_C(k), **slider_kwargs.get(k, slider_defaults)) param_widgets = OrderedDict([( k, Slider(title=k if u is None else k + " / " + u.dimensionality.unicode, value=v, **_dict_to_unitless( slider_kwargs.get( k, dict(start=v / 10, end=v * 10, step=v / 10)), u, )), ) for k, v, u in zip(param_keys, p_ul, p_units)]) all_widgets = list(chain(param_widgets.values(), c0_widgets.values())) def update_data(attrname, old, new): _c0 = defaultdict(lambda: 0 * output_conc_unit) for k, w in c0_widgets.items(): _c0[k] = w.value * output_conc_unit _params = {} for (k, w), u in zip(param_widgets.items(), p_units): _params[k] = w.value if u is None else w.value * u _result = integrate(tout, _c0, _params) for idx, k in enumerate(rsys.substances): sources[idx].data = { "tout": to_unitless(_result.xout, output_time_unit), k: to_unitless(_result.yout[:, idx], output_conc_unit), } for w in all_widgets: w.on_change("value", update_data) inputs = Column(children=all_widgets) return Row(children=[inputs, plot], width=800)
def scatter( figure: Figure, x: List[DataType], y: List[DataType], smiles: Dict[str, tuple], legend_label: Optional[str] = None, marker: Optional[str] = None, marker_size: Optional[int] = None, marker_color: Optional[str] = None, **kwargs: Dict[str, Any], ): """Adds a scatter series to a bokeh figure which will show the molecular structure associated with a data point when the user hovers over it. Args: figure: The bokeh figure to plot the scatter data on. x: An array of the x values to plot. y: An array of the y values to plot. smiles: An array of the SMILES patterns associated with each (x, y) pair. legend_label: The label to show in the legend for this data series. marker: The marker style. marker_size: The size of the marker to draw. marker_color: The marker color. kwargs: Extra keyword arguments to pass to the underlying bokeh ``scatter`` function. """ # Validate the sizes of the input arrays. data_sizes = {"x": len(x), "y": len(y), "smiles": len(smiles)} if len({*data_sizes.values()}) != 1: raise InputSizeError(data_sizes) makevalid = lambda x: x if x.find('_') < 0 else x[:x.find('_')] # Generate an image for each SMILES pattern. raw_images = [] xvalid = [] yvalid = [] smivalid = [] for (smiles_pattern, torsion_indices), x_, y_ in zip(smiles.items(), x, y): try: img = base64.b64encode(smiles_to_svg(makevalid(smiles_pattern), torsion_indices).encode()).decode() raw_images.append(img) xvalid.append(x_) yvalid.append(y_) smivalid.append(smiles_pattern) except rdkit.Chem.rdchem.AtomValenceException: print(f"AtomicValenceException for smiles {makevalid(smiles_pattern)} with torsions {torsion_indices}") continue images = [f"data:image/svg+xml;base64,{raw_image}" for raw_image in raw_images] # Create a custom data source. source = ColumnDataSource(data={"x": xvalid, "y": yvalid, "smiles": smivalid, "image": images}) # Add the scatter data. scatter_kwargs = {**kwargs} if marker is not None: scatter_kwargs["marker"] = marker if marker_size is not None: scatter_kwargs["size"] = marker_size if marker_color is not None: scatter_kwargs["color"] = marker_color if legend_label is not None: scatter_kwargs["legend_label"] = legend_label figure.scatter(x="x", y="y", source=source, **scatter_kwargs)
class SliderApp: def __init__(self): # Set up data self.N = 200 x = np.linspace(0, 4 * np.pi, self.N) y = np.sin(x) self.source = ColumnDataSource(data=dict(x=x, y=y)) # Set up plot self.plot = Figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=[0, 4 * np.pi], y_range=[-2.5, 2.5]) self.plot.line('x', 'y', source=self.source, line_width=3, line_alpha=0.6) # Set up widgets self.text = TextInput(title="title", name='title', value='my sine wave') self.offset = Slider(title="offset", name='offset', value=0.0, start=-5.0, end=5.0, step=0.1) self.amplitude = Slider(title="amplitude", name='amplitude', value=1.0, start=-5.0, end=5.0) self.phase = Slider(title="phase", name='phase', value=0.0, start=0.0, end=2 * np.pi) self.freq = Slider(title="frequency", name='frequency', value=1.0, start=0.1, end=5.1) self.text.on_change('value', self.update_title) for w in [self.offset, self.amplitude, self.phase, self.freq]: w.on_change('value', self.update_data) def get_app(self): # Set up layouts and add to document inputs = VBoxForm(children=[ self.text, self.offset, self.amplitude, self.phase, self.freq ]) hbox = HBox(children=[inputs, self.plot]) return hbox # Set up callbacks def update_title(self, attrname, old, new): self.plot.title = self.text.value def update_data(self, attrname, old, new): # Get the current slider values a = self.amplitude.value b = self.offset.value w = self.phase.value k = self.freq.value # Generate the new curve x = np.linspace(0, 4 * np.pi, self.N) y = a * np.sin(k * x + w) + b self.source.data = dict(x=x, y=y)
sample_peorid = 'W' smoothing_window = 5 #Load Data df = pd.read_pickle('/home/ubuntu/data/jacksonville_2014_2017.pkl') df = df.remove_columns(df) resample_df = df.resample(sample_peorid).sum() materals = get_materal_cluster(resample_df) slider_smoothing = Slider(start=2, end=9, step=1, value=smoothing_window, title="Smoothing Window") p = Figure(title="Clustered Materals", plot_height=500, plot_width=650) df_source = ColumnDataSource( data=dict(x=resample_df[materals[0]], y=resample_df.index)) p.line(x='x', y='y', source=df_source) df_source.data = dict(x=resample_df[materals[0]], y=resample_df.index) grid = girdplot() def get_materal_cluster(df): rolling_df = df.rolling(window=smoothing_window, center=True) rolling_df = rolling_df.mean() rm = round(smoothing_window / 2)
def __init__(self, controller): """Method sets up object. First part of two-part initialization.""" self.controller = controller # Header for section to get file self.file_header =\ Div(text="""<span style='font-weight:bold'>""" """Choose the file to display</span>""", sizing_mode='stretch_width') # Selects the data file to read into the system self.select_file = FileInput(accept=".csv", sizing_mode='stretch_width') # Shows summary and status for data read in. self.status = Div(text="""No file connected""", sizing_mode='stretch_width') # Chart to show temperature and/or humidity. self.temphumidity = Figure(x_axis_type='datetime', title="Humidity & temperature by datetime", x_axis_label='Datetime', y_axis_label='Temperature (C)') df = pd.DataFrame({ 'Timestamp': [pd.to_datetime('4/12/2016 8:15:33 AM')], 'Temperature (C)': [25.0], 'Relative humidity (%)': [40.0] }) self.cds = ColumnDataSource(df) self.temphumidity.line(x='Timestamp', y='Temperature (C)', line_color='red', legend_label='Temperature (C)', line_width=2, line_alpha=0.5, source=self.cds) self.temphumidity.extra_y_ranges = \ {"humidity": Range1d(start=0, end=100)} self.temphumidity.add_layout( LinearAxis(y_range_name="humidity", axis_label='Humidity (%)'), 'right') self.temphumidity.line(x='Timestamp', y='Relative humidity (%)', legend_label='Relative humidity (%)', line_color='blue', line_width=2, line_alpha=0.5, source=self.cds, y_range_name="humidity") self.temphumidity.legend.click_policy = "hide" self.temphumidity.title.text_font_size = '20px' self.temphumidity.xaxis.axis_label_text_font_size = '15px' self.temphumidity.xaxis.major_label_text_font_size = '15px' self.temphumidity.yaxis.axis_label_text_font_size = '15px' self.temphumidity.yaxis.major_label_text_font_size = '15px' # Layout self.layout = row(children=[ column(children=[self.file_header, self.select_file, self.status], sizing_mode='fixed', width=250, height=80), column(self.temphumidity, sizing_mode='stretch_both') ], sizing_mode='stretch_both') self.panel = Panel(child=self.layout, title='Read & display')
class ReadDisplay(): """Reads data saved to file into the system and displays it.""" # %% def __init__(self, controller): """Method sets up object. First part of two-part initialization.""" self.controller = controller # Header for section to get file self.file_header =\ Div(text="""<span style='font-weight:bold'>""" """Choose the file to display</span>""", sizing_mode='stretch_width') # Selects the data file to read into the system self.select_file = FileInput(accept=".csv", sizing_mode='stretch_width') # Shows summary and status for data read in. self.status = Div(text="""No file connected""", sizing_mode='stretch_width') # Chart to show temperature and/or humidity. self.temphumidity = Figure(x_axis_type='datetime', title="Humidity & temperature by datetime", x_axis_label='Datetime', y_axis_label='Temperature (C)') df = pd.DataFrame({ 'Timestamp': [pd.to_datetime('4/12/2016 8:15:33 AM')], 'Temperature (C)': [25.0], 'Relative humidity (%)': [40.0] }) self.cds = ColumnDataSource(df) self.temphumidity.line(x='Timestamp', y='Temperature (C)', line_color='red', legend_label='Temperature (C)', line_width=2, line_alpha=0.5, source=self.cds) self.temphumidity.extra_y_ranges = \ {"humidity": Range1d(start=0, end=100)} self.temphumidity.add_layout( LinearAxis(y_range_name="humidity", axis_label='Humidity (%)'), 'right') self.temphumidity.line(x='Timestamp', y='Relative humidity (%)', legend_label='Relative humidity (%)', line_color='blue', line_width=2, line_alpha=0.5, source=self.cds, y_range_name="humidity") self.temphumidity.legend.click_policy = "hide" self.temphumidity.title.text_font_size = '20px' self.temphumidity.xaxis.axis_label_text_font_size = '15px' self.temphumidity.xaxis.major_label_text_font_size = '15px' self.temphumidity.yaxis.axis_label_text_font_size = '15px' self.temphumidity.yaxis.major_label_text_font_size = '15px' # Layout self.layout = row(children=[ column(children=[self.file_header, self.select_file, self.status], sizing_mode='fixed', width=250, height=80), column(self.temphumidity, sizing_mode='stretch_both') ], sizing_mode='stretch_both') self.panel = Panel(child=self.layout, title='Read & display') # %% def setup(self): """Method sets up object. Second part of two-part initialization.""" self.select_file.on_change("value", self.callback_select_file) # %% def update(self): """Method updates object.""" pass # %% def callback_select_file(self, attrname, old, new): """Callback method for select file""" self.status.text = 'Reading in the data file....' # Convert the data to a Pandas dataframe convert = BytesIO(base64.b64decode(self.select_file.value)) df = pd.read_csv(convert) # Check the Pandas dataframe has the correct fields if set(df.columns) != set([ 'Timestamp', 'Temperature (C)', 'Relative humidity (%)', 'Pressure (Pa)' ]): self.status.text = ( """The file {0} has the columns {1} """ """when it should have the columns {2} """.format( self.select_file.filename, set(df.columns), set([ 'Timestamp', 'Temperature (C)', 'Relative humidity (%)', 'Pressure (Pa)' ]))) return # Make sure the data types are correct df['Timestamp'] = pd.to_datetime(df['Timestamp']) self.cds.data = { 'Timestamp': df['Timestamp'], 'Temperature (C)': df['Temperature (C)'], 'Relative humidity (%)': df['Relative humidity (%)'] } self.status.text = 'Read in the data file correctly.'
if (typeof throttle != 'undefined' && throttle != null) { clearTimeout(throttle); } throttle = setTimeout(update_dims, 100, "replace"); """ # Create plot ------------------------------- xmin = -8240227.037 ymin = 4974203.152 xmax = -8231283.905 ymax = 4979238.441 fig = Figure(x_range=(xmin, xmax), y_range=(ymin, ymax), plot_height=600, plot_width=900, tools='pan,wheel_zoom') fig.background_fill_color = 'black' fig.add_tile(get_provider("STAMEN_TONER"), alpha=.3) fig.x_range.callback = CustomJS(code=dims_jscode, args=dict(plot=fig, dims=dims)) fig.y_range.callback = CustomJS(code=dims_jscode, args=dict(plot=fig, dims=dims)) fig.axis.visible = False fig.grid.grid_line_alpha = 0 fig.min_border_left = 0 fig.min_border_right = 0 fig.min_border_top = 0 fig.min_border_bottom = 0
################ # Data Sources # ################ function_source = ColumnDataSource(data=dict(t=[], y=[])) WaveLet_source = ColumnDataSource(data={'a': [], 'b': [], 'W': []}) Wavelet_Function_source = ColumnDataSource(data=dict(t=[], y=[])) global_var = dict(wavelet_plot=None, wavelet_func_legend='') ########### # FIGURES # ########### toolset = ["save, wheel_zoom, reset"] plot_function = Figure(x_range=(0, 5), y_range=(-3, 3), x_axis_label='t', y_axis_label='f(t)', tools=toolset, title="Function in the Original Domain", width=650, height=300) plot_function.toolbar.logo = None plot_Wavelet = Figure(x_range=(0, 5), y_range=(0, 5), x_axis_label='b', y_axis_label='a', tools=toolset, title="Wavelet Transform of the Function", width=650, height=300) plot_Wavelet.toolbar.logo = None color_mapper = LinearColorMapper(palette=cc.palette.CET_R2)
evhys.append(snhy) rangepts = 100 raseps = 24 decseps = 18 rarange = [-pi + i * 2.0 * pi / rangepts for i in range(0, rangepts + 1)] decrange = [-pi / 2.0 + i * pi / rangepts for i in range(0, rangepts + 1)] ragrid = [-pi + i * 2.0 * pi / raseps for i in range(0, raseps + 1)] decgrid = [-pi / 2.0 + i * pi / decseps for i in range(0, decseps + 1)] tt = [("Event", "@event"), ("R.A. (deg)", "@ra{1.111}"), ("Dec. (deg)", "@dec{1.111}"), ("Claimed type", "@claimedtype")] p1 = Figure( title=moduletitle + ' Positions', # responsive = True, tools=tools, plot_width=990, x_range=(-1.05 * (2.0**1.5), 1.05 * 2.0**1.5), y_range=(-1.4 * sqrt(2.0), 1.0 * sqrt(2.0))) p1.axis.visible = False p1.outline_line_color = None p1.xgrid.grid_line_color = None p1.ygrid.grid_line_color = None p1.title.text_font_size = '20pt' p1.title.align = 'center' raxs = [] rays = [] for rg in ragrid: raxs.append([ 2.0**1.5 * cos(x) * sin(rg / 2.0) / sqrt(1.0 + cos(x) * cos(rg / 2.0))
the guess column or not. Stride factors add a complication as they were not dealt within Cadence. The trackway curve projection algorithm results were used to determine stride factors by looking at the tracks found between each track and the subsequent track in the series. The presence of multiple tracks for another foot in the trackway indicates a stride factor greater than 1. The results are plotted below. To improve the plot value, the stride length ratio was plotted instead of the stride length. The stride length ratio is the stride length normalized by the width of the foot. This reduces value spread due to size of the animal, which would be an undesirable artificat in this plot. """) figure = Figure(title='Stride Length Ratio versus Stride Factors', x_axis_label='Stride Factor (#)', y_axis_label='Stride Length Ratio (#)') def add_scatter(pes: bool, color: str, guess_color: str): indices = [43, 44, 45] if pes else [58, 59, 60] names = [csv_columns[i].name for i in indices] df_slice = pd.merge(df_out[df[names[0]].notnull()], df_tracks[['uid', 'width']], how='left', on='uid') figure.scatter(df_slice[names[-1]], df_slice[names[0]] / df_slice['width'], color=color,
from numpy.random import random from bokeh.io import curdoc from bokeh.layouts import column, row from bokeh.plotting import ColumnDataSource, Figure from bokeh.models.widgets import Select, TextInput def get_data(N): return dict(x=random(size=N), y=random(size=N), r=random(size=N) * 0.03) source = ColumnDataSource(data=get_data(200)) p = Figure(tools="", toolbar_location=None) r = p.circle(x='x', y='y', radius='r', source=source, color="navy", alpha=0.6, line_color="white") COLORS = ["black", "firebrick", "navy", "olive", "goldenrod"] select = Select(title="Color", value="navy", options=COLORS) input = TextInput(title="Number of points", value="200") def update_color(attrname, old, new): r.glyph.fill_color = select.value select.on_change('value', update_color) def update_points(attrname, old, new): N = int(input.value)
options=sorted(axis_map.keys()), value="Tomato Meter") y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="Number of Reviews") # Create Column Data Source that will be used by the plot source = ColumnDataSource( data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[])) hover = HoverTool(tooltips=[("Title", "@title"), ("Year", "@year"), ("$", "@revenue")]) p = Figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover]) p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None, fill_alpha="alpha") def select_movies(): genre_val = genre.value director_val = director.value.strip() cast_val = cast.value.strip()
def render_scatter(itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str]) -> Dict[str, Any]: """ Render scatter plot with a regression line and possible most influencial points """ # pylint: disable=too-many-locals df = itmdt["data"] xcol, ycol, *maybe_label = df.columns tooltips = [(xcol, f"@{{{xcol}}}"), (ycol, f"@{{{ycol}}}")] fig = Figure( plot_width=plot_width, plot_height=plot_height, toolbar_location=None, tools=[], x_axis_label=xcol, y_axis_label=ycol, ) # Scatter scatter = fig.scatter(x=df.columns[0], y=df.columns[1], source=df) if maybe_label: assert len(maybe_label) == 1 mapper = CategoricalColorMapper(factors=["=", "+", "-"], palette=palette) scatter.glyph.fill_color = { "field": maybe_label[0], "transform": mapper } scatter.glyph.line_color = { "field": maybe_label[0], "transform": mapper } # Regression line coeff_a, coeff_b = itmdt["coeffs"] line_x = np.asarray([df.iloc[:, 0].min(), df.iloc[:, 0].max()]) line_y = coeff_a * line_x + coeff_b fig.line(x=line_x, y=line_y, line_width=3) # Not adding the tooltips before because we only want to apply tooltip to the scatter hover = HoverTool(tooltips=tooltips, renderers=[scatter]) fig.add_tools(hover) # Add legends if maybe_label: nidx = df.index[df[maybe_label[0]] == "-"][0] pidx = df.index[df[maybe_label[0]] == "+"][0] legend = Legend( items=[ LegendItem(label="Most Influential (-)", renderers=[scatter], index=nidx), LegendItem(label="Most Influential (+)", renderers=[scatter], index=pidx), ], margin=0, padding=0, ) fig.add_layout(legend, place="right") return { "layout": [fig], "meta": ["Scatter Plot & Regression Line"], "container_width": plot_width, }
from bokeh.layouts import column from bokeh.models import ColumnDataSource, CustomJS, Slider from bokeh.plotting import Figure, output_file, show,save output_file("js_on_change.html") x = [x*0.005 for x in range(0, 200)] y = x source = ColumnDataSource(data=dict(x=x, y=y)) print(y) plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var f = cb_obj.value var x = data['x'] var y = data['y'] for (var i = 0; i < x.length; i++) { y[i] = Math.pow(x[i], f) } source.change.emit(); """) slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") slider.js_on_change('value', callback) print(y) layout = column(slider, plot) save(layout)
def render_crossfilter(itmdt: Intermediate, plot_width: int, plot_height: int) -> column: """ Render crossfilter scatter plot with a regression line. """ # pylint: disable=too-many-locals, too-many-function-args df = itmdt["data"] df["__x__"] = df[df.columns[0]] df["__y__"] = df[df.columns[0]] source_scatter = ColumnDataSource(df) source_xy_value = ColumnDataSource({ "x": [df.columns[0]], "y": [df.columns[0]] }) var_list = list(df.columns[:-2]) xcol = source_xy_value.data["x"][0] ycol = source_xy_value.data["y"][0] tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")] fig = Figure( plot_width=plot_width, plot_height=plot_height, toolbar_location=None, title=Title(text="Scatter Plot", align="center"), tools=[], x_axis_label=xcol, y_axis_label=ycol, ) scatter = fig.scatter("__x__", "__y__", source=source_scatter) hover = HoverTool(tooltips=tooltips, renderers=[scatter]) fig.add_tools(hover) x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150) y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150) x_select.js_on_change( "value", CustomJS( args=dict( scatter=source_scatter, xy_value=source_xy_value, x_axis=fig.xaxis[0], ), code=""" let currentSelect = this.value; let xyValueData = xy_value.data; let scatterData = scatter.data; xyValueData['x'][0] = currentSelect; scatterData['__x__'] = scatterData[currentSelect]; x_axis.axis_label = currentSelect; scatter.change.emit(); xy_value.change.emit(); """, ), ) y_select.js_on_change( "value", CustomJS( args=dict( scatter=source_scatter, xy_value=source_xy_value, y_axis=fig.yaxis[0], ), code=""" let currentSelect = this.value; let xyValueData = xy_value.data; let scatterData = scatter.data; xyValueData['y'][0] = currentSelect; scatterData['__y__'] = scatterData[currentSelect]; y_axis.axis_label = currentSelect; scatter.change.emit(); xy_value.change.emit(); """, ), ) fig = column(row(x_select, y_select, align="center"), fig, sizing_mode="stretch_width") return fig
# Prepare absolute value versions of the currents for plotting later IV_data['Abs_Current_fit'] = np.abs(IV_data['Current_fit']) IV_data['Abs_Current'] = np.abs(IV_data['Current']) #Prepare plots #Define here what interactive functions in plot you want plot_config = dict( plot_height=330, plot_width=550, tools="pan,wheel_zoom,box_zoom,reset,lasso_select,box_select,hover,save") #Set up plots #Generate linear and log plots plot_fit_by_eye = Figure(title='Linear Plot for T = {0} K'.format(str(T)), **plot_config, x_axis_label='Applied Voltage (V)', y_axis_label='Current (A)') plot_fit_by_eye_log = Figure(title='Logarithmic Plot for T = {0} K'.format( str(T)), **plot_config, y_axis_type="log", x_axis_label='Applied Voltage (V)', y_axis_label='Current (A)') #Define data you wanna plot source_data = ColumnDataSource( data=dict(x=IV_data['Voltage'], y=IV_data['Current'])) source_data_log = ColumnDataSource( data=dict(x=IV_data['Voltage'], y=IV_data['Abs_Current'])) source_fit_by_eye = ColumnDataSource( data=dict(x=IV_data['Voltage'], y=IV_data['Current_fit']))
from bokeh.io import show from bokeh.models import ColumnDataSource, CustomJS, ColorPicker from bokeh.plotting import Figure from bokeh.layouts import row, widgetbox cds = ColumnDataSource(data=dict(x=(0, 1), y=(0, 1))) p = Figure(x_range=(0, 1), y_range=(0, 1)) w = ColorPicker(title="Line Color", color="red", height=20, width=100) line = p.line(x='x', y='y', source=cds, color=w.color) cb = CustomJS(args={'line': line}, code=""" line.glyph.line_color = cb_obj.color """) w.js_on_change('color', cb) show(row([widgetbox(w, width=100), p]))
def plot_bollinger_signals(data, signals, ticker=None, notebook=False): # create a new plot with a title and axis labels p = Figure(title=ticker + ' Bollinger Bands Strategy', x_axis_label='Date', x_axis_type='datetime', y_axis_label='Price in $', plot_height=500, plot_width=950, tools=['pan', 'wheel_zoom'], toolbar_location='below') inc = data['Close'] > data['Open'] dec = data['Open'] > data['Close'] w = 12 * 60 * 60 * 1000 # half day in ms p.segment(data.index, data['High'], data.index, data['Low'], color="black") p.vbar(data.index[inc], w, data['Open'][inc], data['Close'][inc], fill_color="#D5E1DD", line_color="black") p.vbar(data.index[dec], w, data['Open'][dec], data['Close'][dec], fill_color="#F2583E", line_color="black") # configure so that Bokeh chooses what (if any) scroll tool is active p.toolbar.active_scroll = "auto" # add a line renderer with legend and line thickness p.line(signals.index, signals['mediumband'], line_width=2, legend='Mediumband', line_color='black') p.line(signals.index, signals['upperband'], line_width=2, legend='Upperband', line_color='orange') p.line(signals.index, signals['lowerband'], line_width=2, legend='Lowerband', line_color='blue') p.triangle(signals.loc[signals.positions == 1.0].index, signals.lowerband[signals.positions == 1.0], size=15, fill_color='green', legend='Buy') p.inverted_triangle(signals.loc[signals.positions == -1.0].index, signals.upperband[signals.positions == -1.0], size=15, fill_color='red', legend='Sell') p.legend.location = "top_left" p.legend.click_policy = "hide" if notebook: # show the results show(p, notebook_handle=True) push_notebook() else: # output the results output_file('%s Bollinger Bands Strategy.html' % ticker) save(p)
new_plot_info.append(element) print element exec(new_plot_info[2]) # xrange exec(new_plot_info[3]) # yrange exec(new_plot_info[4] ) # dictionary containg info about slider values for each parameter # Set up data N = 200 x = np.linspace(xrange[0], xrange[1], N) # Set up plot plot = Figure(plot_height=400, plot_width=400, title=new_plot_info[0], tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=xrange, y_range=yrange) # Set up widgets params = sliders.keys() Slider_instances = [] for n, param in enumerate(params): # create a global Slider instance for each parameter: exec('param{0}'.format(n) + " = Slider(" + sliders[param] + ")") Slider_instances.append(eval('param{0}'.format(n))) # add Slider to list # get the first value for all parameters: exec(param + " = " + 'param{0}.value'.format(n))
def plot_crossover_signals(data, signals, ticker=None, notebook=False): # create a new plot with a title and axis labels p = Figure(title=ticker + ' Moving Crossover Strategy', x_axis_label='Date', x_axis_type='datetime', y_axis_label='Price in $', plot_height=500, plot_width=950, tools=['pan', 'wheel_zoom'], toolbar_location='below') # configure so that Bokeh chooses what (if any) scroll tool is active p.toolbar.active_scroll = "auto" # add a line renderer with legend and line thickness p.line(data.index, data['Close'], line_width=2, legend='Close', line_color='black') p.line(signals.index, signals['short_mavg'], line_width=2, legend='Slow MA', line_color='orange') p.line(signals.index, signals['long_mavg'], line_width=2, legend='Fast MA', line_color='blue') p.triangle(signals.loc[signals.positions == 1.0].index, signals.short_mavg[signals.positions == 1.0], size=15, fill_color='green', legend='Bullish Crossover') p.inverted_triangle(signals.loc[signals.positions == -1.0].index, signals.short_mavg[signals.positions == -1.0], size=15, fill_color='red', legend='Bearish Crossover') p.legend.location = "top_left" p.legend.click_policy = "hide" if notebook: # show the results show(p, notebook_handle=True) push_notebook() else: # output the results output_file('%s Moving Crossover Strategy.html' % ticker) save(p)
return dict(x=df['Year'],y=df[type]) def updatePlot(attrname,old,new): '''Callback function that updates the data source based on the item selected''' source.data = get_data(df,new) ##Code------------------------------------------------------------------------ #Read the data in, grouped and summarized by the given field df = initialize_data('FacilityType') #Create a bokeh column data source object from the data source = ColumnDataSource(data=get_data(df,'Agricultural')) #Create the plot object from the column data source object p = Figure(title='Annual discharge (MG/year)', plot_width=800, plot_height=300) p.line(x='x',y='y',source=source) #Create and populate the select widget optionList = df.columns.tolist() if ('Year') in optionList: optionList.remove('Year') #Create the select (dropdown) object select = Select(title="Select type", options=optionList) #Run the 'updatePlot' function if the select value changes select.on_change('value',updatePlot) #Construct a layout for our app page # This will arrange our two objects (the plot and the select dropdown)
plot_data = [] for cluster in clusters: plot_data.append(np.where(predictions == cluster)[0]) plot_data = spike_waveforms[plot_data] # Set up data N = 0 x = np.arange(len(plot_data[N]) / 10) y = spike_waveforms[0, ::10] source = ColumnDataSource(data=dict( xs=[x for i in range(50)], ys=[plot_data[N + i, ::10] for i in range(50)])) # Set up plot plot = Figure(plot_height=400, plot_width=400, title="Unit waveforms", tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=[0, 45], y_range=[-200, 200]) plot.multi_line('xs', 'ys', source=source, line_width=1, line_alpha=1.0) # Set up widgets # text = TextInput(title="title", value='my sine wave') offset = Slider( title="offset", value=0, start=0, end=50000, step=100 ) # put the end of the slider at a large enough value so that almost all cluster sizes will fit in electrode = TextInput(title='Electrode Number', value='0') clusters = TextInput(title='Number of clusters', value='2') cluster_num = TextInput(title='Cluster Number', value='0') #amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0) #phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)