def buildVendorsTab(): defaultGfxVendors = [ gfxVendors.index('NVIDIA Corporation'), gfxVendors.index('Advanced Micro Devices, Inc. [AMD/ATI]'), gfxVendors.index('Intel Corporation') ] gfxVendorCheckbox = CheckboxGroup(labels=gfxVendors, active=defaultGfxVendors) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title="GFX Vendors", x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): vendors = [gfxVendors[i] for i in range(len(gfxVendors)) if i in selected] releaseUsers = 100 * getUsersForVendors('release', vendors) / gfxTotalReleaseUsers betaUsers = 100 * getUsersForVendors('beta', vendors) / gfxTotalBetaUsers fig.x_range.factors = vendors fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in vendors], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in vendors], y=betaUsers / 2, height=betaUsers, ) gfxVendorCheckbox.on_click(update) update(gfxVendorCheckbox.active) vendorComparison = HBox(HBox(VBoxForm(*[gfxVendorCheckbox]), width=300), fig, width=1100) return Panel(child=vendorComparison, title="GFX Vendor Comparison")
def buildOSesTab(): osesCheckbox = CheckboxGroup(labels=oses, active=[i for i in range(len(oses))]) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title='OS', x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): cur_oses = [oses[i] for i in range(len(oses)) if i in selected] releaseUsers = 100 * getUsersForOses('release', cur_oses) / osTotalReleaseUsers betaUsers = 100 * getUsersForOses('beta', cur_oses) / osTotalBetaUsers fig.x_range.factors = cur_oses fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in cur_oses], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in cur_oses], y=betaUsers / 2, height=betaUsers, ) osesCheckbox.on_click(update) update(osesCheckbox.active) osesComparison = HBox(HBox(VBoxForm(*[osesCheckbox]), width=300), fig, width=1100) return Panel(child=osesComparison, title="OS Comparison")
def dataurl_change(attr, old, new): if new != "DEMO": try: source_url.data = requests.get(new).json() inputs = VBoxForm(text, threshold, dataurl) curdoc().remove_root(plot) curdoc().add_root(HBox(inputs, plot, width=800)) except: logging.warn("unable to fetch {}".format(new)) update_data()
def create_layout(): year_select = Select(title="Year:", value="2010", options=years) location_select = Select(title="Location:", value="World", options=locations) year_select.on_change('value', on_year_change) location_select.on_change('value', on_location_change) controls = HBox(children=[year_select, location_select]) layout = VBox(children=[controls, pyramid(), population()]) return layout
def create_layout(self): years = list(map(str, sorted(self.df.Year.unique()))) locations = sorted(self.df.Location.unique()) year_select = Select(title="Year:", value="2010", options=years) location_select = Select(title="Location:", value="World", options=locations) year_select.on_change('value', self.on_year_change) location_select.on_change('value', self.on_location_change) controls = HBox(year_select, location_select) self.layout = VBox(controls, self.plot)
def create_layout(self): # create figure self.x_range = Range1d(start=self.model.map_extent[0], end=self.model.map_extent[2], bounds=None) self.y_range = Range1d(start=self.model.map_extent[1], end=self.model.map_extent[3], bounds=None) self.fig = Figure(tools='box_zoom,wheel_zoom,pan', x_range=self.x_range, y_range=self.y_range) self.fig.plot_height = 600 self.fig.plot_width = 1024 self.fig.axis.visible = True # add datashader layer self.image_source = ImageSource( url=self.model.service_url, extra_url_vars=self.model.shader_url_vars) self.image_renderer = DynamicImageRenderer( image_source=self.image_source) self.fig.renderers.append(self.image_renderer) # add ui components axes_select = Select.create(name='Plot:', options=self.model.axes) axes_select.on_change('value', self.on_axes_change) field_select = Select.create(name='Summary:', options=self.model.fields) field_select.on_change('value', self.on_field_change) aggregate_select = Select.create( name='Aggregation:', options=self.model.aggregate_functions) aggregate_select.on_change('value', self.on_aggregate_change) transfer_select = Select.create(name='Scale:', options=self.model.transfer_functions) transfer_select.on_change('value', self.on_transfer_function_change) controls = [ axes_select, field_select, aggregate_select, transfer_select ] self.controls = VBox(width=200, height=600, children=controls) self.map_area = VBox(width=self.fig.plot_width, children=[self.fig]) self.layout = HBox(width=self.fig.plot_width, children=[self.controls, self.map_area])
def daily_ticks_by_species(data_source): """ A line chart visualization of daily ticks by species. :param data_source: ColumnDataSource :return: Panel """ sp_callback = CustomJS(args=dict(source=data_source), code=""" var data = source.data; var f = cb_obj.value; data['ticks'] = data[f]; source.trigger('change'); """) fig = figure(plot_width=PLOT_WIDTH, plot_height=PLOT_HEIGHT, x_axis_type='datetime', title="Pinnoja lajeittain per päivä") fig.line('dates', 'ticks', source=data_source, line_width=3, color="navy", alpha=0.5) select = Select(title="Option:", options=['-- Yhteensä --'] + all_species, callback=sp_callback) layout = HBox(widgetbox(select), fig) return Panel(child=layout, title="Lajit päivittäin")
def get_data(f, name): shape = f[name].shape # Empty array data = np.empty(shape, dtype=np.float64) # read_direct to empty arrays f[name].read_direct(data) return data def select_data(): data_val = data_select.value with h5py.File('demo_data.hdf5', 'r') as f: return get_data(f, data_val) def update_data(attrname, old, new): # hardcoded length of 100 x = list(range(1, 101)) y = select_data() source.data = dict(x=x, y=y) data_select.on_change('value', update_data) inputs = VBoxForm(data_select, width=300) update_data(None, None, None) curdoc().add_root(HBox(inputs, p, width=1100))
def hbox(*children, **kwargs): """ Generate a plot that arranges several subplots horizontally. """ layout = HBox(children=list(children), **kwargs) _deduplicate_plots(layout, children) _push_or_save() return layout
# get all parameter values: exec(param + " = " + 'param{0}.value'.format(n)) # Generate the new curve: exec(new_plot_info[0]) # execute y = f(x, params) source.data = dict(x=x, y=y) for w in Slider_instances: w.on_change('value', update_data) # Set up layouts and add to document inputs = VBoxForm(children=Slider_instances) layout = HBox(children=[inputs, plot], width=800) # embed app in html template old_file = "template.html" new_file = "embed_template.html" f1 = open(old_file, "r") f2 = open(new_file, "w+") for line in f1: if "IBPLOT" in line: f2.write(autoload_server(layout, session_id=session.id)) else: f2.write(line) f1.close() f2.close()
df = select_movies() x_name = axis_map[x_axis.value] y_name = axis_map[y_axis.value] p.xaxis.axis_label = x_axis.value p.yaxis.axis_label = y_axis.value p.title = "%d movies selected" % len(df) source.data = dict( x=df[x_name], y=df[y_name], color=df["color"], title=df["Title"], year=df["Year"], revenue=df["revenue"], alpha=df["alpha"], ) controls = [ reviews, boxoffice, genre, min_year, max_year, oscars, director, cast, x_axis, y_axis ] for control in controls: control.on_change('value', update) inputs = HBox(VBoxForm(*controls), width=300) update(None, None, None) # initial load of the data curdoc().add_root(HBox(inputs, p, width=1100))
var g = eval( 'line' + i ).get( 'glyph' ); g.set( '%s', widget.get( 'value' ) ); window.g = g; } """ % (len(lines), prop)) for i, line in enumerate(lines): widget.callback.args['line%i' % i] = line def make_slider(prop, start, end, value): slider = Slider(title=prop, start=start, end=end, value=value) add_callback(slider, prop) return slider def make_dropdown(prop, menu): dropdown = Dropdown(label=prop, menu=menu) add_callback(dropdown, prop) return dropdown sliders = [ make_slider('line_width', start=0.2, end=16, value=5), make_slider('line_dash_offset', start=0, end=100, value=1), make_dropdown('line_cap', [("butt", "butt"), ("round", "round"), ("square", "square")]), make_dropdown('line_join', [("miter", "miter"), ("round", "round"), ("bevel", "bevel")]), ] sliders = VBox(*sliders) output_file("line_compare.html", title="line_compare.py example") show(HBox(sliders, p1, p2))
def chart(request): def get_dataset(src, name, distribution): df = src[src.airport == name].copy() del df['airport'] df['date'] = pd.to_datetime(df.date) df['left'] = df.date #- pd.DateOffset(days=0.5) df['right'] = df.date #+ pd.DateOffset(days=0.5) df = df.set_index(['date']) df.sort_index(inplace=True) if distribution == 'Smooth': window, order = 51, 3 #for key in STATISTICS: #df[key] = savgol_filter(df[key], window, order) return ColumnDataSource(data=df) def make_plot(source, title): print("make plot") plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None) plot.title = title colors = Blues4[0:3] plot.quad(top='record_max_temp', bottom='record_min_temp', left='left', right='right', color=colors[2], source=source, legend="Record") plot.quad(top='average_max_temp', bottom='average_min_temp', left='left', right='right', color=colors[1], source=source, legend="Average") plot.quad(top='actual_max_temp', bottom='actual_min_temp', left='left', right='right', color=colors[0], alpha=0.5, line_color="black", source=source, legend="Actual") # fixed attributes plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = None plot.yaxis.axis_label = "Temperature (F)" 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.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot # set up callbacks def update_plot(attrname, old, new): print("update called") city = city_select.value plot.title = cities[city]['title'] src = get_dataset(df, cities[city]['airport'], distribution_select.value) for key in STATISTICS + ['left', 'right']: source.data.update(src.data) # set up initial data print("main called") city = request.GET['city'] print("city is %s" % city) if len(city) == 0: city = 'Boston' distribution = 'Discrete' cities = { 'Boston': { 'airport': 'BOS', 'title': 'Boston, MA', }, 'Austin': { 'airport': 'AUS', 'title': 'Austin, TX', }, 'Seattle': { 'airport': 'SEA', 'title': 'Seattle, WA', } } #city_select = Select(value=city, title='City', options=sorted(cities.keys())) #distribution_select = Select(value=distribution, title='Distribution', options=['Discrete', 'Smooth']) df = pd.read_csv(join(dirname(__file__), 'data/2015_weather.csv')) source = get_dataset(df, cities[city]['airport'], distribution) plot = make_plot(source, cities[city]['title']) #city_select.on_change('value', update_plot) #distribution_select.on_change('value', update_plot) #controls = VBox(city_select, distribution_select) s = HBox(plot) script, div = components(s) #script2,div2=components(plot) # add to document #curdoc().add_root(HBox(controls, plot)) #script, div = components(vform(controls, plot)) #script, div = components(HBox(controls, plot)) return render(request, "chart.html", { "the_script": script, "the_div": div })
def integration_with_sliders(rsys, tend, c0, parameters, fig_kwargs=None, unit_registry=None, output_conc_unit=None, output_time_unit=None, slider_kwargs=None, x_axis_type="linear", y_axis_type="linear", integrate_kwargs=None, odesys_extra=None, get_odesys_kw=None): """ Parameters ---------- odesys_extra : tuple of :class:`pyodesys.ODESys` & dict From :func:`chempy.kinetics.ode.get_odesys`. get_odesys_kw : dict If odesys_extra is ``None`` the user may pass this for :func:`chempy.kinetics.ode.get_odesys`. """ import numpy as np from bokeh.plotting import Figure from bokeh.models import ColumnDataSource, HBox, VBoxForm 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 state_keys, rarg_keys, p_units = [ extra[k] for k in ('param_keys', 'unique', 'p_units') ] if output_conc_unit is None: output_conc_unit = 1 if output_time_unit is None: 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) tout, Cout, info = odesys.integrate(tout, c0, parameters, **(integrate_kwargs or {})) sources = [ ColumnDataSource( data={ 'tout': to_unitless(tout, output_time_unit), k: to_unitless(Cout[:, idx], output_conc_unit) }) for idx, k in enumerate(rsys.substances) ] if fig_kwargs is None: Cmax = np.max(Cout) x_range = list(to_unitless([tend * 0, tend], 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,resize,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) ] c0_widgets = OrderedDict([ (k, Slider(title=k if output_conc_unit is 1 else k + ' / ' + output_conc_unit.dimensionality.unicode, value=_C(k), **slider_kwargs.get( k, dict(start=_C(k) / 2, end=_C(k) * 2, step=_C(k) / 10)))) for k in rsys.substances ]) def _dict_to_unitless(d, u): return {k: to_unitless(v, u) for k, v in d.items()} 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 _tout, _Cout, _info = odesys.integrate(tout, _c0, _params) for idx, k in enumerate(rsys.substances): sources[idx].data = { 'tout': to_unitless(_tout, output_time_unit), k: to_unitless(_Cout[:, idx], output_conc_unit) } for w in all_widgets: w.on_change('value', update_data) inputs = VBoxForm(children=all_widgets) return HBox(children=[inputs, plot], width=800)
size = [20] * N source1.data["size"] = size session.store_objects(source1) source2.on_change('selected', on_selection_change2) reset = Button(label="Reset") def on_reset_click(): source1.selected = [] source2.selected = [] session.store_objects(source1, source2) reset.on_click(on_reset_click) vbox = VBox(children=[reset], width=150) hbox = HBox(children=[vbox, plot1, plot2]) document.add(hbox) session.store_document(document) if __name__ == "__main__": link = session.object_link(document.context) print("Please visit %s to see the plots" % link) view(link) print("\npress ctrl-C to exit") session.poll_document(document)
plot.title = algorithm def update_samples_or_dataset(attrname, old, new): global X, y dataset = dataset_select.value algorithm = algorithm_select.value n_clusters = int(clusters_slider.value) n_samples = int(samples_slider.value) X, y = get_dataset(dataset, n_samples) X, y_pred = clustering(X, algorithm, n_clusters) colors = [spectral[i] for i in y_pred] source.data['x'] = X[:, 0] source.data['y'] = X[:, 1] source.data['colors'] = colors algorithm_select.on_change('value', update_algorithm_or_clusters) clusters_slider.on_change('value', update_algorithm_or_clusters) dataset_select.on_change('value', update_samples_or_dataset) samples_slider.on_change('value', update_samples_or_dataset) # set up layout selects = HBox(dataset_select, algorithm_select) inputs = VBox(samples_slider, clusters_slider, selects) # add to document curdoc().add_root(HBox(inputs, plot))
global p, patches, colors, counter for _ in range(slider.value): counter += 1 data = patches.data_source.data.copy() rates = np.random.uniform(0, 100, size=100).tolist() color = [colors[2 + int(rate / 16.667)] for rate in rates] p.title = 'Algorithms Deployed, Iteration: {}'.format(counter) source.data['rate'] = rates source.data['color'] = color time.sleep(5) toggle = Toggle(label='START') toggle.on_click(run) slider = Slider(name='N iterations to advance', title='N iterations to advance', start=5, end=10000, step=5, value=500) # set up layout toggler = HBox(toggle) inputs = VBox(toggler, slider) # add to document curdoc().add_root(HBox(inputs))
graphs.append(graph) # Set up layouts and add to document #inputs = VBoxForm(children=[text, offset, amplitude, phase, freq]) ticker_input = TextInput(value='SPFB.RTS') div_input = TextInput(value='1.') length_input = TextInput(value=str(start_candles)) format_input = TextInput(value='0') button = Button(label='Change') button.on_click(change_source) curdoc().clear() curdoc().add_root( HBox(children=[ button, ticker_input, div_input, length_input, format_input ], width=900)) for graph in graphs: inputs = VBoxForm(children=[graph.box, graph.scale, graph.text]) curdoc().add_root(HBox(children=[inputs, graph.plot], width=900)) curdoc().add_periodic_callback(reload_data, data_refresh_interval) except Exception as e: #button = Button(label='Error!') #curdoc().add_root(button) show_exception_info() text = PreText(text=traceback.format_exc()) #str(e) curdoc().clear() curdoc().add_root(text)
from bokeh.models import DatePicker, HBox from bokeh.io import curdoc from datetime import datetime beginning = DatePicker(title="Begin Date", min_date=datetime(2014, 11, 1), max_date=datetime.now(), value=datetime(datetime.now().year, 1, 1)) def cb(attr, old, new): print(new) beginning.on_change('value', cb) curdoc().add_root(HBox(children=[beginning]))
plots = [] for i_dataset, dataset in enumerate( [noisy_circles, noisy_moons, blobs1, blobs2]): X, y = dataset X = StandardScaler().fit_transform(X) # Predict cluster memberships algorithm.fit(X) if hasattr(algorithm, 'labels_'): y_pred = algorithm.labels_.astype(np.int) else: y_pred = algorithm.predict(X) # Plot p = Figure(webgl=True, title=name, plot_width=PLOT_SIZE, plot_height=PLOT_SIZE) p.scatter( X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1, ) plots.append(p) # Genearate and show the plot box = VBox(HBox(plots[0], plots[1]), HBox(plots[2], plots[3])) output_file("clustering.html", title="clustering with sklearn") show(box)
def create_layout(self): # create figure self.x_range = Range1d(start=self.model.map_extent[0], end=self.model.map_extent[2], bounds=None) self.y_range = Range1d(start=self.model.map_extent[1], end=self.model.map_extent[3], bounds=None) self.fig = Figure(tools='wheel_zoom,pan', x_range=self.x_range, lod_threshold=None, plot_width=self.model.plot_width, plot_height=self.model.plot_height, background_fill_color='black', y_range=self.y_range) self.fig.min_border_top = 0 self.fig.min_border_bottom = 10 self.fig.min_border_left = 0 self.fig.min_border_right = 0 self.fig.axis.visible = False self.fig.xgrid.grid_line_color = None self.fig.ygrid.grid_line_color = None # add tiled basemap self.tile_source = WMTSTileSource(url=self.model.basemap) self.tile_renderer = TileRenderer(tile_source=self.tile_source) self.fig.renderers.append(self.tile_renderer) # add datashader layer self.image_source = ImageSource( url=self.model.service_url, extra_url_vars=self.model.shader_url_vars) self.image_renderer = DynamicImageRenderer( image_source=self.image_source) self.fig.renderers.append(self.image_renderer) # add label layer self.label_source = WMTSTileSource(url=self.model.labels_url) self.label_renderer = TileRenderer(tile_source=self.label_source) self.fig.renderers.append(self.label_renderer) # Add a hover tool self.model.legend_side_vbox = VBox() self.model.legend_bottom_vbox = VBox() # add ui components controls = [] axes_select = Select.create(name='Axes', options=self.model.axes) axes_select.on_change('value', self.on_axes_change) controls.append(axes_select) self.field_select = Select.create(name='Field', options=self.model.fields) self.field_select.on_change('value', self.on_field_change) controls.append(self.field_select) self.aggregate_select = Select.create( name='Aggregate', options=self.model.aggregate_functions) self.aggregate_select.on_change('value', self.on_aggregate_change) controls.append(self.aggregate_select) transfer_select = Select.create(name='Transfer Function', options=self.model.transfer_functions) transfer_select.on_change('value', self.on_transfer_function_change) controls.append(transfer_select) color_ramp_select = Select.create(name='Color Ramp', options=self.model.color_ramps) color_ramp_select.on_change('value', self.on_color_ramp_change) controls.append(color_ramp_select) spread_size_slider = Slider(title="Spread Size (px)", value=0, start=0, end=10, step=1) spread_size_slider.on_change('value', self.on_spread_size_change) controls.append(spread_size_slider) hover_size_slider = Slider(title="Hover Size (px)", value=8, start=4, end=30, step=1) hover_size_slider.on_change('value', self.on_hover_size_change) controls.append(hover_size_slider) controls.append(self.model.legend_side_vbox) # add map components basemap_select = Select.create(name='Basemap', value='Imagery', options=self.model.basemaps) basemap_select.on_change('value', self.on_basemap_change) image_opacity_slider = Slider(title="Opacity", value=100, start=0, end=100, step=1) image_opacity_slider.on_change('value', self.on_image_opacity_slider_change) basemap_opacity_slider = Slider(title="Basemap Opacity", value=100, start=0, end=100, step=1) basemap_opacity_slider.on_change('value', self.on_basemap_opacity_slider_change) show_labels_chk = CheckboxGroup(labels=["Show Labels"], active=[0]) show_labels_chk.on_click(self.on_labels_change) map_controls = [ basemap_select, basemap_opacity_slider, image_opacity_slider, show_labels_chk ] self.controls = VBox(width=200, height=600, children=controls) self.map_controls = HBox(width=self.fig.plot_width, children=map_controls) self.map_area = VBox(width=self.fig.plot_width, children=[ self.map_controls, self.fig, self.model.legend_bottom_vbox ]) self.layout = HBox(width=1366, children=[self.controls, self.map_area]) self.model.fig = self.fig self.model.update_hover()
electrode_num = int(electrode.value) num_clusters = int(clusters.value) cluster = int(cluster_num.value) # Now get new data spike_waveforms = np.load( './spike_waveforms/electrode%i/spike_waveforms.npy' % electrode_num) predictions = np.load( './clustering_results/electrode%i/clusters%i/predictions.npy' % (electrode_num, num_clusters)) plot_data = spike_waveforms[np.where(predictions == cluster)[0]] # Get the current slider values b = offset.value # Generate the new curve x = np.arange(len(plot_data[b]) / 10) #y = a*np.sin(k*x + w) + b source.data = dict(xs=[x for i in range(50)], ys=[plot_data[b + i, ::10] for i in range(50)]) for w in [offset]: w.on_change('value', update_data) # Set up layouts and add to document inputs = widgetbox(children=[offset, electrode, clusters, cluster_num]) curdoc().add_root(HBox(children=[inputs, plot], width=800))
} source = ColumnDataSource(data=dict(x=[],y=[],height=[])) cities=TextInput(title='location name') companies=TextInput(title='company name') industries=TextInput(title='industry name') x_axis=Select(title='X axis',options=sorted(axis_map.keys()),value='Current Industry') plot = figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover],x_range=industry[:10],y_range=[0,2000]) plot.rect(x='x',y='y',width=.8,height='height',source=source) plot.xaxis.major_label_orientation = np.pi/3 controls=[x_axis,cities,companies,industries] inputs=HBox(VBoxForm(*controls)) def select_types(): city_val=cities.value.strip() company_val=companies.value.strip() industry_val=industries.value.strip() selected=data_all.copy() if(city_val!=""): selected=selected[selected['location'].str.contains(city_val)==True] if(company_val!=""): selected=selected[selected['company'].str.contains(company_val)==True] if(industry_val!=""): selected=selected[selected['industry'].str.contains(industry_val)==True] return selected
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 model = AppModel(autompg) controls_view = HBox(width=800) x_select = Select.create(name='X-Axis', value=model.x_field, options=model.df.columns) x_select.on_change('value', partial(bind_on_change, model_field='x_field')) y_select = Select.create(name='Y-Axis', value=model.y_field, options=model.df.columns) y_select.on_change('value', partial(bind_on_change, model_field='y_field')) color_select = Select.create(name='Color', value=model.color_field, options=['None'] + model.quantileable_column_names)
import numpy as np from numpy import pi from bokeh.client import push_session from bokeh.driving import cosine from bokeh.plotting import figure, curdoc from bokeh.models import HBox x = np.linspace(0, 4 * pi, 80) y = np.sin(x) p = figure() r1 = p.line([0, 4 * pi], [-1, 1], color="firebrick") r2 = p.line(x, y, color="navy", line_width=4) @cosine(w=0.03) def update(step): # updating a single column of the the *same length* is OK r2.data_source.data["y"] = y * step r2.glyph.line_alpha = 1 - 0.8 * abs(step) curdoc().add_periodic_callback(update, 50) curdoc().add_root(HBox(p))
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 image_source = ColumnDataSource(dict(image=[], x=[], y=[], dw=[], dh=[])) fig.image_rgba(source=image_source, image='image', x='x', y='y', dw='dw', dh='dh', dilate=False) time_text = Paragraph(text='Time Period: 00:00 - 00:00') controls = HBox(children=[time_text, time_select], width=fig.plot_width) layout = VBox(children=[fig, controls]) curdoc().add_root(layout) curdoc().add_periodic_callback(update_data, 1000)
p2.line(x='time', y='macd9', color='blue', source=source) p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source) mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001) stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01) mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26]) curdoc().add_root( VBox(HBox(mean, stddev, mavg), GridPlot(children=[[p], [p2]]))) def _create_prices(t): last_average = 100 if t == 0 else source.data['average'][-1] returns = asarray(lognormal(mean.value, stddev.value, 1)) average = last_average * cumprod(returns) high = average * exp(abs(gamma(1, 0.03, size=1))) low = average / exp(abs(gamma(1, 0.03, size=1))) delta = high - low open = low + delta * uniform(0.05, 0.95, size=1) close = low + delta * uniform(0.05, 0.95, size=1) return open[0], high[0], low[0], close[0], average[0] def _moving_avg(prices, days=10):
def initialize_plot(self, plots=None, ranges=None): ranges = self.compute_ranges(self.layout, self.keys[-1], None) passed_plots = [] if plots is None else plots plots = [[] for _ in range(self.rows)] tab_titles = {} insert_rows, insert_cols = [], [] adjoined = False for r, c in self.coords: subplot = self.subplots.get((r, c), None) if subplot is not None: shared_plots = passed_plots if self.shared_axes else None subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots) # Computes plotting offsets depending on # number of adjoined plots offset = sum(r >= ir for ir in insert_rows) if len(subplots) > 2: adjoined = True # Add pad column in this position insert_cols.append(c) if r not in insert_rows: # Insert and pad marginal row if none exists plots.insert(r + offset, [None for _ in range(len(plots[r]))]) # Pad previous rows for ir in range(r): plots[ir].insert(c + 1, None) # Add to row offset insert_rows.append(r) offset += 1 # Add top marginal plots[r + offset - 1] += [subplots.pop(-1), None] elif len(subplots) > 1: adjoined = True # Add pad column in this position insert_cols.append(c) # Pad previous rows for ir in range(r): plots[r].insert(c + 1, None) # Pad top marginal if one exists if r in insert_rows: plots[r + offset - 1] += 2 * [None] else: # Pad top marginal if one exists if r in insert_rows: plots[r + offset - 1] += [None] * (1 + (c in insert_cols)) plots[r + offset] += subplots if len(subplots) == 1 and c in insert_cols: plots[r + offset].append(None) passed_plots.append(subplots[0]) if self.tabs: if isinstance(self.layout, Layout): tab_titles[r, c] = ' '.join(self.paths[r, c]) else: dim_vals = zip(self.layout.kdims, self.paths[r, c]) tab_titles[r, c] = ', '.join( [d.pprint_value_string(k) for d, k in dim_vals]) # Replace None types with empty plots # to avoid bokeh bug if adjoined: plots = layout_padding(plots, self.renderer) # Wrap in appropriate layout model if self.tabs: panels = [ Panel(child=child, title=str(tab_titles.get((r, c)))) for r, row in enumerate(plots) for c, child in enumerate(row) if child is not None ] layout_plot = Tabs(tabs=panels) elif bokeh_version >= '0.12': plots = filter_toolboxes(plots) plots, width = pad_plots(plots) layout_plot = gridplot(children=plots, width=width) elif len(plots) == 1 and not adjoined: layout_plot = VBox(children=[HBox(children=plots[0])]) elif len(plots[0]) == 1: layout_plot = VBox(children=[p[0] for p in plots]) else: layout_plot = BokehGridPlot(children=plots) title = self._get_title(self.keys[-1]) if title: self.handles['title'] = title layout_plot = Column(title, layout_plot) self._update_callbacks(layout_plot) self.handles['plot'] = layout_plot self.handles['plots'] = plots if self.shared_datasource: self.sync_sources() self.drawn = True return self.handles['plot']
def buildPlot(): #####################Setup # Grab graph colors, pop undesireable ones colors = SEABORN_PALETTES['bright'] #Grab and sort the FQs quals = fruit_df.reset_index() quals = quals['FruitQuality'].unique().tolist() for idx, i in enumerate(list(quals)): if type(i) == type(0.5): quals.pop(idx) unique_FQs = quals #a little math to get the epoch time to set the initial x range minDate = ts_to_epoch(fruit_df['Date'].min()) maxDate = ts_to_epoch(fruit_df['Date'].max()) ###########Create and format the plot plot = figure( x_axis_type="datetime", plot_width=600, plot_height=400, tools=[PanTool(), WheelZoomTool(), SaveTool(), BoxZoomTool()], x_range=DataRange1d( start=minDate, end=maxDate ), #sets the initial date range to the limits of the data y_range=DataRange1d(start=0, end=1), name='the_plot', toolbar_location='above') #some styling plot.title.text = "Historical Volatility" plot.xaxis.axis_label = "Trade Date" plot.yaxis.axis_label = "Vol" plot.background_fill_color = '#EAEBF0' plot.xgrid.grid_line_color = 'white' plot.ygrid.grid_line_color = 'white' plot.xaxis.axis_line_color = 'white' plot.xaxis.major_tick_line_color = 'white' plot.xaxis.minor_tick_line_color = 'white' plot.yaxis.axis_line_color = 'white' plot.yaxis.major_tick_line_color = 'white' plot.yaxis.minor_tick_line_color = 'white' plot.toolbar.logo = None #a list for all of the lines to reside in lines = [] legends = [] ##############Create the widgets #a console style window to show debug messages TODO: add on/off functionality debug = PreText(text="", width=1200, height=500) #echos the debug in a place more visiable for the user user_message = Paragraph(text='') #Asset_Class, Product, and From dropdown boxes. Sets dropdown's initial value. asCls = Select(title="Asset Class", options=ddOpts['Asset_Class'].unique().tolist()) asCls.value = asCls.options[0] prod = Select(title="Products", options=ddOpts[ddOpts['Asset_Class'] == asCls.value] ['Product'].unique().tolist()) prod.value = prod.options[0] whereFrom = Select(title="From", options=ddOpts[(ddOpts['Asset_Class'] == asCls.value) & (ddOpts['Product'] == prod.value)] ['From'].unique().tolist()) whereFrom.value = whereFrom.options[0] FQslider = Slider(title='Fruit Quality', start=min(unique_FQs), end=max(unique_FQs), step=1) #the amount of days back to look for the data days_back = TextInput(title='Days ago', value='365') days_back_buttons = RadioButtonGroup( labels=['10', '30', '90', '180', '365', '730'], active=4) #the date to linear fit to fixed_date_buttons = RadioButtonGroup( labels=['30', '60', '90', '120', '180', '365'], active=2) fixed_date = TextInput(title='Days to Exp', value='90') #the amount of days with which to calculate the rolling mean rolling_days_buttons = RadioButtonGroup(labels=['1', '2', '5', '10'], active=0) rolling_days = TextInput(title='Rolling Mean Days', value='1') #a dynamically resizing checkbox group that allows for the changing of the visablity of any line on the plot line_onOff = CheckboxGroup(width=400, name='line_onOff') #the associated colors to act as a legend for line_onOff legendDiv = Div(width=50) #button to add a line addLine = Button(label="Add Line") #an html rendered visualization of the data for each line descriptions = Div(text='', width=500) #resizes the plot rszButton = Button(label='resize') ##########Define functions associated with the widgets #concats any dubug call to the end of the current debug text, and changes the user message def updateDebug(inString): inString = str(inString) user_message.text = inString oldText = debug.text newText = ("*- " + str(datetime.now()) + " : " + inString) debug.text = oldText + '\n' + newText #changes the potential products and contract categories to match the user selected asset class def asClsChange(attrname, old, new): prod.options = ddOpts[ddOpts['Asset_Class'] == asCls.value]['Product'].unique().tolist() prod.value = prod.options[0] #changes the potential contract categories to match the user selected product def prodChange(attrname, old, new): whereFrom.options = ddOpts[(ddOpts['Asset_Class'] == asCls.value) & ( ddOpts['Product'] == prod.value)]['From'].unique().tolist() whereFrom.value = whereFrom.options[0] #links the days back button and text box def days_back_buttonChange(attrname, old, new): days_back.value = days_back_buttons.labels[days_back_buttons.active] #checks that the users input is an int def days_backChange(attrname, old, new): try: days_back.value = str(int(days_back.value)) except ValueError: days_back.value = '0' updateDebug('please type an integer') #links the fixed date button and text box def fixed_date_buttonChange(attrname, old, new): fixed_date.value = fixed_date_buttons.labels[fixed_date_buttons.active] #checks that the users input is an int def fixed_dateChange(attrname, old, new): try: fixed_date.value = str(int(fixed_date.value)) except ValueError: fixed_date.value = '0' updateDebug('please type an integer') #links the rolling days button and text box def rolling_days_buttonsChange(attrname, old, new): rolling_days.value = rolling_days_buttons.labels[ rolling_days_buttons.active] #checks that the users input is an int def rolling_daysChange(attrname, old, new): try: rolling_days.value = str(int(rolling_days.value)) except ValueError: rolling_days.value = '0' updateDebug('please type an integer') #fits the plot to the currently visiable lines def resize(): if len(line_onOff.active) == 0 or len(line_onOff.labels) == 0: plot.x_range.start = ts_to_epoch(fruit_df['Date'].min()) plot.x_range.end = ts_to_epoch(fruit_df['Date'].max()) plot.y_range.start = 0 plot.y_range.end = 100 else: xmin, xmax, ymin, ymax = calc_range(lines) plot.x_range.start = xmin plot.x_range.end = xmax plot.y_range.start = ymin plot.y_range.end = ymax #turn lines on or off def line_onOffChange(attrname, old, new): for i in range(len(line_onOff.labels)): if i in line_onOff.active: lines[i].glyph.visible = True else: lines[i].glyph.visible = False legendDiv.text = '<div>' for line in lines: legendDiv.text += '<br><div style="background-color: %s; float:up; padding: 4px 4px 4px 4px"></div><br>' % line.glyph.line_color legendDiv.text += '</div>' resize() #adds a line to the graph def grphUpdt(): #adds some debug messages, grabs the current time as to later show the total time taken to calculate updateDebug("Starting") updateDebug("total dataframe size: " + str(fruit_df.shape)) stTime = datetime.now() #the value to linear fit to fit_to = int(fixed_date.value) #instiantiate an empty dataframe that will eventually contain the graphs data graphData = pd.DataFrame({ 'Date': [], 'PriceVolatility': [], 'Days_to_Exp': [] }) #grab the appropriate subset of the whole dataframe based on the users input into the widgets updateDebug("querying the data..") try: workingDf = fruit_df.loc[asCls.value, prod.value, whereFrom.value] except KeyError: updateDebug( 'no data with that combination of Asset Class, Product, From') return try: workingDf = workingDf[[ 'Date', 'PriceVolatility', 'Days_to_Exp' ]][(workingDf['Date'] > (date.today() - timedelta(days=int(days_back.value))))] except KeyError: updateDebug( 'no data with that combination of Asset Class, Product, From, and days back' ) return updateDebug("done breaking down df") #a hook in the case that the users inputs resulted in an empty dataframe if (workingDf.empty): updateDebug( 'no data with that combination of Asset Class, Product, From, and days back' ) return #widdle down the database to only contain the user specified FQ try: graphData = workingDf.loc[int(FQslider.value)].copy() except KeyError: updateDebug('no data with that FQ') #another empty graph hook if (graphData.empty): updateDebug( 'no data with that combination of Asset Class, Product, Contract Category, FQ, and days back' ) return updateDebug('grabed correct FQs') #calculate linear fit on the current subset updateDebug('calculating linear fit...') graphData = mu.linearFit(fit_to=fit_to, group_on_column='Date', df=graphData, fit_column='Days_to_Exp', on_columns=['PriceVolatility']) updateDebug('finished with linear fit') # a few more debug messages updateDebug( "working df qry: Asset_Class = %s and Product = %s and From = %s and Date > %s " % (asCls.value, prod.value, whereFrom.value, str(date.today() - timedelta(days=int(days_back.value))))) updateDebug("graph data shape: " + str(workingDf.shape)) #makes sure graph data has at least 5 rows, so that rolling mean can be calculated if graphData.shape[0] > int(rolling_days.value): #make the graph legend, based on if there's a denominator specified or not this_legend = '%s - %s FQ: %s Days to Exp: %s From: %s Rolling Days: %s' % ( prod.value, whereFrom.value, int( FQslider.value), fixed_date.value, str(date.today() - timedelta(days=int(days_back.value))), rolling_days.value) #add a new line to the graph, and add the accosiated GlyphRenderer created by adding the line to the lines list. #Set the legend to the previously calculated legend, and set the color to the next color in the current theme (if there are more lines than colors, there will be multiple lines with the same color) #Calculates a 5 day rolling mean on the y values. Maybe add a slider/text box/other widget so the user can set the rolling mean themselves updateDebug('adding line to plot') lines.append( plot.line(graphData.index.values[int(rolling_days.value) - 1:], graphData['PriceVolatility'].rolling( window=int(rolling_days.value)).mean() [int(rolling_days.value) - 1:], line_width=3, color=colors[len(lines) % len(colors)])) legends.append(this_legend) updateDebug("updated graph") global descDf #either creates, or adds to, a dataframe containing statistics about the data. stats come from pandas DataFrame.describe. if descDf is None: graphData[this_legend] = graphData['PriceVolatility'] descDf = graphData[[ this_legend ]].rolling(window=int(rolling_days.value)).mean( )[int(rolling_days.value) - 1:].describe(percentiles=[]).transpose().copy() else: graphData[this_legend] = graphData['PriceVolatility'] descDf = pd.concat([ descDf, graphData[[ this_legend ]].rolling(window=int(rolling_days.value)).mean() [int(rolling_days.value) - 1:].describe(percentiles=[]).transpose().copy() ]) descDf = descDf.round(1) descriptions.text = descDf.to_html().replace('\\n', '') graphData.drop(this_legend, 1, inplace=True) #add the name of the line to the checkbox so that it can be turned off and o line_onOff.labels.append(this_legend) line_onOff.active.append(len(line_onOff.labels) - 1) legendDiv.text = '<div>' for line in lines: legendDiv.text += '<br><div style="background-color: %s; float:up; padding: 4px 4px 4px 4px"></div><br>' % line.glyph.line_color legendDiv.text += '</div>' ##leaving this in case we get around to figuring out the hover tool ##formats the date values for the hover tool, currently commented out until we, or bokeh, fix the hover tool for multiple lines #formDates= pd.to_datetime(graphData['Date'] ,format="%m-%d-%Y") #lines[-1].data_source.data['formDates'] = formDates.apply(lambda x: x.strftime('%m-%d-%Y')) ##Displays the amout of time it took to draw the line, as well as the number of points in the graph updateDebug("updated y vals, with rolling mean calculated") updateDebug( str(datetime.now() - stTime) + " FOR " + str(len(lines[-1].data_source.data['x'])) + " points") else: updateDebug("There's no data to display") del graphData del workingDf #######Link widgets to their associated functions asCls.on_change('value', asClsChange) prod.on_change('value', prodChange) days_back_buttons.on_change('active', days_back_buttonChange) days_back.on_change('value', days_backChange) fixed_date_buttons.on_change('active', fixed_date_buttonChange) fixed_date.on_change('value', fixed_dateChange) rolling_days_buttons.on_change('active', rolling_days_buttonsChange) rolling_days.on_change('value', rolling_daysChange) line_onOff.on_change('active', line_onOffChange) addLine.on_click(grphUpdt) rszButton.on_click(resize) #Formatting fixed_date_box = WidgetBox(fixed_date, fixed_date_buttons) days_back_box = WidgetBox(days_back, days_back_buttons) rolling_days_box = WidgetBox(rolling_days, rolling_days_buttons) widgets = [ asCls, prod, whereFrom, FQslider, days_back_box, fixed_date_box, rolling_days_box, addLine, rszButton, user_message ] plot_w_description = VBox(plot, descriptions, width=700) pwd_w_leg = HBox(plot_w_description, VBox(legendDiv), VBox(line_onOff), width=plot_w_description.width + line_onOff.width + 100, name='div_to_save') input_box = VBox(*widgets, width=400, height=1200) total_box = HBox(VBox(input_box), VBox(pwd_w_leg), width=input_box.width + pwd_w_leg.width + 100, height=1200) tot_w_debug = VBox(total_box, VBox(HBox(debug))) resize() return tot_w_debug
p.line(x='time', y='average', alpha=0.2, line_width=3, color='navy', source=source) p.line(x='time', y='ma', alpha=0.8, line_width=2, color='orange', 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) p2 = Figure(plot_height=250, x_range=p.x_range, tools="xpan,xwheel_zoom,xbox_zoom,reset") p2.line(x='time', y='macd', color='red', source=source) p2.line(x='time', y='macd9', color='blue', source=source) p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source) mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001) stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01) mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26]) curdoc().add_root(VBox(HBox(mean, stddev, mavg, width=800), GridPlot(children=[[p], [p2]]))) def create_random_corr_matrix(n): m = 2 * np.random.random_sample((n, n)) - 5 return np.tril(m) + np.tril(m, -1).T def create_random_corr_dataframe(n): m = create_random_corr_matrix(n) def convert_to_title(num): title = '' alist = string.uppercase while num: mod = (num - 1) % 26
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 model = AppModel(autompg) controls_view = HBox(width=800) x_select = Select.create(name='X-Axis', value=model.x_field, options=model.df.columns) x_select.on_change('value', partial(bind_on_change, model_field='x_field')) y_select = Select.create(name='Y-Axis', value=model.y_field, options=model.df.columns) y_select.on_change('value', partial(bind_on_change, model_field='y_field')) color_select = Select.create(name='Color', value=model.color_field, options=['None'] + model.quantileable_column_names) color_select.on_change('value', partial(bind_on_change, model_field='color_field')) palette_select = Select.create(name='Palette', options=sorted(model.palettes)) palette_select.on_change('value', partial(bind_on_change, model_field='palette_name')) size_select = Select.create(name='Size', value=model.size_field, options=['None'] + model.quantileable_column_names) size_select.on_change('value', partial(bind_on_change, model_field='size_field'))