label_data = ColumnDataSource( data=dict(x=[1, 2, 3], y=[0, 0, 0], t=['Original', 'Normal', 'Uniform'])) label_set = LabelSet(x='x', y='y', text='t', y_offset=-4, source=label_data, render_mode='css', text_baseline="top", text_align='center') p.add_layout(label_set) callback = CustomJS(args=dict(source=source, normal=normal, uniform=uniform), code=""" const data = source.data; for (var i = 0; i < data.y.length; i++) { data.xn[i] = normal.compute(data.x[i] + 1); } for (var i = 0; i < data.y.length; i++) { data.xu[i] = uniform.compute(data.x[i] + 2); } source.change.emit(); """) button = Button(label='Press to apply Jitter!', width=300) button.js_on_click(callback) output_file("transform_jitter.html", title="Example Jitter Transform") show(Column(button, p))
# Set up callbacks def update_title(attrname, old, new): plot.title.text = 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 = Column(text, offset, amplitude, phase, freq) curdoc().add_root(row(inputs, plot, width=800)) curdoc().title = 'Sliders'
def plot_waveform_bokeh(filename,waveform_list,metadata_list,station_lat_list,\ station_lon_list, event_lat, event_lon, boundary_data, style_parameter): xlabel_fontsize = style_parameter['xlabel_fontsize'] # map_station_location_bokeh = ColumnDataSource(data=dict(map_lat_list=station_lat_list,\ map_lon_list=station_lon_list)) dot_default_index = 0 selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[station_lat_list[dot_default_index]],\ lon=[station_lon_list[dot_default_index]],\ index=[dot_default_index])) map_view = Figure(plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['map_view_plot_height'], \ y_range=[style_parameter['map_view_lat_min'],\ style_parameter['map_view_lat_max']], x_range=[style_parameter['map_view_lon_min'],\ style_parameter['map_view_lon_max']], tools=style_parameter['map_view_tools'],\ title=style_parameter['map_view_title']) # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='gray',\ line_width=2, level='underlay', nonselection_line_alpha=1.0,\ nonselection_line_color='gray') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='gray',\ level='underlay', nonselection_line_alpha=1.0,\ nonselection_line_color='gray') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='gray',\ line_width=2, nonselection_line_alpha=1.0, level='underlay', nonselection_line_color='gray') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='gray',\ level='underlay', nonselection_line_alpha=1.0,\ nonselection_line_color='gray') # map_view.triangle('map_lon_list', 'map_lat_list', source=map_station_location_bokeh, \ line_color='gray', size=style_parameter['marker_size'], fill_color='black',\ selection_color='black', selection_line_color='gray',\ selection_fill_alpha=1.0,\ nonselection_fill_alpha=1.0, nonselection_fill_color='black',\ nonselection_line_color='gray', nonselection_line_alpha=1.0) map_view.triangle('lon','lat', source=selected_dot_on_map_bokeh,\ size=style_parameter['selected_marker_size'], line_color='black',fill_color='red') map_view.asterisk([event_lon], [event_lat], size=style_parameter['event_marker_size'], line_width=3, line_color='red', \ fill_color='red') # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # -------------------------------------------------------- max_waveform_length = 0 max_waveform_amp = 0 ncurve = len(waveform_list) for a_sta in waveform_list: for a_trace in a_sta: if len(a_trace) > max_waveform_length: max_waveform_length = len(a_trace) if np.max(np.abs(a_trace)) > max_waveform_amp: max_waveform_amp = np.max(np.abs(a_trace)) # plotting_list = [] for a_sta in waveform_list: temp = [] for a_trace in a_sta: if len(a_trace) < max_waveform_length: a_trace = np.append( a_trace, np.zeros([(max_waveform_length - len(a_trace)), 1])) temp.append(list(a_trace)) plotting_list.append(temp) # time_list = [] for ista in range(len(plotting_list)): a_sta = plotting_list[ista] temp = [] for itr in range(len(a_sta)): a_trace = a_sta[itr] delta = metadata_list[ista][itr]['delta'] time = list(np.arange(len(a_trace)) * delta) temp.append(time) # time_list.append(temp) # reftime_label_list = [] channel_label_list = [] for ista in range(len(metadata_list)): temp_ref = [] temp_channel = [] a_sta = metadata_list[ista] for a_trace in a_sta: temp_ref.append('Starting from ' + a_trace['starttime']) temp_channel.append(a_trace['network'] + '_' + a_trace['station'] + '_' + a_trace['channel']) reftime_label_list.append(temp_ref) channel_label_list.append(temp_channel) # -------------------------------------------------------- curve_fig01 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \ y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \ x_range=(0,max_waveform_length),\ tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) # curve_index = 0 select_curve_data = plotting_list[dot_default_index][curve_index] select_curve_time = time_list[dot_default_index][curve_index] selected_curve_data_bokeh01 = ColumnDataSource( data=dict(time=select_curve_time, amp=select_curve_data)) select_reftime_label = reftime_label_list[dot_default_index][curve_index] selected_reftime_label_bokeh01 = ColumnDataSource(data=dict(x=[style_parameter['curve_reftime_label_x']],\ y=[style_parameter['curve_reftime_label_y']],\ label=[select_reftime_label])) select_channel_label = channel_label_list[dot_default_index][curve_index] selected_channel_label_bokeh01 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\ y=[style_parameter['curve_channel_label_y']],\ label=[select_channel_label])) all_curve_data_bokeh = ColumnDataSource( data=dict(t=time_list, amp=plotting_list)) all_reftime_label_bokeh = ColumnDataSource(data=dict( label=reftime_label_list)) all_channel_label_bokeh = ColumnDataSource(data=dict( label=channel_label_list)) # plot waveform curve_fig01.line('time','amp', source=selected_curve_data_bokeh01,\ line_color='black') # add refference time as a label curve_fig01.text('x', 'y', 'label', source=selected_reftime_label_bokeh01) # add channel label curve_fig01.text('x', 'y', 'label', source=selected_channel_label_bokeh01) # change style curve_fig01.title.text_font_size = style_parameter['title_font_size'] curve_fig01.title.align = 'center' curve_fig01.title.text_font_style = 'normal' curve_fig01.xaxis.axis_label = style_parameter['curve_xlabel'] curve_fig01.xaxis.axis_label_text_font_style = 'normal' curve_fig01.xaxis.axis_label_text_font_size = xlabel_fontsize curve_fig01.xaxis.major_label_text_font_size = xlabel_fontsize curve_fig01.yaxis.axis_label = style_parameter['curve_ylabel'] curve_fig01.yaxis.axis_label_text_font_style = 'normal' curve_fig01.yaxis.axis_label_text_font_size = xlabel_fontsize curve_fig01.yaxis.major_label_text_font_size = xlabel_fontsize curve_fig01.toolbar.logo = None curve_fig01.toolbar_location = 'above' curve_fig01.toolbar_sticky = False # -------------------------------------------------------- curve_fig02 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \ y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \ x_range=(0,max_waveform_length),\ tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) # curve_index = 1 select_curve_data = plotting_list[dot_default_index][curve_index] select_curve_time = time_list[dot_default_index][curve_index] selected_curve_data_bokeh02 = ColumnDataSource( data=dict(time=select_curve_time, amp=select_curve_data)) select_channel_label = channel_label_list[dot_default_index][curve_index] selected_channel_label_bokeh02 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\ y=[style_parameter['curve_channel_label_y']],\ label=[select_channel_label])) # plot waveform curve_fig02.line('time','amp', source=selected_curve_data_bokeh02,\ line_color='black') # add channel label curve_fig02.text('x', 'y', 'label', source=selected_channel_label_bokeh02) # change style curve_fig02.title.text_font_size = style_parameter['title_font_size'] curve_fig02.title.align = 'center' curve_fig02.title.text_font_style = 'normal' curve_fig02.xaxis.axis_label = style_parameter['curve_xlabel'] curve_fig02.xaxis.axis_label_text_font_style = 'normal' curve_fig02.xaxis.axis_label_text_font_size = xlabel_fontsize curve_fig02.xaxis.major_label_text_font_size = xlabel_fontsize curve_fig02.yaxis.axis_label = style_parameter['curve_ylabel'] curve_fig02.yaxis.axis_label_text_font_style = 'normal' curve_fig02.yaxis.axis_label_text_font_size = xlabel_fontsize curve_fig02.yaxis.major_label_text_font_size = xlabel_fontsize curve_fig02.toolbar.logo = None curve_fig02.toolbar_location = 'above' curve_fig02.toolbar_sticky = False # -------------------------------------------------------- curve_fig03 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \ y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \ x_range=(0,max_waveform_length),\ tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) # curve_index = 2 select_curve_data = plotting_list[dot_default_index][curve_index] select_curve_time = time_list[dot_default_index][curve_index] selected_curve_data_bokeh03 = ColumnDataSource( data=dict(time=select_curve_time, amp=select_curve_data)) select_channel_label = channel_label_list[dot_default_index][curve_index] selected_channel_label_bokeh03 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\ y=[style_parameter['curve_channel_label_y']],\ label=[select_channel_label])) # plot waveform curve_fig03.line('time','amp', source=selected_curve_data_bokeh03,\ line_color='black') # add channel label curve_fig03.text('x', 'y', 'label', source=selected_channel_label_bokeh03) # change style curve_fig03.title.text_font_size = style_parameter['title_font_size'] curve_fig03.title.align = 'center' curve_fig03.title.text_font_style = 'normal' curve_fig03.xaxis.axis_label = style_parameter['curve_xlabel'] curve_fig03.xaxis.axis_label_text_font_style = 'normal' curve_fig03.xaxis.axis_label_text_font_size = xlabel_fontsize curve_fig03.xaxis.major_label_text_font_size = xlabel_fontsize curve_fig03.yaxis.axis_label = style_parameter['curve_ylabel'] curve_fig03.yaxis.axis_label_text_font_style = 'normal' curve_fig03.yaxis.axis_label_text_font_size = xlabel_fontsize curve_fig03.yaxis.major_label_text_font_size = xlabel_fontsize curve_fig03.toolbar.logo = None curve_fig03.toolbar_location = 'above' curve_fig03.toolbar_sticky = False # -------------------------------------------------------- map_station_location_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_station_location_bokeh=map_station_location_bokeh,\ selected_curve_data_bokeh01=selected_curve_data_bokeh01,\ selected_curve_data_bokeh02=selected_curve_data_bokeh02,\ selected_curve_data_bokeh03=selected_curve_data_bokeh03,\ selected_channel_label_bokeh01=selected_channel_label_bokeh01,\ selected_channel_label_bokeh02=selected_channel_label_bokeh02,\ selected_channel_label_bokeh03=selected_channel_label_bokeh03,\ selected_reftime_label_bokeh01=selected_reftime_label_bokeh01,\ all_reftime_label_bokeh=all_reftime_label_bokeh,\ all_channel_label_bokeh=all_channel_label_bokeh,\ all_curve_data_bokeh=all_curve_data_bokeh), code=""" var inds = cb_obj.indices selected_dot_on_map_bokeh.data['index'] = [inds] var new_loc = map_station_location_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [new_loc['map_lat_list'][inds]] selected_dot_on_map_bokeh.data['lon'] = [new_loc['map_lon_list'][inds]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh01.data['t'] = all_curve_data_bokeh.data['t'][inds][0] selected_curve_data_bokeh01.data['amp'] = all_curve_data_bokeh.data['amp'][inds][0] selected_curve_data_bokeh01.change.emit() selected_curve_data_bokeh02.data['t'] = all_curve_data_bokeh.data['t'][inds][1] selected_curve_data_bokeh02.data['amp'] = all_curve_data_bokeh.data['amp'][inds][1] selected_curve_data_bokeh02.change.emit() selected_curve_data_bokeh03.data['t'] = all_curve_data_bokeh.data['t'][inds][2] selected_curve_data_bokeh03.data['amp'] = all_curve_data_bokeh.data['amp'][inds][2] selected_curve_data_bokeh03.change.emit() selected_reftime_label_bokeh01.data['label'] = [all_reftime_label_bokeh.data['label'][inds][0]] selected_reftime_label_bokeh01.change.emit() selected_channel_label_bokeh01.data['label'] = [all_channel_label_bokeh.data['label'][inds][0]] selected_channel_label_bokeh01.change.emit() selected_channel_label_bokeh02.data['label'] = [all_channel_label_bokeh.data['label'][inds][1]] selected_channel_label_bokeh02.change.emit() selected_channel_label_bokeh03.data['label'] = [all_channel_label_bokeh.data['label'][inds][2]] selected_channel_label_bokeh03.change.emit() """) # map_station_location_bokeh.selected.js_on_change('indices', map_station_location_js) # curve_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_station_location_bokeh=map_station_location_bokeh,\ selected_curve_data_bokeh01=selected_curve_data_bokeh01,\ selected_curve_data_bokeh02=selected_curve_data_bokeh02,\ selected_curve_data_bokeh03=selected_curve_data_bokeh03,\ selected_channel_label_bokeh01=selected_channel_label_bokeh01,\ selected_channel_label_bokeh02=selected_channel_label_bokeh02,\ selected_channel_label_bokeh03=selected_channel_label_bokeh03,\ selected_reftime_label_bokeh01=selected_reftime_label_bokeh01,\ all_reftime_label_bokeh=all_reftime_label_bokeh,\ all_channel_label_bokeh=all_channel_label_bokeh,\ all_curve_data_bokeh=all_curve_data_bokeh),code=""" var inds = Math.round(cb_obj.value) selected_dot_on_map_bokeh.data['index'] = [inds] var new_loc = map_station_location_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [new_loc['map_lat_list'][inds]] selected_dot_on_map_bokeh.data['lon'] = [new_loc['map_lon_list'][inds]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh01.data['t'] = all_curve_data_bokeh.data['t'][inds][0] selected_curve_data_bokeh01.data['amp'] = all_curve_data_bokeh.data['amp'][inds][0] selected_curve_data_bokeh01.change.emit() selected_curve_data_bokeh02.data['t'] = all_curve_data_bokeh.data['t'][inds][1] selected_curve_data_bokeh02.data['amp'] = all_curve_data_bokeh.data['amp'][inds][1] selected_curve_data_bokeh02.change.emit() selected_curve_data_bokeh03.data['t'] = all_curve_data_bokeh.data['t'][inds][2] selected_curve_data_bokeh03.data['amp'] = all_curve_data_bokeh.data['amp'][inds][2] selected_curve_data_bokeh03.change.emit() selected_reftime_label_bokeh01.data['label'] = [all_reftime_label_bokeh.data['label'][inds][0]] selected_reftime_label_bokeh01.change.emit() selected_channel_label_bokeh01.data['label'] = [all_channel_label_bokeh.data['label'][inds][0]] selected_channel_label_bokeh01.change.emit() selected_channel_label_bokeh02.data['label'] = [all_channel_label_bokeh.data['label'][inds][1]] selected_channel_label_bokeh02.change.emit() selected_channel_label_bokeh03.data['label'] = [all_channel_label_bokeh.data['label'][inds][2]] selected_channel_label_bokeh03.change.emit() """) curve_slider = Slider(start=0, end=ncurve-1, value=style_parameter['curve_default_index'], \ step=1, title=style_parameter['curve_slider_title'], width=style_parameter['map_view_plot_width'],\ height=50) curve_slider.js_on_change('value', curve_slider_callback) curve_slider_callback.args['curve_index'] = curve_slider # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text=style_parameter['annotating_html02'],\ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== output_file(filename, title=style_parameter['html_title'], mode=style_parameter['library_source']) # left_fig = Column(curve_slider, map_view, annotating_fig01, width=style_parameter['left_column_width']) right_fig = Column(curve_fig01, curve_fig02, curve_fig03, annotating_fig02, width=style_parameter['right_column_width']) layout = Row(left_fig, right_fig) save(layout)
selectType.on_change("value",typeChange) def updatePlot(): setMapColorRange() newfig=plotAvgTrend() graphColumn.children[2]=newfig new_countryMap=createMap() mapColum.children[0]=new_countryMap def slider_update(attrname, old, new): global year year=new new_countryMap=createMap() mapColum.children[0]=new_countryMap slider = Slider(start=1973, end=2017, value=2017, step=1, title="Year") slider.on_change('value', slider_update) div = Div(text=""" <p>All source data is from the Begian governement at <a href=https://statbel.fgov.be/en target="_blank">https://statbel.fgov.be/en</a>.</br> All data are averages.</br> For communes where no data was available at all the average was set at 0.</br> For years where no data was available the average was set to the same value as the year before.</br> <b>The interactive graph was made by <a href=mailto:[email protected] >Joris Meert</a> for educational purpose.</b></p> """,width=700, height=100) graphColumn=Column(selectType,Row(selectCommune1,selectCommune2),fig,selectYaxis,div) mapColum=Column(countryMap,Row(slider,button)) layout=Row(graphColumn,mapColum) curdoc().add_root(layout) curdoc().title="Belgian house market"
def initialize_plot(self, plots=None, ranges=None): ranges = self.compute_ranges(self.layout, self.keys[-1], None) opts = self.layout.opts.get('plot', self.backend) opts = {} if opts is None else opts.kwargs plot_grid = self._compute_grid() passed_plots = [] if plots is None else plots r_offset = 0 col_offsets = defaultdict(int) tab_plots = [] stretch_width = False stretch_height = False for r in range(self.rows): # Compute row offset row = [(k, sp) for k, sp in self.subplots.items() if k[0] == r] row_padded = any(len(sp.layout) > 2 for k, sp in row) if row_padded: r_offset += 1 for c in range(self.cols): subplot = self.subplots.get((r, c), None) # Compute column offset col = [(k, sp) for k, sp in self.subplots.items() if k[1] == c] col_padded = any(len(sp.layout) > 1 for k, sp in col) if col_padded: col_offsets[r] += 1 c_offset = col_offsets.get(r, 0) if subplot is None: continue shared_plots = list(passed_plots) if self.shared_axes else None subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots) nsubplots = len(subplots) modes = { sp.sizing_mode for sp in subplots if sp.sizing_mode not in (None, 'auto', 'fixed') } sizing_mode = self.sizing_mode if modes: responsive_width = any(s in m for m in modes for s in ('width', 'both')) responsive_height = any(s in m for m in modes for s in ('height', 'both')) stretch_width |= responsive_width stretch_height |= responsive_height if responsive_width and responsive_height: sizing_mode = 'stretch_both' elif responsive_width: sizing_mode = 'stretch_width' elif responsive_height: sizing_mode = 'stretch_height' # If tabs enabled lay out AdjointLayout on grid if self.tabs: title = subplot.subplots['main']._format_title( self.keys[-1], dimensions=False) if not title: title = ' '.join(self.paths[r, c]) if nsubplots == 1: grid = subplots[0] elif nsubplots == 2: grid = gridplot([subplots], merge_tools=self.merge_tools, toolbar_location=self.toolbar, sizing_mode=sizing_mode) else: grid = [[subplots[2], None], subplots[:2]] grid = gridplot(children=grid, merge_tools=self.merge_tools, toolbar_location=self.toolbar, sizing_mode=sizing_mode) tab_plots.append((title, grid)) continue # Situate plot in overall grid if nsubplots > 2: plot_grid[r + r_offset - 1][c + c_offset - 1] = subplots[2] plot_column = plot_grid[r + r_offset] if nsubplots > 1: plot_column[c + c_offset - 1] = subplots[0] plot_column[c + c_offset] = subplots[1] else: plot_column[c + c_offset - int(col_padded)] = subplots[0] passed_plots.append(subplots[0]) if 'sizing_mode' in opts: sizing_mode = opts['sizing_mode'] elif stretch_width and stretch_height: sizing_mode = 'stretch_both' elif stretch_width: sizing_mode = 'stretch_width' elif stretch_height: sizing_mode = 'stretch_height' else: sizing_mode = None # Wrap in appropriate layout model if self.tabs: plots = filter_toolboxes([p for t, p in tab_plots]) panels = [Panel(child=child, title=t) for t, child in tab_plots] layout_plot = Tabs(tabs=panels, sizing_mode=sizing_mode) else: plot_grid = filter_toolboxes(plot_grid) layout_plot = gridplot(children=plot_grid, toolbar_location=self.toolbar, merge_tools=self.merge_tools, sizing_mode=sizing_mode) title = self._get_title_div(self.keys[-1]) if title: self.handles['title'] = title layout_plot = Column(title, layout_plot, sizing_mode=sizing_mode) self.handles['plot'] = layout_plot self.handles['plots'] = plots if self.shared_datasource: self.sync_sources() if self.top_level: self.init_links() self.drawn = True return self.handles['plot']
def large_plot(n: int) -> Tuple[Model, Set[Model]]: from bokeh.models import ( BoxSelectTool, BoxZoomTool, Column, ColumnDataSource, DataRange1d, GlyphRenderer, Grid, Line, LinearAxis, PanTool, Plot, ResetTool, SaveTool, WheelZoomTool, ZoomInTool, ZoomOutTool, ) col = Column() objects: Set[Model] = {col} for i in range(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis() plot.add_layout(xaxis, "below") yaxis = LinearAxis() plot.add_layout(yaxis, "left") xgrid = Grid(dimension=0) plot.add_layout(xgrid, "center") ygrid = Grid(dimension=1) plot.add_layout(ygrid, "center") tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() save = SaveTool() reset = ResetTool() tools = [ pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset ] plot.add_tools(*tools) col.children.append(plot) objects |= set([ xdr, ydr, xaxis, xaxis.major_label_policy, yaxis, yaxis.major_label_policy, xgrid, ygrid, renderer, renderer.view, glyph, source, source.selected, source.selection_policy, plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title, box_zoom.overlay, box_select.overlay, ] + tickers + tools) return col, objects
def FrecuenciaCardiaca(DatosBokeh, EjeX, MetricasAuxiliares): """ GRAFICO AREA | FRECUENCIA CARDIACA """ # Creacion del diccionario de metricas auxiliares DiccionarioVariables = ParametrosVariables(DatosBokeh) # Generacion del codigo JavaScript que habilita la visualizacion de metricas auxiliares CodigoJS = GeneracionCodigoJS(MetricasAuxiliares) # Asignacion de tamaño del punto en graficas discretas SizeCircle = FunctionSizeCircle(DatosBokeh) # Creacion de un grafica PLT = figure(width=1000, height=400, x_range=(DatosBokeh.data[EjeX].min(), DatosBokeh.data[EjeX].max()), y_range=(LimiteEjeY(DatosBokeh, 'FRECUENCIA CARDIACA', 'Inferior'), LimiteEjeY(DatosBokeh, 'FRECUENCIA CARDIACA', 'Superior')), tools='', toolbar_location=None) # Creacion del area bajo la linea de la metrica a partir del CDS Area = DatosBokeh.to_df().copy().reset_index()[[ EjeX, 'FrecuenciaCardiaca[ppm]' ]].set_index(EjeX) Area.rename(columns={'FrecuenciaCardiaca[ppm]': 'Area'}, inplace=True) AreaBottom = Area[::-1] AreaBottom['Area'] = 0 PLT.patch(x=hstack((AreaBottom.index, Area.index)), y=hstack((AreaBottom['Area'], Area['Area'])), color=Grapefruit[1], alpha=1, line_color=None) # Inclusion de datos PLT_Linea = PLT.line(EjeX, 'FrecuenciaCardiaca[ppm]', source=DatosBokeh, color=Grapefruit[2], line_width=2, line_cap='round') PLT.add_tools( HoverTool(tooltips=[('', '@{FrecuenciaCardiaca[ppm]}{int} ppm')], renderers=[PLT_Linea], mode='vline')) PLT_Max = PLT.inverted_triangle( DatosBokeh.data[EjeX][list( DatosBokeh.data['FrecuenciaCardiaca[ppm]']).index( DatosBokeh.data['FrecuenciaCardiaca[ppm]'].max())], DatosBokeh.data['FrecuenciaCardiaca[ppm]'].max(), size=10, line_color=DarkGray[1], line_width=2, fill_color=LightGray[1]) PLT.add_tools( HoverTool(tooltips=[ ('Maximo', str(DatosBokeh.data['FrecuenciaCardiaca[ppm]'].max()) + ' ppm') ], renderers=[PLT_Max], mode='mouse')) PLT.add_layout( Span(location=DatosBokeh.data['FrecuenciaCardiaca[ppm]'].mean(), dimension='width', line_color=Grapefruit[0], line_dash='dashed', line_width=1, line_alpha=1)) # Inclusion de lineas auxiliares ListadoMetricasAuxiliares = {} for Metrica in MetricasAuxiliares: if DiccionarioVariables[Metrica]['Tipo'] == 'circle': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.circle( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['FRECUENCIA CARDIACA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], size=SizeCircle, line_color=DiccionarioVariables[Metrica]['Color'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) elif DiccionarioVariables[Metrica]['Tipo'] == 'step': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.step( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['FRECUENCIA CARDIACA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) else: ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.line( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['FRECUENCIA CARDIACA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) # Atributos PLT.title.text = 'FRECUENCIA CARDIACA' PLT.sizing_mode = 'fixed' PLT.yaxis.axis_label = 'Frecuencia cardiaca [ppm]' PLT.yaxis.formatter = NumeralTickFormatter(format='0') PLT.grid.visible = False PLT.yaxis.minor_tick_line_color = None PLT.yaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['FrecuenciaCardiaca[ppm]'], 10, 1) # Asignacion de opciones de visualizacion del eje X if EjeX == 'Distancia[m]': PLT.xaxis.axis_label = 'Distancia' PLT.xaxis.formatter = NumeralTickFormatter(format='0') if DatosBokeh.data['Distancia[m]'].max() >= 4000: PLT.xaxis.ticker = SingleIntervalTicker(interval=1000) PLT.xaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['Distancia[m]'], 1000, 1000, 0, 0) elif EjeX == 'TiempoActividad': PLT.xaxis.axis_label = 'Tiempo actividad' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() elif EjeX == 'TiempoTotal': PLT.xaxis.axis_label = 'Tiempo total' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() #Botones Botones = CheckboxGroup(labels=MetricasAuxiliares, active=[], width=100, height=380) ListadoMetricasAuxiliares['checkbox'] = Botones CodigoJSFrecuenciaCardiaca = CustomJS(code=CodigoJS, args=ListadoMetricasAuxiliares) Botones.js_on_click(CodigoJSFrecuenciaCardiaca) #Layout GridBotones = layout( [Spacer(width=100, height=25), Column(Botones, width=100, height=375)], sizing_mode='fixed', width=100, height=400) GridGrafica = gridplot([PLT, GridBotones], ncols=2, sizing_mode='stretch_width', toolbar_location=None, plot_width=1100, plot_height=400) return GridGrafica
args = document.session_context.request.arguments try: file = args['file'][0].decode('ascii') user = args['user'][0].decode('ascii') except KeyError as e: raise KeyError( str(e) + '. Filename and username must be provided as request parameters.') # find path for result data results_path = join(UPLOAD_FOLDER, user, file, 'results') p = Paragraph(text="", width=500) layout = Column(children=[p]) layer_activation_source = ColumnDataSource(data=dict()) def create_image_grid(filters): no_of_images = len(filters) if no_of_images < 4: no_of_rows = 1 elif no_of_images < 64: no_of_rows = 4 else: no_of_rows = 8
var data = source.data; var dx = 6 / %d; if (mode == 'None') { data['x'] = []; data['y'] = []; } else { if (mode == 'Linear') { interp = linear; } else if (mode == 'Step (before)') { interp = step; step.mode = 'before'; } else if (mode == 'Step (center)') { interp = step; step.mode = 'center'; } else if (mode == 'Step (after)') { interp = step; step.mode = 'after'; } for (var i = 0; i < %d; i++) { data['x'][i] = i * dx data['y'][i] = interp.compute(data['x'][i]) } } source.change.emit() """ % (N, N)) mode = Select( title='Interpolation Mode', value='None', options=['None', 'Linear', 'Step (before)', 'Step (center)', 'Step (after)'], callback=callback) output_file("transform_interpolator.html", title="Example Transforms") show(Column(WidgetBox(mode,width=300), p))
else: #If the number of stations deployed is max, display message print("Max number of stations reached") # #----------------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------------- #-------------------------------This allows you to interact with the drone sim button to start the drone simulation----------------------- #----------------------------------------------------------------------------------------------------------------------------------------- # def callbackSimRun(event): eventTrigger(coordList) # #----------------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------------- #These plot the new stations and the button to run the simulation p.on_event(DoubleTap, callback) button_widget.on_event(ButtonClick, callbackSimRun) #This sets the layout of the plot layout=Column(p,widgetbox(button_widget)) #This updates the plot to the server curdoc().add_root(layout)
def bar_cam(sni_csub, sni_dsub): # make data sources def make_camr_src(cmr): data = { 'NVF': sni_csub[sni_csub['CAMR'] == cmr]['NVF'], 'NB': sni_csub[sni_csub['CAMR'] == cmr]['Count'] } return data def make_dr_src(dr): data = { 'NVF': sni_dsub[sni_dsub['DR'] == dr]['NVF'], 'NB': sni_dsub[sni_dsub['DR'] == dr]['Count'] } return data # make plots def make_plots(src1, src2): nvf = list(sni_csub['NVF'].unique()) color_map = factor_cmap(field_name='NVF', palette=GnBu[8], factors=nvf) # define figure and plot p1 p1 = figure( title='Répartition du PTF de la CAM CORPORATE par classe de risque', plot_height=450, plot_width=600, x_axis_label='Rating Class', y_axis_label='Number of rated clients', x_range=nvf, toolbar_location='below') p1.vbar(x='NVF', top='NB', source=src1, width=0.5, color='#2B7C75') #p1.line('NVF', 'NB', source=src1, color='red') p1.toolbar.active_drag = None hover1 = HoverTool(tooltips=[('NVF', '@NVF'), ('NB Rated', '@NB')]) p1.add_tools(hover1) labels1 = LabelSet(x='NVF', y='NB', text='NB', level='glyph', x_offset=0, y_offset=1, source=src1, render_mode='canvas', text_align='center', text_font_style='bold', text_font_size='10pt') p1.add_layout(labels1) # define figure and plot p2 p2 = figure( title='Répartition du PTF de la CAM CORPORATE par classe de risque', plot_height=450, plot_width=600, x_axis_label='Rating Class', y_axis_label='Number of rated clients', x_range=nvf, toolbar_location='below') p2.vbar(x='NVF', top='NB', source=src2, width=0.5, color='#2D7D3E') #p2.line('NVF', 'NB', source=src2, color='black') p2.toolbar.active_drag = None hover2 = HoverTool(tooltips=[('NVF', '@NVF'), ('NB Rated', '@NB')]) p2.add_tools(hover2) labels2 = LabelSet(x='NVF', y='NB', text='NB', level='glyph', x_offset=0, y_offset=1, source=src2, render_mode='canvas', text_align='center', text_font_style='bold', text_font_size='10pt') p2.add_layout(labels2) return p1, p2 # plot style def style(p): p.xgrid.visible = False p.ygrid.visible = False p.yaxis.visible = False # title p.title.align = 'center' p.title.text_font_size = '12pt' p.title.text_font = 'times' # Axis titles p.xaxis.axis_label_text_font_size = '11pt' p.xaxis.axis_label_text_font_style = 'bold italic' p.yaxis.axis_label_text_font_size = '11pt' p.yaxis.axis_label_text_font_style = 'bold italic' # Tick labels p.xaxis.major_label_text_font_size = '9pt' p.yaxis.major_label_text_font_size = '9pt' p.border_fill_color = None p.outline_line_color = None return p # callback 1 def update_plot1(attr, old, new): # read the current value of the dropdown cmr = camr_select.value # set new_data new_data = make_camr_src(cmr) # Assign new_data to the original source src1.data = new_data p1.title.text = 'Répartition du PTF de la %s par classe de risque' % cmr # callback 2 def update_plot2(attr, old, new): # read the current value of the dropdown dr = dr_select.value # set new_data new_data = make_dr_src(dr) # Assign new_data to the original source src2.data = new_data p2.title.text = 'Répartition du PTF de la %s par classe de risque' % dr def table(src1, src2): col1 = [ TableColumn(field='NVF', title='Rating Class'), TableColumn(field='NB', title='Clients Rated') ] tbl1 = DataTable(source=src1, columns=col1, editable=True, width=600) col2 = [ TableColumn(field='NVF', title='Rating Class'), TableColumn(field='NB', title='Clients Rated') ] tbl2 = DataTable(source=src2, columns=col2, editable=True, width=600) return tbl1, tbl2 camr_select = Select(options=list(sni_csub['CAMR'].unique()), value='CAM CORPORATE', title='Choisir une CAM Region') # attach the update to the value camr_select.on_change('value', update_plot1) dr_select = Select(options=list(sni_dsub['DR'].unique()), value='CAM CORPORATE', title='Choisir une DR') # attach the update to the value dr_select.on_change('value', update_plot2) camr_select.width = 600 # Data data1 = make_camr_src(camr_select.value) data2 = make_dr_src(dr_select.value) src1 = ColumnDataSource(data=data1) src2 = ColumnDataSource(data=data2) p1, p2 = make_plots(src1, src2) p1 = style(p1) p2 = style(p2) tbl1, tbl2 = table(src1, src2) layout = row([ column([Column(camr_select, width=500), p1, tbl1]), column([Column(dr_select, width=500), p2, tbl2]) ]) tab = Panel(child=layout, title='Rating class distribution') return tab
def plot_3DModel_bokeh(filename, map_data_all_slices, map_depth_all_slices, \ color_range_all_slices, profile_data_all, boundary_data, \ style_parameter): ''' Plot shear velocity maps and velocity profiles using bokeh Input: filename is the filename of the resulting html file map_data_all_slices contains the velocity model parameters saved for map view plots map_depth_all_slices is a list of depths color_range_all_slices is a list of color ranges profile_data_all constains the velocity model parameters saved for profile plots boundary_data is a list of boundaries style_parameter contains plotting parameters Output: None ''' xlabel_fontsize = style_parameter['xlabel_fontsize'] # colorbar_data_all_left = [] colorbar_data_all_right = [] map_view_ndepth = style_parameter['map_view_ndepth'] ncolor = len(palette) colorbar_top = [0.1 for i in range(ncolor)] colorbar_bottom = [0 for i in range(ncolor)] map_data_all_slices_depth = [] for idepth in range(map_view_ndepth): color_min = color_range_all_slices[idepth][0] color_max = color_range_all_slices[idepth][1] color_step = (color_max - color_min)*1./ncolor colorbar_left = np.linspace(color_min,color_max-color_step,ncolor) colorbar_right = np.linspace(color_min+color_step,color_max,ncolor) colorbar_data_all_left.append(colorbar_left) colorbar_data_all_right.append(colorbar_right) map_depth = map_depth_all_slices[idepth] map_data_all_slices_depth.append('Depth: {0:8.1f} km'.format(map_depth)) # palette_r = palette[::-1] # data for the colorbar colorbar_data_one_slice = {} colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']] colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']] colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\ colorbar_left=colorbar_data_one_slice['colorbar_left'],\ colorbar_right=colorbar_data_one_slice['colorbar_right'],\ palette_r=palette_r)) colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\ colorbar_data_all_right=colorbar_data_all_right)) # map_view_label_lon = style_parameter['map_view_depth_label_lon'] map_view_label_lat = style_parameter['map_view_depth_label_lat'] map_data_one_slice_depth = map_data_all_slices_depth[style_parameter['map_view_default_index']] map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon], map_depth=[map_data_one_slice_depth], left=[style_parameter['profile_plot_xmin']], \ right=[style_parameter['profile_plot_xmax']])) # map_view_default_index = style_parameter['map_view_default_index'] #map_data_one_slice = map_data_all_slices[map_view_default_index] # map_color_all_slices = [] for i in range(len(map_data_all_slices)): vmin, vmax = color_range_all_slices[i] map_color = val_to_rgb(map_data_all_slices[i], palette_r, vmin, vmax) map_color_all_slices.append(map_color) map_color_one_slice = map_color_all_slices[map_view_default_index] # map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\ y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']*style_parameter['dlon']],\ dh=[style_parameter['nlat']*style_parameter['dlat']],map_data_one_slice=[map_color_one_slice])) map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_color_all_slices,\ map_data_all_slices_depth=map_data_all_slices_depth)) # ------------------------------ nprofile = len(profile_data_all) grid_lat_list = [] grid_lon_list = [] width_list = [] height_list = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] grid_lat_list.append(aprofile['lat']) grid_lon_list.append(aprofile['lon']) width_list.append(style_parameter['map_view_grid_width']) height_list.append(style_parameter['map_view_grid_height']) grid_data_bokeh = ColumnDataSource(data=dict(lon=grid_lon_list,lat=grid_lat_list,\ width=width_list, height=height_list)) profile_default_index = style_parameter['profile_default_index'] selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[grid_lat_list[profile_default_index]], \ lon=[grid_lon_list[profile_default_index]], \ width=[style_parameter['map_view_grid_width']],\ height=[style_parameter['map_view_grid_height']],\ index=[profile_default_index])) # ------------------------------ profile_vs_all = [] profile_depth_all = [] profile_ndepth = style_parameter['profile_ndepth'] profile_lat_label_list = [] profile_lon_label_list = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] vs_raw = aprofile['vs'] top_raw = aprofile['top'] profile_lat_label_list.append('Lat: {0:12.1f}'.format(aprofile['lat'])) profile_lon_label_list.append('Lon: {0:12.1f}'.format(aprofile['lon'])) vs_plot = [] depth_plot = [] for idepth in range(profile_ndepth): vs_plot.append(vs_raw[idepth]) depth_plot.append(top_raw[idepth]) vs_plot.append(vs_raw[idepth]) depth_plot.append(top_raw[idepth+1]) profile_vs_all.append(vs_plot) profile_depth_all.append(depth_plot) profile_data_all_bokeh = ColumnDataSource(data=dict(profile_vs_all=profile_vs_all, \ profile_depth_all=profile_depth_all)) selected_profile_data_bokeh = ColumnDataSource(data=dict(vs=profile_vs_all[profile_default_index],\ depth=profile_depth_all[profile_default_index])) selected_profile_lat_label_bokeh = ColumnDataSource(data=\ dict(x=[style_parameter['profile_lat_label_x']], y=[style_parameter['profile_lat_label_y']],\ lat_label=[profile_lat_label_list[profile_default_index]])) selected_profile_lon_label_bokeh = ColumnDataSource(data=\ dict(x=[style_parameter['profile_lon_label_x']], y=[style_parameter['profile_lon_label_y']],\ lon_label=[profile_lon_label_list[profile_default_index]])) all_profile_lat_label_bokeh = ColumnDataSource(data=dict(profile_lat_label_list=profile_lat_label_list)) all_profile_lon_label_bokeh = ColumnDataSource(data=dict(profile_lon_label_list=profile_lon_label_list)) # button_ndepth = style_parameter['button_ndepth'] button_data_all_vs = [] button_data_all_vp = [] button_data_all_rho = [] button_data_all_top = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] button_data_all_vs.append(aprofile['vs'][:button_ndepth]) button_data_all_vp.append(aprofile['vp'][:button_ndepth]) button_data_all_rho.append(aprofile['rho'][:button_ndepth]) button_data_all_top.append(aprofile['top'][:button_ndepth]) button_data_all_bokeh = ColumnDataSource(data=dict(button_data_all_vs=button_data_all_vs,\ button_data_all_vp=button_data_all_vp,\ button_data_all_rho=button_data_all_rho,\ button_data_all_top=button_data_all_top)) # ============================== map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \ tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \ y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\ x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']]) # map_view.image_rgba('map_data_one_slice',x='x',\ y='y',dw='dw',dh='dh', source=map_data_one_slice_bokeh, level='image') depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ map_data_all_slices_bokeh=map_data_all_slices_bokeh,\ colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\ colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\ map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code=""" var d_index = Math.round(cb_obj.value) var map_data_all_slices = map_data_all_slices_bokeh.data map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]] map_data_one_slice_bokeh.change.emit() var color_data_all_slices = colorbar_data_all_slices_bokeh.data colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index] colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index] colorbar_data_one_slice_bokeh.change.emit() map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]] map_data_one_slice_depth_bokeh.change.emit() """) depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \ value=map_view_default_index, step=1, \ width=style_parameter['map_view_plot_width'],\ title=style_parameter['depth_slider_title'], height=50, \ callback=depth_slider_callback) # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # ------------------------------ # add depth label map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \ width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \ width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\ text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay') # ------------------------------ map_view.rect('lon', 'lat', width='width', \ width_units='screen', height='height', \ height_units='screen', line_color='gray', line_alpha=0.5, \ selection_line_color='gray', selection_line_alpha=0.5, selection_fill_color=None,\ nonselection_line_color='gray',nonselection_line_alpha=0.5, nonselection_fill_color=None,\ source=grid_data_bokeh, color=None, line_width=1, level='glyph') map_view.rect('lon', 'lat',width='width', \ width_units='screen', height='height', \ height_units='screen', line_color='#00ff00', line_alpha=1.0, \ source=selected_dot_on_map_bokeh, fill_color=None, line_width=3.,level='glyph') # ------------------------------ grid_data_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh, \ grid_data_bokeh=grid_data_bokeh,\ profile_data_all_bokeh=profile_data_all_bokeh,\ selected_profile_data_bokeh=selected_profile_data_bokeh,\ selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\ selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \ all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \ all_profile_lon_label_bokeh=all_profile_lon_label_bokeh, \ ), code=""" var inds = cb_obj.indices var grid_data = grid_data_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][inds]] selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][inds]] selected_dot_on_map_bokeh.data['index'] = [inds] selected_dot_on_map_bokeh.change.emit() var profile_data_all = profile_data_all_bokeh.data selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][inds] selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][inds] selected_profile_data_bokeh.change.emit() var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list'] var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list'] selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[inds]] selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[inds]] selected_profile_lat_label_bokeh.change.emit() selected_profile_lon_label_bokeh.change.emit() """) grid_data_bokeh.selected.js_on_change('indices', grid_data_js) # ------------------------------ # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # ============================== # plot colorbar colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig.toolbar_location=None colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\ color='palette_r',source=colorbar_data_one_slice_bokeh) colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[]) colorbar_fig.xgrid.grid_line_color = None colorbar_fig.ygrid.grid_line_color = None colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig.title.text_font_size = xlabel_fontsize colorbar_fig.title.align = 'center' colorbar_fig.title.text_font_style = 'normal' # ============================== profile_xrange = Range1d(start=style_parameter['profile_plot_xmin'], end=style_parameter['profile_plot_xmax']) profile_yrange = Range1d(start=style_parameter['profile_plot_ymax'], end=style_parameter['profile_plot_ymin']) profile_fig = Figure(plot_width=style_parameter['profile_plot_width'], plot_height=style_parameter['profile_plot_height'],\ x_range=profile_xrange, y_range=profile_yrange, tools=style_parameter['profile_tools'],\ title=style_parameter['profile_title']) profile_fig.line('vs','depth',source=selected_profile_data_bokeh, line_width=2, line_color='black') # ------------------------------ # add lat, lon profile_fig.rect([style_parameter['profile_label_box_x']], [style_parameter['profile_label_box_y']],\ width=style_parameter['profile_label_box_width'], height=style_parameter['profile_label_box_height'],\ width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black',\ level='underlay') profile_fig.text('x','y','lat_label', source=selected_profile_lat_label_bokeh) profile_fig.text('x','y','lon_label', source=selected_profile_lon_label_bokeh) # ------------------------------ # change style profile_fig.xaxis.axis_label = style_parameter['profile_xlabel'] profile_fig.xaxis.axis_label_text_font_style = 'normal' profile_fig.xaxis.axis_label_text_font_size = xlabel_fontsize profile_fig.xaxis.major_label_text_font_size = xlabel_fontsize profile_fig.yaxis.axis_label = style_parameter['profile_ylabel'] profile_fig.yaxis.axis_label_text_font_style = 'normal' profile_fig.yaxis.axis_label_text_font_size = xlabel_fontsize profile_fig.yaxis.major_label_text_font_size = xlabel_fontsize profile_fig.xgrid.grid_line_dash = [4, 2] profile_fig.ygrid.grid_line_dash = [4, 2] profile_fig.title.text_font_size = style_parameter['title_font_size'] profile_fig.title.align = 'center' profile_fig.title.text_font_style = 'normal' profile_fig.toolbar_location = 'above' profile_fig.toolbar_sticky = False profile_fig.toolbar.logo = None # ============================== profile_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ grid_data_bokeh=grid_data_bokeh, \ profile_data_all_bokeh=profile_data_all_bokeh, \ selected_profile_data_bokeh=selected_profile_data_bokeh,\ selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\ selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \ all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \ all_profile_lon_label_bokeh=all_profile_lon_label_bokeh), code=""" var p_index = Math.round(cb_obj.value) var grid_data = grid_data_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][p_index]] selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][p_index]] selected_dot_on_map_bokeh.data['index'] = [p_index] selected_dot_on_map_bokeh.change.emit() var profile_data_all = profile_data_all_bokeh.data selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][p_index] selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][p_index] selected_profile_data_bokeh.change.emit() var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list'] var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list'] selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[p_index]] selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[p_index]] selected_profile_lat_label_bokeh.change.emit() selected_profile_lon_label_bokeh.change.emit() """) profile_slider = Slider(start=0, end=nprofile-1, value=style_parameter['profile_default_index'], \ step=1, title=style_parameter['profile_slider_title'], \ width=style_parameter['profile_plot_width'], height=50,\ callback=profile_slider_callback) profile_slider_callback.args['profile_index'] = profile_slider # ============================== simple_text_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \ code=""" var index = selected_dot_on_map_bokeh.data['index'] var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index] var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index] var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index] var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index] var csvContent = "data:text;charset=utf-8," var i = 0 var temp = csvContent temp += "# Layer Top (km) Vs(km/s) Vp(km/s) Rho(g/cm^3) \\n" while(button_data_vp[i]) { temp+=button_data_top[i].toPrecision(6) + " " + button_data_vs[i].toPrecision(4) + " " + \ button_data_vp[i].toPrecision(4) + " " + button_data_rho[i].toPrecision(4) + "\\n" i = i + 1 } var encodedUri = encodeURI(temp) link = document.createElement('a'); link.setAttribute('href', encodedUri); link.setAttribute('download', 'vel_model.txt'); link.click(); """) simple_text_button = Button(label=style_parameter['simple_text_button_label'], button_type='default', width=style_parameter['button_width'],\ callback=simple_text_button_callback) # ------------------------------ model96_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \ code=""" var index = selected_dot_on_map_bokeh.data['index'] var lat = selected_dot_on_map_bokeh.data['lat'] var lon = selected_dot_on_map_bokeh.data['lon'] var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index] var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index] var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index] var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index] var csvContent = "data:text;charset=utf-8," var i = 0 var temp = csvContent temp += "MODEL." + index + " \\n" temp += "ShearVelocityModel Lat: "+ lat +" Lon: " + lon + "\\n" temp += "ISOTROPIC \\n" temp += "KGS \\n" temp += "SPHERICAL EARTH \\n" temp += "1-D \\n" temp += "CONSTANT VELOCITY \\n" temp += "LINE08 \\n" temp += "LINE09 \\n" temp += "LINE10 \\n" temp += "LINE11 \\n" temp += " H(KM) VP(KM/S) VS(KM/S) RHO(GM/CC) QP QS ETAP ETAS FREFP FREFS \\n" while(button_data_vp[i+1]) { var thickness = button_data_top[i+1] - button_data_top[i] temp+=" " +thickness.toPrecision(6) + " " + button_data_vp[i].toPrecision(4) + " " + button_data_vs[i].toPrecision(4) \ + " " + button_data_rho[i].toPrecision(4) + " 0.00 0.00 0.00 0.00 1.00 1.00" + "\\n" i = i + 1 } var encodedUri = encodeURI(temp) link = document.createElement('a'); link.setAttribute('href', encodedUri); link.setAttribute('download', 'vel_model96.txt'); link.click(); """) model96_button = Button(label=style_parameter['model96_button_label'], button_type='default', width=style_parameter['button_width'],\ callback=model96_button_callback) # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text=style_parameter['annotating_html02'],\ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== output_file(filename,title=style_parameter['html_title'], mode=style_parameter['library_source']) left_column = Column(depth_slider, map_view, colorbar_fig, annotating_fig01, width=style_parameter['left_column_width']) button_pannel = Row(simple_text_button, model96_button) right_column = Column(profile_slider, profile_fig, button_pannel, annotating_fig02, width=style_parameter['right_column_width']) layout = Row(left_column, right_column) save(layout)
ys=[[y0, y0, Y[i+1], Y[i]] for i in range(len(Y[:-1])) ], color=data.colors[:-1] )) patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color") plot.add_glyph(patches_source, patches) line_source = ColumnDataSource(dict(x=data.dist, y=data.alt)) line = Line(x='x', y='y', line_color="black", line_width=1) plot.add_glyph(line_source, line) return plot data = prep_data(obiszow_mtb_xcm) trail = trail_map(data) altitude = altitude_profile(data) layout = Column(children=[altitude, trail]) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "trail.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Trail map and altitude profile")) print("Wrote %s" % filename) view(filename)
def Zancada(DatosBokeh, EjeX, MetricasAuxiliares): """ GRAFICO DISCRETO | LONGITUD DE ZANCADA """ # Creacion del diccionario de metricas auxiliares DiccionarioVariables = ParametrosVariables(DatosBokeh) # Generacion del codigo JavaScript que habilita la visualizacion de metricas auxiliares CodigoJS = GeneracionCodigoJS(MetricasAuxiliares) # Asignacion de tamaño del punto en graficas discretas SizeCircle = FunctionSizeCircle(DatosBokeh) # Creacion de un grafica PLT = figure(width=1000, height=400, x_range=(DatosBokeh.data[EjeX].min(), DatosBokeh.data[EjeX].max()), y_range=(LimiteEjeY(DatosBokeh, 'LONGITUD ZANCADA', 'Inferior'), LimiteEjeY(DatosBokeh, 'LONGITUD ZANCADA', 'Superior')), tools='', toolbar_location=None) # Inclusion de datos PLT.circle(EjeX, 'LongitudZancada[m]', source=DatosBokeh, size=SizeCircle, line_color=transform( 'LongitudZancada[m]', LinearColorMapper(palette=PaletaColoresLinea, low=0.8, high=2)), color=transform( 'LongitudZancada[m]', LinearColorMapper(palette=PaletaColores, low=0.8, high=2)), fill_alpha=1) PLT_Linea = PLT.line(EjeX, 'LongitudZancada[m]', source=DatosBokeh, color='white', line_width=0, line_alpha=0) PLT.add_tools( HoverTool(tooltips=[('', '@{LongitudZancada[m]}{0,0.00} m')], renderers=[PLT_Linea], mode='vline')) # Inclusion de lineas auxiliares ListadoMetricasAuxiliares = {} for Metrica in MetricasAuxiliares: if DiccionarioVariables[Metrica]['Tipo'] == 'circle': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.circle( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], size=SizeCircle, line_color=DiccionarioVariables[Metrica]['Color'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) elif DiccionarioVariables[Metrica]['Tipo'] == 'step': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.step( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) else: ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.line( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) # Atributos PLT.title.text = 'LONGITUD DE ZANCADA' PLT.sizing_mode = 'fixed' PLT.yaxis.axis_label = 'Longitud de zancada [m]' PLT.yaxis.formatter = NumeralTickFormatter(format='0.0') PLT.grid.visible = False PLT.yaxis.minor_tick_line_color = None # Asignacion de opciones de visualizacion del eje X if EjeX == 'Distancia[m]': PLT.xaxis.axis_label = 'Distancia' PLT.xaxis.formatter = NumeralTickFormatter(format='0') if DatosBokeh.data['Distancia[m]'].max() >= 4000: PLT.xaxis.ticker = SingleIntervalTicker(interval=1000) PLT.xaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['Distancia[m]'], 1000, 1000, 0, 0) elif EjeX == 'TiempoActividad': PLT.xaxis.axis_label = 'Tiempo actividad' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() elif EjeX == 'TiempoTotal': PLT.xaxis.axis_label = 'Tiempo total' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() #Botones Botones = CheckboxGroup(labels=MetricasAuxiliares, active=[], width=100, height=380) ListadoMetricasAuxiliares['checkbox'] = Botones CodigoJSFrecuenciaCardiaca = CustomJS(code=CodigoJS, args=ListadoMetricasAuxiliares) Botones.js_on_click(CodigoJSFrecuenciaCardiaca) #Layout GridBotones = layout( [Spacer(width=100, height=25), Column(Botones, width=100, height=375)], sizing_mode='fixed', width=100, height=400) GridGrafica = gridplot([PLT, GridBotones], ncols=2, sizing_mode='stretch_width', toolbar_location=None, plot_width=1100, plot_height=400) return GridGrafica
checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: active=' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.js_on_click(CustomJS(code="console.log('radio_group: active=' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: active=' + this.active, this.toString())")) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: active=' + this.active, this.toString())")) widget_box = Column(children=[ button, button_disabled, toggle_inactive, toggle_active, dropdown, dropdown_disabled, dropdown_split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, ]) doc = Document() doc.add_root(widget_box) if __name__ == "__main__": doc.validate() filename = "buttons.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Button widgets")) print("Wrote %s" % filename) view(filename)
bar_chart_source = ColumnDataSource(data=bar_chart_data) bar_chart = create_bar_chart(bar_chart_data, bar_chart_source) stacked_chart_positive_data = wrangle_pos_data_for_stacked_chart(user_inputs) stacked_chart_negative_data = wrangle_neg_data_for_stacked_chart(user_inputs) stacked_chart_positive_source = ColumnDataSource( data=stacked_chart_positive_data) stacked_chart_negative_source = ColumnDataSource( data=stacked_chart_negative_data) stacked_chart = create_stacked_chart( stacked_chart_positive_data, stacked_chart_negative_data, stacked_chart_positive_source, stacked_chart_negative_source, ) inputs = Column(change_air_travel_slider, ) # layout of charts bar_chart.margin = (0, 0, 15, 0) stacked_chart.margin = (0, 0, 15, 0) charts = column( bar_chart, stacked_chart, sizing_mode="stretch_width", margin=(0, 15, 0, 15), ) # doc.theme = Theme(filename="main/static/main/ghg_bokeh_theme.yaml") curdoc().add_root(layout([[inputs, charts]], css_classes=["center"]))
def compute(t): value = np.sin(xx / 50 + t / 10) * np.cos(yy / 50 + t / 10) * 50 + 50 return dict(x=xx, y=yy, z=value, color=value) source = ColumnDataSource(data=compute(0)) content_filename = join(dirname(__file__), "description.html") description = Div(text=open(content_filename).read(), render_as_text=False, width=600) surface = Surface3d(x="x", y="y", z="z", color="color", data_source=source) curdoc().add_root(Column(description, surface)) @count() def update(t): source.data = compute(t) curdoc().add_periodic_callback(update, 100) curdoc().title = "Surface3dYo" session = push_session(curdoc(), url="http://127.0.0.1:5006/extension_loader") session.show() # open the document in a browser session.loop_until_closed() # run forever
source.data = { value: [cb_obj.value] } """) exposure_controls.append(sn_slider) noise_slider = Slider(title="Noise to Add In", value=500, start=0.0, end=1000.0, step=50.0, callback_policy='mouseup') noise_slider.callback = CustomJS(args=dict(source=fake_callback_source3), code=""" source.data = { value: [cb_obj.value] } """) #exposure_controls.append(noise_slider) sp.set_plot_options( plot.state ) # plot.state has bokeh type Figure, so can be manipulated in the usual way astro_tab = Panel(child=Column(children=astro_controls), title='Stars') exposure_tab = Panel(child=Column(children=exposure_controls), title='Exposure') info_tab = Panel(child=Div(text=h.help(), width=300), title='Info') visual_tab = Panel(child=Column(children=[widget]), title='Visuals') controls = Tabs(tabs=[astro_tab, exposure_tab, visual_tab, info_tab], width=400) layout = layout([[controls, plot.state]], sizing_mode='fixed') curdoc().add_root(layout)
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 = [], [] offset = 0 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: # 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: # 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: title = subplot.subplots['main']._format_title( self.keys[-1], dimensions=False) if not title: title = ' '.join(self.paths[r, c]) tab_titles[r, c] = title else: plots[r + offset] += [empty_plot(0, 0)] # Replace None types with empty plots # to avoid bokeh bug plots = layout_padding(plots, self.renderer) # Wrap in appropriate layout model kwargs = dict(sizing_mode=self.sizing_mode) 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) else: plots = filter_toolboxes(plots) plots, width = pad_plots(plots) layout_plot = gridplot(children=plots, width=width, toolbar_location=self.toolbar, merge_tools=self.merge_tools, **kwargs) title = self._get_title(self.keys[-1]) if title: self.handles['title'] = title layout_plot = Column(title, layout_plot, **kwargs) self.handles['plot'] = layout_plot self.handles['plots'] = plots self._update_callbacks(layout_plot) if self.shared_datasource: self.sync_sources() self.drawn = True return self.handles['plot']
if not warning_devices: alarm.visible = False alarm_list.visible = False t += 1 layout = layout([[fig_tanque3, fig_tanque4], [fig_tanque1, fig_tanque2], [fig_vol1, fig_vol2]]) panel1 = Panel(child=row( Column( label1, row(Column(dataRecordingButton, dataRecordingLabel), Column(extensionsDropdown)), refEst1, refEst2, row(Column(valvula1Label, Kp1, Ki1, Kd1, Kw1), Column(valvula2Label, Kp2, Ki2, Kd2, Kw2)), row(alarm, alarm_list)), layout), title='Modo Automático') panel2 = Panel(child=row( Column( label2, row(Column(dataRecordingButton, dataRecordingLabel), Column(extensionsDropdown)), row(Column(valvula1Label, voltageV1, razonFlujoV1), Column(valvula2Label, voltageV2, razonFlujoV2)), row(alarm, alarm_list)), layout), title='Modo Manual') # Tabs
widgets = Column(children=[ Row(children=[ Column(children=[ click_button, disabled_button, toggle, dropdown, dropdown_split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, Row(children=[ checkbox_button_group_vertical, radio_button_group_vertical ]), ]), Column(children=[ text_input, autocomplete_input, text_area, select, multi_select, multi_choice, slider, range_slider, date_slider, date_range_slider, spinner, color_picker, date_picker, Row(children=[switch_0, switch_1]), paragraph, div, pre_text, ]), tabs, ]), table, ])
div.background = `rgb(${r}, ${g}, ${b})` """) red.js_on_change('value', cb) green.js_on_change('value', cb) blue.js_on_change('value', cb) return Row(children=[red, green, blue, div]) sliders = Row(children=[ Column(children=[ slider, disabled_slider, range_slider, date_slider, date_range_slider, only_value_slider, no_title_slider, ]), color_picker(), ]) doc = Document() doc.add_root(sliders) if __name__ == "__main__": doc.validate() filename = "sliders.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "sliders"))
def initialize_plot(self, plots=None, ranges=None): ranges = self.compute_ranges(self.layout, self.keys[-1], None) plot_grid = self._compute_grid() passed_plots = [] if plots is None else plots r_offset = 0 col_offsets = defaultdict(int) tab_plots = [] for r in range(self.rows): # Compute row offset row = [(k, sp) for k, sp in self.subplots.items() if k[0] == r] row_padded = any(len(sp.layout) > 2 for k, sp in row) if row_padded: r_offset += 1 for c in range(self.cols): subplot = self.subplots.get((r, c), None) # Compute column offset col = [(k, sp) for k, sp in self.subplots.items() if k[1] == c] col_padded = any(len(sp.layout) > 1 for k, sp in col) if col_padded: col_offsets[r] += 1 c_offset = col_offsets.get(r, 0) if subplot is None: continue shared_plots = list(passed_plots) if self.shared_axes else None subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots) nsubplots = len(subplots) # If tabs enabled lay out AdjointLayout on grid if self.tabs: title = subplot.subplots['main']._format_title(self.keys[-1], dimensions=False) if not title: title = ' '.join(self.paths[r,c]) if nsubplots == 1: grid = subplots[0] elif nsubplots == 2: grid = gridplot([subplots], merge_tools=self.merge_tools, toolbar_location=self.toolbar) else: grid = [[subplots[2], None], subplots[:2]] grid = gridplot(children=grid, merge_tools=self.merge_tools, toolbar_location=self.toolbar) tab_plots.append((title, grid)) continue # Situate plot in overall grid if nsubplots > 2: plot_grid[r+r_offset-1][c+c_offset-1] = subplots[2] plot_column = plot_grid[r+r_offset] if nsubplots > 1: plot_column[c+c_offset-1] = subplots[0] plot_column[c+c_offset] = subplots[1] else: plot_column[c+c_offset-int(col_padded)] = subplots[0] passed_plots.append(subplots[0]) # Wrap in appropriate layout model kwargs = dict(sizing_mode=self.sizing_mode) if self.tabs: plots = filter_toolboxes([p for t, p in tab_plots]) panels = [Panel(child=child, title=t) for t, child in tab_plots] layout_plot = Tabs(tabs=panels) else: plot_grid = layout_padding(plot_grid, self.renderer) plot_grid = filter_toolboxes(plot_grid) plot_grid, width = pad_plots(plot_grid) layout_plot = gridplot(children=plot_grid, width=width, toolbar_location=self.toolbar, merge_tools=self.merge_tools, **kwargs) title = self._get_title(self.keys[-1]) if title: self.handles['title'] = title layout_plot = Column(title, layout_plot, **kwargs) self.handles['plot'] = layout_plot self.handles['plots'] = plots self._update_callbacks(layout_plot) if self.shared_datasource: self.sync_sources() if self.top_level: self.init_links() self.drawn = True return self.handles['plot']
def Mapa(dfBokeh, DatosBokeh): """ PREPARACION DE DATOS """ # Calculo de los valores agregados AVG_Altitud, MAX_Altitud, MIN_Altitud, \ AVG_Velocidad, MAX_Velocidad, MIN_Velocidad, \ AVG_Ritmo, MAX_Ritmo, MIN_Ritmo, \ AVG_FrecuenciaCardiaca, MAX_FrecuenciaCardiaca, MIN_FrecuenciaCardiaca, \ AVG_Cadencia, MAX_Cadencia, MIN_Cadencia, \ AVG_Temperatura, MAX_Temperatura, MIN_Temperatura, \ AVG_LongitudZancada, MAX_LongitudZancada, MIN_LongitudZancada, \ AVG_Pendiente, MAX_Pendiente , MIN_Pendiente = CalculosVectoresAgregados(dfBokeh) AltitudInicio, AltitudFin = dfBokeh.loc[dfBokeh.index.min() == dfBokeh.index, ['Altitud']].min()[0], dfBokeh.loc[dfBokeh.index.max() == dfBokeh.index, ['Altitud']].min()[0] # Calculo de desniveles finales DesnivelPositivo = dfBokeh['DesnivelPositivoAcumulado'].max() DesnivelNegativo = dfBokeh['DesnivelNegativoAcumulado'].max() DesnivelAcumulado = DesnivelPositivo + DesnivelNegativo DesnivelPorKilometro = (DesnivelAcumulado/dfBokeh['Distancia'].max())*1000 """ MAPA CARTODBPOSITRON CARTODBPOSITRON_RETINA STAMEN_TERRAIN STAMEN_TERRAIN_RETINA STAMEN_TONER STAMEN_TONER_BACKGROUND STAMEN_TONER_LABELS """ # Creacion de un grafica PLT_Mapa = figure(width=900, height=430, x_range=(DatosBokeh.data['LongitudMercator'].min()-100, DatosBokeh.data['LongitudMercator'].max()+100), y_range=(DatosBokeh.data['LatitudMercator'].min()-100, DatosBokeh.data['LatitudMercator'].max()+100), x_axis_type= 'mercator', y_axis_type= 'mercator', tools= 'wheel_zoom, reset, hover') PLT_Mapa.add_tile(get_provider('STAMEN_TERRAIN')) # Inclusion de datos PLT_MP_Linea = PLT_Mapa.line(x= 'LongitudMercator', y= 'LatitudMercator', source= DatosBokeh, line_color= Grapefruit[2], line_width= 3, line_cap= 'round') """ #PLT_Mapa.circle(x= 'LongitudMercator', y= 'LatitudMercator', source= DatosBokeh, size= 5, line_color= None, fill_color= None, fill_alpha= 0, hover_fill_color= 'yellow', hover_line_color = 'black', hover_alpha= 1) #PLT_Mapa.add_tools(HoverTool(tooltips=None, mode='mouse')) """ CoordenadasHitosKm, TiempoTotalKm, TiempoActividadKm, MinDistanciaKm = HitosKilometricos(dfBokeh) CoordenadasPausas, TiempoTotalPausas, TiempoActividadPausas, DistanciasPausas = HitosPausas(dfBokeh) # Ubicacion de puntos de inicio, fin y kilometros LongitudKm =[] LatitudKm =[] PuntoKilometrico = [] for i, Km in enumerate(CoordenadasHitosKm): if i == 0: PLT_Mapa_Inicio = PLT_Mapa.circle(ConversorCoordenadasMercator(Km[1], Km[0])[0], ConversorCoordenadasMercator(Km[1], Km[0])[1], size= 8, line_color= 'black', fill_color= Spectral[2], visible= True) elif i == len(CoordenadasHitosKm)-1: PLT_Mapa_Fin = PLT_Mapa.circle(ConversorCoordenadasMercator(Km[1], Km[0])[0], ConversorCoordenadasMercator(Km[1], Km[0])[1], size= 8, line_color= 'black', fill_color= Spectral[7], visible= True) else: LongitudKm.append(ConversorCoordenadasMercator(Km[1], Km[0])[0]) LatitudKm.append(ConversorCoordenadasMercator(Km[1], Km[0])[1]) PuntoKilometrico.append(str(i)) CDS_PuntosKm = ColumnDataSource(data= dict(Longitud= LongitudKm, Latitud= LatitudKm, PuntoKilometrico= PuntoKilometrico)) PLT_Mapa_PuntoKm = PLT_Mapa.circle(x= 'Longitud', y= 'Latitud', source= CDS_PuntosKm, color= 'white', size= 8, line_color= 'black', fill_color= 'white', visible= True) PLT_Mapa_PuntoKm_TXT = LabelSet(x= 'Longitud', y= 'Latitud', text='PuntoKilometrico', level='glyph', x_offset= 5, y_offset= 0, source= CDS_PuntosKm, render_mode='canvas', text_font_size= '10pt', text_color= 'black', text_align= 'left', text_baseline= 'middle', text_font_style= 'bold', visible= True) PLT_Mapa.add_layout(PLT_Mapa_PuntoKm_TXT) # Ubicacion de pausas LongitudPausa =[] LatitudPausa =[] for i, Km in enumerate(CoordenadasPausas): LongitudPausa.append(ConversorCoordenadasMercator(Km[1], Km[0])[0]) LatitudPausa.append(ConversorCoordenadasMercator(Km[1], Km[0])[1]) PLT_Mapa_Pausas = PLT_Mapa.x(LongitudPausa, LatitudPausa, line_color= 'black', line_width= 2, fill_color= None, visible= False) # Identificacion de pico y valle en trails for index, row in dfBokeh.iterrows(): LongitudMercator, LatitudMercator = ConversorCoordenadasMercator(row.Longitud, row.Latitud) dfBokeh.at[index,'LongitudMercator'] = LongitudMercator dfBokeh.at[index,'LatitudMercator'] = LatitudMercator if (DesnivelPorKilometro > 40) and (MAX_Altitud[0] >= (AltitudInicio + 50) and MAX_Altitud[0] >= (AltitudFin + 50)): PLT_Mapa_Cima = PLT_Mapa.triangle(dfBokeh[dfBokeh['Altitud']==MAX_Altitud[0]]['LongitudMercator'].min(), dfBokeh[dfBokeh['Altitud']==MAX_Altitud[0]]['LatitudMercator'].min(), size= 10, line_color= 'black', line_width= 2, fill_color= Spectral[4], visible= False) PLT_Mapa_Cima_TXT = Label(x= dfBokeh[dfBokeh['Altitud']==MAX_Altitud[0]]['LongitudMercator'].min(), y= dfBokeh[dfBokeh['Altitud']==MAX_Altitud[0]]['LatitudMercator'].min(), text= str(round(MAX_Altitud[0])), x_offset= 5, y_offset= 0, text_font_size= '10pt', text_color= 'black', text_align= 'left', text_baseline= 'middle', text_font_style= 'bold', visible= False) PLT_Mapa.add_layout(PLT_Mapa_Cima_TXT) else: PLT_Mapa_Cima = PLT_Mapa.triangle(0, 0, size= 0, line_alpha= 0, visible= False) PLT_Mapa_Cima_TXT = Label(x= 0, y= 0, text= '', text_font_size= '0pt', text_alpha= 0, visible= False) if (DesnivelPorKilometro > 40) and (MIN_Altitud[0] <= (AltitudInicio - 50) and MIN_Altitud[0] <= (AltitudFin - 50)): PLT_Mapa_Valle = PLT_Mapa.inverted_triangle(dfBokeh[dfBokeh['Altitud']==MIN_Altitud[0]]['LongitudMercator'].min(), dfBokeh[dfBokeh['Altitud']==MIN_Altitud[0]]['LatitudMercator'].min(), size= 10, line_color= 'black', line_width= 2, fill_color= Spectral[0], visible= False) PLT_Mapa_Valle_TXT = Label(x= dfBokeh[dfBokeh['Altitud']==MIN_Altitud[0]]['LongitudMercator'].min(), y= dfBokeh[dfBokeh['Altitud']==MIN_Altitud[0]]['LatitudMercator'].min(), text= str(round(MIN_Altitud[0])), x_offset= 5, y_offset= 0, text_font_size= '10pt', text_color= 'black', text_align= 'left', text_baseline= 'middle', text_font_style= 'bold', visible= False) PLT_Mapa.add_layout(PLT_Mapa_Valle_TXT) else: PLT_Mapa_Valle = PLT_Mapa.inverted_triangle(0, 0, size= 0, line_alpha= 0, visible= False) PLT_Mapa_Valle_TXT = Label(x= 0, y= 0, text= '', text_font_size= '0pt', text_alpha= 0, visible= False) # Atributos PLT_Mapa.sizing_mode = 'fixed' PLT_Mapa.xaxis.major_tick_line_color = None PLT_Mapa.xaxis.minor_tick_line_color = None PLT_Mapa.yaxis.major_tick_line_color = None PLT_Mapa.yaxis.minor_tick_line_color = None PLT_Mapa.xaxis.major_label_text_font_size = '0pt' PLT_Mapa.yaxis.major_label_text_font_size = '0pt' PLT_Mapa.grid.visible = False PLT_Mapa.toolbar.autohide = True # Sin bordes PLT_Mapa.min_border_left = 0 PLT_Mapa.min_border_right = 0 PLT_Mapa.min_border_top = 0 PLT_Mapa.min_border_bottom = 0 # Linea exterior PLT_Mapa.outline_line_width = 3 PLT_Mapa.outline_line_alpha = 0.3 PLT_Mapa.outline_line_color = 'black' """ BOTONES """ CodigoJS = """ var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; l0.visible = indexOf.call(checkbox.active,0)>=0; l1.visible = indexOf.call(checkbox.active,0)>=0; l2.visible = indexOf.call(checkbox.active,1)>=0; l3.visible = indexOf.call(checkbox.active,1)>=0; l4.visible = indexOf.call(checkbox.active,2)>=0; l5.visible = indexOf.call(checkbox.active,2)>=0; l6.visible = indexOf.call(checkbox.active,2)>=0; l7.visible = indexOf.call(checkbox.active,2)>=0; l8.visible = indexOf.call(checkbox.active,3)>=0; """ BotonesMapa = CheckboxButtonGroup(labels=["INICIO/FIN", "PUNTOS KILOMETRICOS", "CIMA/VALLE", 'PAUSAS'], active=[0, 1], width=300, height=30) CodigoJSMapa = CustomJS(code=CodigoJS, args=dict(l0=PLT_Mapa_Inicio, l1=PLT_Mapa_Fin, l2=PLT_Mapa_PuntoKm, l3= PLT_Mapa_PuntoKm_TXT, l4=PLT_Mapa_Cima, l5=PLT_Mapa_Cima_TXT, l6=PLT_Mapa_Valle, l7=PLT_Mapa_Valle_TXT, l8=PLT_Mapa_Pausas, checkbox= BotonesMapa)) BotonesMapa.js_on_click(CodigoJSMapa) GridMapa = layout([PLT_Mapa, Column(BotonesMapa, width=300, height=35)], sizing_mode='stretch_width', width=900, height=470) return GridMapa
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.add_tools(HoverTool()) tab = Panel(child=plot, title=title, closable=True) return tab def make_tabs(objs): return Tabs(tabs=[make_tab(title, obj) for title, obj in objs], width=600) layout = Column(children=[ Paragraph(text="Only Image and ImageRGBA glyphs are not demonstrated."), make_tabs(glyphs), make_tabs(markers) ]) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "glyphs.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Glyphs")) print("Wrote %s" % filename) view(filename)
plot_1.title.text = "Circular Layout (NodesAndLinkedEdges inspection policy)" plot_1.add_tools(HoverTool(tooltips=None)) plot_2 = create_graph(nx.spring_layout, selection_policy=NodesAndLinkedEdges(), scale=2, center=(0, 0)) plot_2.title.text = "Spring Layout (NodesAndLinkedEdges selection policy)" plot_2.add_tools(TapTool(), BoxSelectTool()) plot_3 = create_graph(nx.random_layout, inspection_policy=EdgesAndLinkedNodes(), center=(0, 0)) plot_3.title.text = "Random Layout (EdgesAndLinkedNodes inspection policy)" plot_3.add_tools(HoverTool(tooltips=None)) plot_4 = create_graph(nx.fruchterman_reingold_layout, selection_policy=EdgesAndLinkedNodes(), scale=2, center=(0, 0), dim=2) plot_4.title.text = "FR Layout (EdgesAndLinkedNodes selection policy)" plot_4.add_tools(TapTool()) layout = Column(Row(plot_1, plot_2), Row(plot_3, plot_4)) doc = curdoc() doc.add_root(layout) show(layout)
def plot_dispersion_bokeh(filename, period_array, curve_data_array, boundary_data, style_parameter): ''' Plot dispersion maps and curves using bokeh Input: filename is the filename of the resulting html file period_array is a list of period curve_data_array is a list of dispersion curves boundary_data is a list of boundaries style_parameter contains plotting parameters Output: None ''' xlabel_fontsize = style_parameter['xlabel_fontsize'] # ============================== # prepare data map_data_all_slices_velocity = [] map_data_all_slices_period = [] map_data_all_slices_color = [] colorbar_data_all_left = [] colorbar_data_all_right = [] nperiod = len(period_array) ncurve = len(curve_data_array) ncolor = len(palette) palette_r = palette[::-1] colorbar_top = [0.1 for i in range(ncolor)] colorbar_bottom = [0 for i in range(ncolor)] for iperiod in range(nperiod): one_slice_lat_list = [] one_slice_lon_list = [] one_slice_vel_list = [] map_period = period_array[iperiod] for icurve in range(ncurve): acurve = curve_data_array[icurve] curve_lat = acurve['latitude'] curve_lon = acurve['longitude'] curve_vel = acurve['velocity'] curve_period = acurve['period'] one_slice_lat_list.append(curve_lat) one_slice_lon_list.append(curve_lon) if map_period in curve_period: curve_period_index = curve_period.index(map_period) one_slice_vel_list.append(curve_vel[curve_period_index]) else: one_slice_vel_list.append(style_parameter['nan_value']) # get color for dispersion values one_slice_vel_mean = np.nanmean(one_slice_vel_list) one_slice_vel_std = np.nanstd(one_slice_vel_list) color_min = one_slice_vel_mean - one_slice_vel_std * style_parameter[ 'spread_factor'] color_max = one_slice_vel_mean + one_slice_vel_std * style_parameter[ 'spread_factor'] color_step = (color_max - color_min) * 1. / ncolor one_slice_color_list = get_color_list(one_slice_vel_list,color_min,color_max,palette_r,\ style_parameter['nan_value'],style_parameter['nan_color']) colorbar_left = np.linspace(color_min, color_max - color_step, ncolor) colorbar_right = np.linspace(color_min + color_step, color_max, ncolor) if one_slice_lat_list: map_data_all_slices_velocity.append(one_slice_vel_list) map_data_all_slices_period.append( 'Period: {0:6.1f} s'.format(map_period)) map_data_all_slices_color.append(one_slice_color_list) colorbar_data_all_left.append(colorbar_left) colorbar_data_all_right.append(colorbar_right) # get location for all points map_lat_list, map_lon_list = [], [] map_lat_label_list, map_lon_label_list = [], [] for i in range(ncurve): acurve = curve_data_array[i] map_lat_list.append(acurve['latitude']) map_lon_list.append(acurve['longitude']) map_lat_label_list.append('Lat: {0:12.3f}'.format(acurve['latitude'])) map_lon_label_list.append('Lon: {0:12.3f}'.format(acurve['longitude'])) # data for the map view plot map_view_label_lon = style_parameter['map_view_period_label_lon'] map_view_label_lat = style_parameter['map_view_period_label_lat'] map_data_one_slice = map_data_all_slices_color[ style_parameter['map_view_default_index']] map_data_one_slice_period = map_data_all_slices_period[ style_parameter['map_view_default_index']] map_data_one_slice_bokeh = ColumnDataSource(data=dict(map_lat_list=map_lat_list,\ map_lon_list=map_lon_list,\ map_data_one_slice=map_data_one_slice)) map_data_one_slice_period_bokeh = ColumnDataSource( data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon], map_period=[map_data_one_slice_period])) map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices_color=map_data_all_slices_color,\ map_data_all_slices_period=map_data_all_slices_period)) # data for the colorbar colorbar_data_one_slice = {} colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[ style_parameter['map_view_default_index']] colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[ style_parameter['map_view_default_index']] colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom, colorbar_left=colorbar_data_one_slice['colorbar_left'],\ colorbar_right=colorbar_data_one_slice['colorbar_right'],\ palette_r=palette_r)) colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\ colorbar_data_all_right=colorbar_data_all_right)) # data for dispersion curves curve_default_index = style_parameter['curve_default_index'] selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[map_lat_list[curve_default_index]],\ lon=[map_lon_list[curve_default_index]],\ color=[map_data_one_slice[curve_default_index]],\ index=[curve_default_index])) selected_curve_data = curve_data_array[curve_default_index] selected_curve_data_bokeh = ColumnDataSource(data=dict(curve_period=selected_curve_data['period'],\ curve_velocity=selected_curve_data['velocity'])) period_all = [] velocity_all = [] for acurve in curve_data_array: period_all.append(acurve['period']) velocity_all.append(acurve['velocity']) curve_data_all_bokeh = ColumnDataSource( data=dict(period_all=period_all, velocity_all=velocity_all)) selected_curve_lat_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lat_label_x']], \ y=[style_parameter['curve_lat_label_y']],\ lat_label=[map_lat_label_list[curve_default_index]])) selected_curve_lon_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lon_label_x']], \ y=[style_parameter['curve_lon_label_y']],\ lon_label=[map_lon_label_list[curve_default_index]])) all_curve_lat_label_bokeh = ColumnDataSource(data=dict( map_lat_label_list=map_lat_label_list)) all_curve_lon_label_bokeh = ColumnDataSource(data=dict( map_lon_label_list=map_lon_label_list)) # ============================== map_view = Figure(plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['map_view_plot_height'], \ y_range=[style_parameter['map_view_lat_min'],\ style_parameter['map_view_lat_max']], x_range=[style_parameter['map_view_lon_min'],\ style_parameter['map_view_lon_max']], tools=style_parameter['map_view_tools'],\ title=style_parameter['map_view_title']) # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # ------------------------------ # add period label map_view.rect(style_parameter['map_view_period_box_lon'], style_parameter['map_view_period_box_lat'], \ width=style_parameter['map_view_period_box_width'], height=style_parameter['map_view_period_box_height'], \ width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') map_view.text('lon', 'lat', 'map_period', source=map_data_one_slice_period_bokeh,\ text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay') # ------------------------------ # plot dots map_view.circle('map_lon_list', 'map_lat_list', color='map_data_one_slice', \ source=map_data_one_slice_bokeh, size=style_parameter['marker_size'],\ line_width=0.2, line_color='black', alpha=1.0,\ selection_color='map_data_one_slice', selection_line_color='black',\ selection_fill_alpha=1.0,\ nonselection_fill_alpha=1.0, nonselection_fill_color='map_data_one_slice',\ nonselection_line_color='black', nonselection_line_alpha=1.0) map_view.circle('lon', 'lat', color='color', source=selected_dot_on_map_bokeh, \ line_color='#00ff00', line_width=4.0, alpha=1.0, \ size=style_parameter['selected_marker_size']) # ------------------------------ # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # ============================== # plot colorbar colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig.toolbar_location = None colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\ fill_color='palette_r',source=colorbar_data_one_slice_bokeh) colorbar_fig.yaxis[0].ticker = FixedTicker(ticks=[]) colorbar_fig.xgrid.grid_line_color = None colorbar_fig.ygrid.grid_line_color = None colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig.title.text_font_size = xlabel_fontsize colorbar_fig.title.align = 'center' colorbar_fig.title.text_font_style = 'normal' # ============================== curve_fig = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \ y_range=(style_parameter['curve_y_min'],style_parameter['curve_y_max']), \ x_range=(style_parameter['curve_x_min'],style_parameter['curve_x_max']),x_axis_type='log',\ tools=['save','box_zoom','wheel_zoom','reset','crosshair','pan'], title=style_parameter['curve_title']) # ------------------------------ curve_fig.rect([style_parameter['curve_label_box_x']], [style_parameter['curve_label_box_y']], \ width=style_parameter['curve_label_box_width'], height=style_parameter['curve_label_box_height'], \ width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') curve_fig.text('x', 'y', \ 'lat_label', source=selected_curve_lat_label_bokeh) curve_fig.text('x', 'y', \ 'lon_label', source=selected_curve_lon_label_bokeh) # ------------------------------ curve_fig.line('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, color='black') curve_fig.circle('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, size=5, color='black') # ------------------------------ curve_fig.title.text_font_size = style_parameter['title_font_size'] curve_fig.title.align = 'center' curve_fig.title.text_font_style = 'normal' curve_fig.xaxis.axis_label = style_parameter['curve_xlabel'] curve_fig.xaxis.axis_label_text_font_style = 'normal' curve_fig.xaxis.axis_label_text_font_size = xlabel_fontsize curve_fig.xaxis.major_label_text_font_size = xlabel_fontsize curve_fig.yaxis.axis_label = style_parameter['curve_ylabel'] curve_fig.yaxis.axis_label_text_font_style = 'normal' curve_fig.yaxis.axis_label_text_font_size = xlabel_fontsize curve_fig.yaxis.major_label_text_font_size = xlabel_fontsize curve_fig.xgrid.grid_line_dash = [4, 2] curve_fig.ygrid.grid_line_dash = [4, 2] curve_fig.xaxis[0].formatter = PrintfTickFormatter(format="%4.0f") curve_fig.toolbar.logo = None curve_fig.toolbar_location = 'above' curve_fig.toolbar_sticky = False # ============================== map_data_one_slice_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ selected_curve_data_bokeh=selected_curve_data_bokeh,\ curve_data_all_bokeh=curve_data_all_bokeh,\ selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\ selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\ all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\ all_curve_lon_label_bokeh=all_curve_lon_label_bokeh), code=""" var inds = cb_obj.indices selected_dot_on_map_bokeh.data['index'] = [inds] var new_slice = map_data_one_slice_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [new_slice['map_lat_list'][inds]] selected_dot_on_map_bokeh.data['lon'] = [new_slice['map_lon_list'][inds]] selected_dot_on_map_bokeh.data['color'] = [new_slice['map_data_one_slice'][inds]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][inds] selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][inds] selected_curve_data_bokeh.change.emit() var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list'] var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list'] selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[inds]] selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[inds]] selected_curve_lat_label_bokeh.change.emit() selected_curve_lon_label_bokeh.change.emit() """) map_data_one_slice_bokeh.selected.js_on_change('indices', map_data_one_slice_js) # ============================== period_slider_callback = CustomJS(args=dict(map_data_all_slices_bokeh=map_data_all_slices_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh, \ colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_period_bokeh=map_data_one_slice_period_bokeh),\ code=""" var p_index = Math.round(cb_obj.value) var map_data_all_slices = map_data_all_slices_bokeh.data var map_data_new_slice = map_data_all_slices['map_data_all_slices_color'][p_index] map_data_one_slice_bokeh.data['map_data_one_slice'] = map_data_new_slice map_data_one_slice_bokeh.change.emit() var color_data_all_slices = colorbar_data_all_slices_bokeh.data colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][p_index] colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][p_index] colorbar_data_one_slice_bokeh.change.emit() var selected_index = selected_dot_on_map_bokeh.data['index'] selected_dot_on_map_bokeh.data['color'] = [map_data_new_slice[selected_index]] selected_dot_on_map_bokeh.change.emit() map_data_one_slice_period_bokeh.data['map_period'] = [map_data_all_slices['map_data_all_slices_period'][p_index]] map_data_one_slice_period_bokeh.change.emit() """) period_slider = Slider(start=0, end=nperiod-1, value=style_parameter['map_view_default_index'], \ step=1, title=style_parameter['period_slider_title'], \ width=style_parameter['period_slider_plot_width'],\ height=50) period_slider.js_on_change('value', period_slider_callback) period_slider_callback.args['period_index'] = period_slider # ============================== curve_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ selected_curve_data_bokeh=selected_curve_data_bokeh,\ curve_data_all_bokeh=curve_data_all_bokeh,\ selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\ selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\ all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\ all_curve_lon_label_bokeh=all_curve_lon_label_bokeh),\ code=""" var c_index = Math.round(cb_obj.value) var one_slice = map_data_one_slice_bokeh.data selected_dot_on_map_bokeh.data['index'] = [c_index] selected_dot_on_map_bokeh.data['lat'] = [one_slice['map_lat_list'][c_index]] selected_dot_on_map_bokeh.data['lon'] = [one_slice['map_lon_list'][c_index]] selected_dot_on_map_bokeh.data['color'] = [one_slice['map_data_one_slice'][c_index]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][c_index] selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][c_index] selected_curve_data_bokeh.change.emit() var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list'] var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list'] selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[c_index]] selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[c_index]] selected_curve_lat_label_bokeh.change.emit() selected_curve_lon_label_bokeh.change.emit() """) curve_slider = Slider(start=0, end=ncurve-1, value=style_parameter['curve_default_index'], \ step=1, title=style_parameter['curve_slider_title'], width=style_parameter['curve_plot_width'],\ height=50) curve_slider.js_on_change('value', curve_slider_callback) curve_slider_callback.args['curve_index'] = curve_slider # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text=style_parameter['annotating_html02'],\ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== output_file(filename, title=style_parameter['html_title'], mode=style_parameter['library_source']) left_fig = Column(period_slider, map_view, colorbar_fig, annotating_fig01,\ width=style_parameter['left_column_width'] ) right_fig = Column(curve_slider, curve_fig, annotating_fig02, \ width=style_parameter['right_column_width'] ) layout = Row(left_fig, right_fig) save(layout)
y_axis=Select(title="Y Axis", options=[ "Tomato Meter", "Number of Review", "Dollars at box office" ], value="Number of Reviews", sizing_mode=sizing_mode)) w1 = make_widgets(sizing_mode) w2 = make_widgets(sizing_mode) check = Icon(icon_name='check') Column(w1['genre'], w1['director'], w1['x_axis'], w1['y_axis'], sizing_mode=sizing_mode) Column(w2['genre'], w2['director'], w2['x_axis'], w2['y_axis'], sizing_mode=sizing_mode) layout = Column(Row(intro, sizing_mode=sizing_mode), Row(WidgetBox(w1['reviews'], w1['genre'], w1['oscars'], w1['director'], w1['x_axis'], w1['y_axis'],
step.mode = 'before'; break; case 'Step (center)': interp = step; step.mode = 'center'; break; case 'Step (after)': interp = step; step.mode = 'after'; break; } for (var i = 0; i < N; i++) { data['x'][i] = i * dx data['y'][i] = interp.compute(data['x'][i]) } } source.change.emit() """) mode = Select( title='Interpolation Mode', value='None', options=['None', 'Linear', 'Step (before)', 'Step (center)', 'Step (after)'], width=300) mode.js_on_change('value', callback) show(Column(mode, p))
# Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = Column(plot, data_table) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "data_tables.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Data Tables")) print("Wrote %s" % filename) view(filename)