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, y_range=self.y_range) self.fig.plot_height = 560 self.fig.plot_width = 800 self.fig.axis.visible = False # 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 ui components axes_select = Select.create(name='Axes', options=self.model.axes) axes_select.on_change('value', self.on_axes_change) field_select = Select.create(name='Field', options=self.model.fields) field_select.on_change('value', self.on_field_change) aggregate_select = Select.create( name='Aggregate', options=self.model.aggregate_functions) aggregate_select.on_change('value', self.on_aggregate_change) transfer_select = Select.create(name='Transfer Function', options=self.model.transfer_functions) transfer_select.on_change('value', self.on_transfer_function_change) basemap_select = Select.create(name='Basemap', value='Toner', 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) controls = [ axes_select, field_select, aggregate_select, transfer_select ] 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.layout = HBox(width=1024, children=[self.controls, self.map_area])
def on_slider_change(attr, old, new): simplify_tolerance = new simplify_features(simplify_tolerance) # let's read some shapefile metadata crs = states.crs simplify_slider = Slider(title='Simplify Tolerance', value=0, start=0, end=1, step=.01) simplify_slider.on_change('value', on_slider_change) save_button = Button(label='Save') save_button.on_click(save_to_shapefile) p = Figure(plot_height=600, plot_width=900, x_range=(bounds[0], bounds[2]), y_range=(bounds[1], bounds[3])) polys = p.patches(xs='xs', ys='ys', alpha=0.9, source=geo_source) controls = HBox(width=p.plot_width, children=[simplify_slider, save_button]) layout = VBox(width=p.plot_width, children=[controls, p]) curdoc().add_root(layout)
def initialize_plot(self, ranges=None): ranges = self.compute_ranges(self.layout, self.keys[-1], None) plots = [[] for i in range(self.rows)] passed_plots = [] 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) # Determine the most appropriate composite plot type # If the object cannot be displayed in a single layout # it will be split into Tabs, for 1-row or 1-column # Layouts we use the vplot and hplots. # If there is a table and multiple rows and columns # everything will be forced to a vertical layout if self.tabs: panels = [ Panel(child=child, title=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 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) self.handles['plot'] = layout_plot self.handles['plots'] = plots if self.shared_datasource: self.sync_sources() self.drawn = True return self.handles['plot']
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 on_click(*args): # TODO: process button print('***click***') # year = int(select_years.value) partition = select_partition.value station = int(inputs.children[2].value) # key = visbean_key_format.format(year, partition, station) visbean = visbeans[key] rec = visbean.get_reconstruction() x = [i for i in xrange(len(rec))] y = rec # source.data = dict(x=x, y=y) select_years.on_change('value', update_station_list) select_partition.on_change('value', update_station_list) button.on_click(on_click) # Set up layouts and add to document global inputs inputs = HBox(children=[select_years, select_partition, select_stations], height=75) m_doc = curdoc() m_doc.add_root(VBox(children=[inputs, button, plot], width=1000))
}, '2d': { 'indices': [] } } source2.selected = { '0d': { 'flag': False, 'indices': [] }, '1d': { 'indices': [] }, '2d': { 'indices': [] } } reset.on_click(on_reset_click) vbox = VBox(children=[reset], width=150) hbox = HBox(children=[vbox, plot1, plot2]) document.add_root(hbox) session.show(hbox) if __name__ == "__main__": print("\npress ctrl-C to exit") session.loop_until_closed()
def save_static(data: pd.DataFrame, filename: str, title: str): data['y'] = np.log10(data.y.values) diff = data.y.max() - data.y.min() scale = abs(data.y.min()) data['y'] += scale data['y'] /= diff #kui p väärtus on # p = 0.5 #siis graafikul peab see olema # print((np.log10(-np.log10(p))+scale)/diff) hover = HoverTool( tooltips=[("value", "@text"), ("count_first", "@count_first"), ("count_second", "@count_second")]) plot = figure( tools=[hover, WheelZoomTool(), BoxZoomTool(), PanTool(), ResetTool()], webgl=True, plot_width=800, plot_height=700, ) source = ColumnDataSource(data) scatter = plot.scatter(source=source, line_width=0, line_alpha=0, size=10, x="x", y="y", alpha=0.5) loc = ((np.log10(-np.log10(0.5)) + scale) / diff) p_line = Span(location=loc, dimension='width', line_color='red', line_width=3) plot.renderers.append(p_line) p_value_text = bokeh.models.Paragraph() p_value = TextInput(title='p value', value='0.5', callback=CustomJS(args=dict(source=source, line=p_line, p_text=p_value_text), code=''' val = parseFloat(cb_obj.value); if (val < 0|| val > 1){{ alert('p must be between 0 and 1') }} line.location = (Math.log10(-Math.log10(val)) + {scale})/{diff}; p_text.text = "p =" + (val).toString() p_text.trigger('change') line.trigger('change') '''.format(scale=float(scale), diff=float(diff)))) left = Span(location=-0.5, dimension='height', line_color='maroon') plot.renderers.append(left) right = Span(location=0.5, dimension='height', line_color='maroon') plot.renderers.append(right) left_limit = Slider(title='left_limit', value=-0.5, start=-1, end=0, step=0.001, orientation='horizontal', callback=CustomJS(args=dict(source=source, line=left), code=''' line.location = cb_obj.value; line.trigger('change') ''')) right_limit = Slider(title='right_limit', value=0.5, start=0, end=1, step=0.001, orientation='horizontal', callback=CustomJS(args=dict(source=source, line=right), code=''' line.location = cb_obj.value; line.trigger('change') ''')) ################################################### ## Data table ############################## ################################################### aux_source = bokeh.models.ColumnDataSource(column_names=['index', 'text']) table = bokeh.models.DataTable( source=aux_source, columns=[bokeh.models.TableColumn(field='text', title='text')], fit_columns=True, width=300) ################################################### ## Buttons ############################## ################################################### button_width = 40 buttons = [ bokeh.models.Button(label='1', width=button_width), bokeh.models.Button(label='2', width=button_width), bokeh.models.Button(label='3', width=button_width), bokeh.models.Button(label='4', width=button_width), bokeh.models.Button(label='5', width=button_width), bokeh.models.Button(label='6', width=button_width) ] def make_button_callback(label): if label in '123': v_pred = 'source.data.y[i] > (Math.log10(-Math.log10(parseFloat(p_value.value))) + {scale})/{diff}'.format( scale=float(scale), diff=float(diff)) elif label in '456': v_pred = 'source.data.y[i] <= (Math.log10(-Math.log10(parseFloat(p_value.value))) + {scale})/{diff}'.format( scale=float(scale), diff=float(diff)) if label in '14': h_pred = 'source.data.x[i] <= left_limit.value' elif label in '25': h_pred = 'source.data.x[i] > left_limit.value && source.data.x[i] < right_limit.value' elif label in '36': h_pred = 'source.data.x[i] >= right_limit.value' condition = '({h_pred} && {v_pred})'.format(h_pred=h_pred, v_pred=v_pred) return CustomJS(args=dict(source=source, left_limit=left_limit, right_limit=right_limit, p_value=p_value, table=table), code=''' table.source.data.index = [] table.source.data.text = [] for (var i = 0; i < source.data.x.length; i++){{ if {condition}{{ table.source.data.index.push(source.data.index[i]) table.source.data.text.push(source.data.text[i]) }} }} table.trigger('change') '''.format(condition=condition)) for button in buttons: button.callback = make_button_callback(button.label) # plot.renderers.extend( # [ # Span(location=-math.log10(0.05), dimension='width', line_color='blue'), # Span(location=-math.log10(0.05 / len(source.data['index'])), dimension='width', # line_color='darkblue') # ] # ) ## Siin on y-koordinaatide jooned # labels = np.arange(10, 100, 10) / 100 # labels = np.append([0.001, 0.01, 0.05], labels) # coords = -np.log10(labels) # y_ticker = bokeh.models.tickers.FixedTicker(ticks=coords) plot.ygrid[0].ticker = bokeh.models.tickers.FixedTicker(ticks=[]) plot.yaxis[0].formatter = bokeh.models.formatters.PrintfTickFormatter() plot.yaxis[0].formatter.format = '' plot.set(x_range=Range1d(-1.1, 1.1), y_range=Range1d(-0.05, 1.05)) sliders = VBox(p_value_text, p_value, left_limit, right_limit) save_filename = bokeh.models.TextInput(value='filename') save_button = bokeh.models.Button(label='Save') save_button.callback = CustomJS(args=dict( table=table, filename=save_filename, ), code=''' if (table.source.data.text == undefined){ alert('No elements selected! Press 1-6'); } var text = table.source.data.text.join('\\n'); var name = filename.value if (name === ''){ alert('Filename is empty!') } console.log(name) var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; func = function (data, fileName) { console.log('doing') blob = new Blob([data], {type: "text/plain"}), url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); } func(text, name) console.log('done') ''') input_box = widgetbox(save_filename, save_button) app = row( column(plot), column(row(sliders), row(*buttons[:3]), row(*buttons[3:]), row(input_box), row(table), responsive=False)) curdoc().add_root(app) save(curdoc(), filename=filename, title=title, resources=bokeh.resources.INLINE)
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.add_tools(PanTool(), WheelZoomTool()) children.append(plot) make_plot( 'annular_wedge', AnnularWedge(x="x", y="y", inner_radius=0.2, outer_radius=0.5, start_angle=0.8, end_angle=3.8)) make_plot('annulus', Annulus(x="x", y="y", inner_radius=0.2, outer_radius=0.5)) make_plot('arc', Arc(x="x", y="y", radius=0.4, start_angle=0.8, end_angle=3.8)) make_plot('circle', Circle(x="x", y="y", radius=1)) make_plot('oval', Oval(x="x", y="y", width=0.5, height=0.8, angle=-0.6)) make_plot('ray', Ray(x="x", y="y", length=25, angle=0.6)) make_plot('rect', Rect(x="x", y="y", width=0.5, height=0.8, angle=-0.6)) make_plot('text', Text(x="x", y="y", text={"value": "foo"}, angle=0.6)) make_plot('wedge', Wedge(x="x", y="y", radius=0.5, start_angle=0.9, end_angle=3.2)) layout = VBox(children=children) document.add_root(layout) session.show(layout)
v3 = Slider(title="V3_Coefficient", value=m_projection[3], start=v3_struct[0], end=v3_struct[1]) # Set up callbacks def update_data(attrname, old, new): # Get the current slider values v0_value = v0.value v1_value = v1.value v2_value = v2.value v3_value = v3.value # Generate the new curve m_projection = [v0_value, v1_value, v2_value, v3_value] rec = get_reconstruction(m_eigs_t, m_projection, m_mean_vector) x = [i for i in xrange(np.shape(rec)[0])] y = [v for v in rec] source.data = dict(x=x, y=y) for w in [v0, v1, v2, v3]: w.on_change('value', update_data) # Set up layouts and add to document inputs = HBox(children=[v0, v1, v2, v3]) curdoc().add_root(VBox(children=[inputs, plot], width=800))
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.handles['plot'] = layout_plot self.handles['plots'] = plots if self.shared_datasource: self.sync_sources() self.drawn = True return self.handles['plot']
def update_plots(attr, old, new): b.children = [plot_state_by_year(), make_scatterplot()] def update_plot_1(attr, old, new): b.children[0] = plot_state_by_year() states = [ 'AL', 'AR', 'AZ', 'CO', 'CT', 'DC', 'DE', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'NE', 'NH', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT' ] multi_select = MultiSelect(title="States:", value=['VT'], options=states) checkbox_group = CheckboxGroup( labels=["show US average", "show regression line"], active=[0, 1]) multi_select.on_change('value', update_plots) checkbox_group.on_change('active', update_plots) controls = widgetbox(multi_select, checkbox_group) b = VBox(plot_state_by_year(), make_scatterplot()) l = row(controls, b) curdoc().add_root(l)
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', source=source, color='black', line_width=2) p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source) p2 = Figure(plot_width=1200, plot_height=250, toolbar_location="left", tools="pan", x_range=p.x_range) 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), VBox(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): if len(prices) < days: return [100] return convolve(prices[-days:], ones(days, dtype=float), mode="valid") / days
df_outliers_removed = outliers(df_subset, np.float(threshold_value)) selection_dict = { 'x': df_outliers_removed[x_feature_value + '_x'], 'y': df_outliers_removed[y_feature_value + '_y'] } return selection_dict # Update plot def update(attr, old, new): plot_dict = select_features() source.data = plot_dict # Define controls list # While server is running, update the values input_values = [x_feature, y_feature, threshold] for value in input_values: value.on_change('value', update) inputs = VBox(VBoxForm(*input_values), width=300) update(None, None, None) # initial load of the data curdoc().add_root(HBox(inputs, plot, width=1100))
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, 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 hover_layer = HoverLayer() hover_layer.field_name = self.model.field_title hover_layer.is_categorical = self.model.field in self.model.categorical_fields self.fig.renderers.append(hover_layer.renderer) self.fig.add_tools(hover_layer.tool) self.model.hover_layer = hover_layer 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])
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 load_spectra(): #'/Users/guillaumeshippee/Desktop/splat-master/reference/Spectra/10001_10443.fits' #change if request.method == 'GET': return render_template('input.html', error='') else: # for k in list(request.form.keys()): # print(k,request.form[k]) # search by file "upload" if request.form['submit'] == 'Load File': try: path = request.form['path'] sp = splat.Spectrum(file=str(path)) sp = [sp] except: return render_template( 'input.html', error="\n\nProblem with file upload button") # search by file path specification if request.form['submit'] == 'Load File ': try: path = request.form['path'] sp = splat.Spectrum(file=str(path)) sp = [sp] except: return render_template( 'input.html', error="\n\nProblem with file path specification") # search by spectrum key if request.form['submit'] == 'Load by ID': try: sp = splat.Spectrum(int(str(request.form['key']))) sp = [sp] except: return render_template( 'input.html', error="\n\nProblem with key specification") # search by date observed if request.form['submit'] == 'Load by Date': try: sp = splat.getSpectrum(date=str(request.form['date'])) except: return render_template( 'input.html', error="\n\nProblem with key specification") # search by shortname elif request.form['submit'] == 'Load by Shortname': try: sp = splat.getSpectrum( shortname=str(request.form['shortname'])) except: return render_template( 'input.html', error="\n\nProblem with specifying file by shortname") # search by name elif request.form['submit'] == 'Load by Name': try: sp = splat.getSpectrum(name=str(request.form['name'])) except: return render_template( 'input.html', error="\n\nProblem with specifying file by name") # search by options elif request.form['submit'] == 'Load by Options': sp1 = request.form['sp1'] sp2 = request.form['sp2'] mag1 = request.form['mag1'] mag2 = request.form['mag2'] if sp2 == '': sp = sp1 elif sp1 == '': sp2 = sp1 elif sp1 == '' and sp2 == '': sp = '' else: sp = [sp1, sp2] if mag2 == '': mag = mag1 elif sp1 == '': mag2 = mag1 elif sp1 == '' and sp2 == '': mag = '' else: mag = [mag1, mag2] kwargs = { 'spt': sp, 'jmag': mag, 'snr': request.form['snr'], 'date': request.form['date'] } kwargs = {k: v for k, v in kwargs.items() if v} try: sp = splat.getSpectrum(**kwargs) except: return render_template('input.html', error="\n\nProblem with option search") # lucky pull elif request.form['submit'] == 'Get Lucky!': sp = splat.getSpectrum(lucky=True) if len(sp) == 0: return render_template( 'input.html', error="\n\nNo spectra matched search constratins") try: tab = [] for s in sp: spectral_type = splat.classifyByStandard(s)[0] mpl_fig = splot.plotSpectrum(s, web=True, uncertainty=True)[0] bokehfig = mpl.to_bokeh(fig=mpl_fig) bokehfig.set(x_range=Range1d(.8, 2.4), y_range=Range1d(0, s.fluxMax().value * 1.2)) # sys.stdout = open("out1.txt", "w") # sys.stdout = sys.__stdout__ # with open("out1.txt", "r") as f: # content = f.read() content = s.info(printout=False) # print(content) p = Paragraph(text=content) widget = VBox(bokehfig, p) tab.append(Panel(child=widget, title=str(s.name))) # tab.append(Panel(child=widget, title=str(spectral_type)+ " Star")) plottabs = Tabs(tabs=tab) script, div_dict = components({"plot": tab}) except: return render_template('input.html', error="\n\nProblem Plotting Spectra") return render_template('output.html', star_type=spectral_type, script=script, div=div_dict)
'Boston': { 'airport': 'BOS', 'title': 'Boston, MA', }, '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) tplot = make_temperature_plot(source, cities[city]['title']) pplot = make_precipitation_plot(source) city_select.on_change('value', update_plot) distribution_select.on_change('value', update_plot) controls = VBox(city_select, distribution_select) # add to document curdoc().add_root( HBox(controls, GridPlot(children=[[tplot], [pplot]], toolbar_location=None), width=1200))