def map_intensity_signed(nx, ny, source, z, power=1.0, color='red', color_neg='blue', alpha=0.01, ranges=None): if not present(source, z): return None tools = [PanTool(dimensions='both'), ZoomInTool(dimensions='both'), ZoomOutTool(dimensions='both'), ResetTool(), HoverTool(tooltips=[tooltip(x) for x in (z, DISTANCE_KM, LOCAL_TIME)])] f = figure(plot_width=nx, plot_height=ny, x_axis_type='mercator', y_axis_type='mercator', title=z, tools=tools) tools[-1].renderers = [add_route(f, source)] mn, mx = source[z].min(), source[z].max() scale = max(mx, -mn) if mx > 0: source['size'] = np.sign(source[z]) * sqrt(nx * ny) * (np.abs(source[z]) / scale) ** power / 10 source['size'].clip(lower=0, inplace=True) f.circle(x=SPHERICAL_MERCATOR_X, y=SPHERICAL_MERCATOR_Y, size='size', source=source, color=color, alpha=alpha) if mn < 0: source['size'] = -np.sign(source[z]) * sqrt(nx * ny) * (np.abs(source[z]) / scale) ** power / 10 source['size'].clip(lower=0, inplace=True) f.circle(x=SPHERICAL_MERCATOR_X, y=SPHERICAL_MERCATOR_Y, size='size', source=source, color=color_neg, alpha=alpha) f.axis.visible = False f.toolbar.logo = None if ranges is not None: f.x_range = ranges.x_range f.y_range = ranges.y_range return f
def create_figure(title='Power P'): hover = HoverTool( tooltips=[('Name', '@name'), ("Time", "@time"), ("Date", "@date"), (title, "@data")]) f = figure( plot_width=700, plot_height=500, x_axis_type='datetime', # x_axis_type='auto', tools=[ hover, SaveTool(), ZoomOutTool(), ZoomInTool(), BoxZoomTool(), ResetTool() ], title="Real-Time " + title + " Plot") f.xaxis.axis_label = "Time" f.yaxis.axis_label = title f.xaxis.formatter = DatetimeTickFormatter( seconds="%X", # seconds=["%H:%M:%S"] # seconds="%d %B %Y", # minutes="%d %B %Y", # hours="%d %b %Y", # days="%d %b %Y", # months="%d %b %Y", # years="%d %b %Y" ) return f
def multi_plot(nx, ny, x, ys, source, colors, alphas=None, x_range=None, y_label=None, rescale=False, plotters=None): if not ys or not present(source, x, *ys): return None tools = [PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[tooltip(x) for x in ys + [LOCAL_TIME]], names=['with_hover'])] f = figure(plot_width=nx, plot_height=ny, x_axis_type='datetime' if TIME in x else 'linear', tools=tools) if y_label: f.yaxis.axis_label = y_label elif rescale: f.yaxis.axis_label = ys[0] else: f.yaxis.axis_label = ', '.join(ys) if rescale: f.extra_y_ranges = {} if alphas is None: alphas = [1 for _ in ys] while len(plotters) < len(ys): plotters += plotters for y, color, alpha, plotter in zip(ys, colors, alphas, plotters): y_range = make_range(source, y) if rescale and y != ys[0]: f.extra_y_ranges[y] = y_range f.add_layout(LinearAxis(y_range_name=y, axis_label=y), 'right') plotter(f, x=x, y=y, source=source, color=color, alpha=alpha, y_range_name=y, name='with_hover') else: f.y_range = y_range plotter(f, x=x, y=y, source=source, color=color, alpha=alpha, name='with_hover') f.xaxis.axis_label = x f.toolbar.logo = None if ny < 300: f.toolbar_location = None if x_range: f.x_range = x_range return f
def test_ranges_udpate(self, single_plot_page) -> None: source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(ZoomOutTool()) code = RECORD("event_name", "cb_obj.event_name", final=False) + \ RECORD("x0", "cb_obj.x0", final=False) + \ RECORD("x1", "cb_obj.x1", final=False) + \ RECORD("y0", "cb_obj.y0", final=False) + \ RECORD("y1", "cb_obj.y1") plot.js_on_event(RangesUpdate, CustomJS(code=code)) plot.add_tools(CustomAction(callback=CustomJS(code=""))) plot.toolbar_sticky = False page = single_plot_page(plot) button = page.get_toolbar_button('zoom-out') button.click() page.click_custom_action() results = page.results assert results['event_name'] == "rangesupdate" assert results['x0'] < 0 assert results['x1'] > 1 assert results['y0'] < 0 assert results['y1'] > 1 assert page.has_no_console_errors()
def map_plot(nx, ny, source, other=None, output_backend=MAP_BACKEND): tools = [ PanTool(dimensions='both'), ZoomInTool(dimensions='both'), ZoomOutTool(dimensions='both'), ResetTool(), HoverTool(tooltips=[ tooltip(x) for x in (N.LATITUDE, N.LONGITUDE, N.DISTANCE_KM, N.LOCAL_TIME) ]) ] f = figure(output_backend=output_backend, plot_width=nx, plot_height=ny, x_axis_type='mercator', y_axis_type='mercator', match_aspect=True, tools=tools) add_route(f, source) if present(other, N.SPHERICAL_MERCATOR_X, N.SPHERICAL_MERCATOR_Y): add_route(f, other, color='black', line_dash='dotted') f.add_tile(STAMEN_TERRAIN, alpha=0.3) f.axis.visible = False f.toolbar.logo = None return f
def plot_bqm(bqm): """Plot binary quadratic model as a labeled graph.""" g = nx.Graph() g.add_nodes_from(bqm.variables) g.add_edges_from(bqm.quadratic) plot_size = 400 text_size = '16pt' graph = from_networkx(g, nx.spring_layout) graph.node_renderer.glyph = Circle(size=35, fill_color='purple', fill_alpha=0.25) graph.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=2) pos = nx.spring_layout(g) data = {'xpos': [], 'ypos': [], 'label': []} for label, loc in pos.items(): data['label'].append(label) data['xpos'].append(loc[0]) data['ypos'].append(loc[1]) labels = LabelSet(x='xpos', y='ypos', text='label', level='glyph', source=ColumnDataSource(data), x_offset=-1, y_offset=-1, text_color="blue", text_font_size='14pt', text_font_style='bold') plot = Plot(plot_width=plot_size, plot_height=plot_size, x_range=Range1d(-1.3, 1.3), y_range=Range1d(-1.3, 1.3)) plot.title.text = "BQM with {} nodes and {} edges".format(len(bqm), len(bqm.quadratic)) tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] plot.add_tools(*tools) plot.toolbar.active_scroll = tools[0] plot.renderers.append(graph) plot.add_layout(labels) plot.background_fill_color = "lightyellow" show(plot)
def std_distance_time_plot(nx, ny, source, x_range=None): groups = list(related_statistics(source, ACTIVE_TIME)) if not groups: # original monochrome plot return multi_dot_plot(nx, ny, TIME, [ACTIVE_TIME_H, ACTIVE_DISTANCE_KM], source, ['black', 'grey'], alphas=[1, 0.5], x_range=x_range, rescale=True) times = [f'{ACTIVE_TIME} ({group})' for group in groups] distances = [f'{ACTIVE_DISTANCE} ({group})' for group in groups] time_y_range = make_range(source, ACTIVE_TIME_H) distance_y_range = make_range(source, ACTIVE_DISTANCE_KM) colours = list(evenly_spaced_hues(len(groups))) tools = [ PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[ tooltip(x) for x in (ACTIVE_TIME_H, ACTIVE_DISTANCE_KM, ACTIVITY_GROUP, LOCAL_TIME) ], names=['with_hover']) ] f = figure(plot_width=nx, plot_height=ny, x_axis_type='datetime', tools=tools) f.yaxis.axis_label = f'lines - {ACTIVE_TIME_H}' f.y_range = time_y_range f.extra_y_ranges = {ACTIVE_DISTANCE: distance_y_range} f.add_layout( LinearAxis(y_range_name=ACTIVE_DISTANCE, axis_label=f'dots - {ACTIVE_DISTANCE_KM}'), 'right') plotter = comb_plotter() for time, colour in zip(times, colours): time_h = _slash(time, H) source[time_h] = source[time] / 3600 plotter(f, x=TIME, y=time_h, source=source, color=colour, alpha=1) plotter = dot_plotter() for distance, colour in zip(distances, colours): distance_km = _slash(distance, KM) source[distance_km] = source[distance] / 1000 plotter(f, x=TIME, y=distance_km, source=source, color=colour, alpha=1, name='with_hover', y_range_name=ACTIVE_DISTANCE) f.xaxis.axis_label = TIME f.toolbar.logo = None if ny < 300: f.toolbar_location = None if x_range: f.x_range = x_range return f
def make_plot(data): # Make the API request and load json data into DataFrame symbol = 'amzn' res = requests.get(API_URL.format(symbol)) data = res.json() df = pd.DataFrame(data) # Add a new column in the shape of the original data seqs = np.arange(df.shape[0]) df['seqs'] = pd.Series(seqs) # Add a mid column that is midpoint between open and close df['mid'] = df.apply(lambda x: (x['open'] + x['close']) / 2, axis=1) # Add height column after checking if close is greater than open df['height'] = df.apply(lambda x: x['close'] - x['open'] if x['close'] != x['open'] else 0.01, axis=1) # some stuff to format plot inc = df.close > df.open # Series where stocks closed higher than they opened dec = df.close < df.open # Series in which stocks closed lower than they opened w = .3 # line width for plot # some stuff to format plot inc = df.close > df.open # Series where stocks closed higher than they opened dec = df.close < df.open # Series in which stocks closed lower than they opened w = .3 # line width for plot # Define sources for increasing and decreasing stocks sourceInc = bk.ColumnDataSource(df.loc[inc]) sourceDec = bk.ColumnDataSource(df.loc[dec]) # Define the Bokeh tools to include in the figure hover = HoverTool( tooltips=[ ('Date', '@date'), ('Low', '@low'), ('High', '@high'), ('Open', '@open'), ('Close', '@close'), ('Percent', '@changePercent') ] ) TOOLS = [hover, BoxZoomTool(), PanTool(), ZoomInTool(), ZoomOutTool(), ResetTool()] # Define size and layout of figure p = bk.figure(plot_width=1200, plot_height=800, title='Amazon', tools=TOOLS, toolbar_location='above') p.xaxis.major_label_orientation = np.pi/4 p.grid.grid_line_alpha = w descriptor = Label(x=70, y=70, text='Amazon Stock Price Over Time') p.add_layout(descriptor) # Create segments for price increases p.segment(df.seqs[inc], df.high[inc], df.seqs[inc], df.low[inc], color='green') # Create segments for price decreases p.segment(df.seqs[dec], df.high[dec], df.seqs[dec], df.low[dec], color='red') # Create rects for price increases p.rect(x='seqs', y='mid', width=w, height='height', fill_color='green', line_color='green', source=sourceInc) # Create rects for price decreases p.rect(x='seqs', y='mid', width=w, height='height', fill_color='red', line_color='red', source=sourceDec) script, div = components(p) return script, div
def plot_pca_apexbio_asinex(self, parameter, a, b): result = self.result print(a, b) source1 = column_source(result, "APEXBIO") source2 = column_source(result, "Asinex") hover = HoverTool(tooltips=[ ("PCA 1", "$x"), ("PCA 2", "$y"), ("ID", "@N"), ]) p = figure( # title="PCA based on: " + parameter, x_axis_label="PC 1 " + str(a) + "%", y_axis_label="PC 2 " + str(b) + "%", x_range=(-2, 6), y_range=(-4, 4.1), tools=[hover], plot_width=1000, plot_height=800, ) p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), PanTool()) APEXBIO_plot = p.circle(x="x", y="y", source=source1, color="mediumvioletred", size=5) Asinex_plot = p.circle(x="x", y="y", source=source2, color="mediumslateblue", size=5) legend = Legend( items=[ ("APEXBIO", [APEXBIO_plot]), ("Asinex", [Asinex_plot]), ], location="center", orientation="vertical", click_policy="hide", ) p.add_layout(legend, place="right") p.xaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_text_font_size = "20pt" p.xaxis.axis_label_text_color = "black" p.yaxis.axis_label_text_color = "black" p.xaxis.major_label_text_font_size = "18pt" p.yaxis.major_label_text_font_size = "18pt" p.title.text_font_size = "22pt" # show(p) # save p.output_backend = "svg" export_svgs( p, filename="/Users/eurijuarez/Desktop/Alexis/Plots/SVG_files/" + "ChemSpace_PCA_APEXBIO_Asinex" + ".svg", )
def plot_gmap(zones, trips=None, **map_options): """Plot zones over a Google Map. Examples: - plot_gmap(['Astoria', 'Manhattan'], zoom=12) - plot_gmap(['Astoria', 'Midtown', 'Greenpoint', 'Sunnyside', 'Harlem']) """ # Gather zone data polygons = [ GeoJSONDataSource(geojson=json.dumps(load_geojson(z))) for z in zones ] u = unary_union([load_geojson(z, make_shape=True) for z in zones]) m_polygons = u.centroid plot = GMapPlot( api_key=GOOGLE_API_KEY, x_range=Range1d(), y_range=Range1d(), map_options=GMapOptions( lat=m_polygons.y, lng=m_polygons.x, map_type="roadmap", **map_options, ), ) plot.toolbar.logo = None plot.toolbar_location = "above" plot.title.text = None # Toolbar wheel_zoom = WheelZoomTool() plot.add_tools( PanTool(), BoxZoomTool(), BoxSelectTool(), wheel_zoom, ZoomInTool(), ZoomOutTool(), ResetTool(), SaveTool(), ) plot.toolbar.active_scroll = wheel_zoom # Add neighborhood polygons for geo_source in polygons: glyph = Patches(xs="xs", ys="ys", fill_color="Blue", fill_alpha=0.2) plot.add_glyph(geo_source, glyph) # Add trips if trips is not None: add_trips_to_plot(plot, trips) output_file("plots/plot.html") show(plot) return plot
def get_charts(self, mobile=False) -> Dict[str, figure]: if self._sort is None: self.get_sort() # the song names original old_names = [x.name for x in self._tracks] # the song names sorted sorted_names = [old_names[i] for i in self._sort] # the unsorted locations locs = np.array(self._locations) # the sorted locations sorted_locs = np.array([locs[i] for i in self._sort]) # create a ColumnDataSource for the original data old_source = ColumnDataSource(data=dict( x=locs[:, 0], y=locs[:, 1], name=old_names, )) # create a ColumnDataSource for the sorted data new_source = ColumnDataSource(data=dict( x=sorted_locs[:, 0], y=sorted_locs[:, 1], name=sorted_names, )) # our hovertool shoes the name and the x,y position hover = HoverTool(tooltips=[ ("name", "@name"), ("(x,y)", "($x, $y)"), ]) # the unsorted figure if mobile: logger.debug('Mobile browser detected') toolset = [hover] else: toolset = [hover, BoxZoomTool(), ZoomInTool(), ZoomOutTool(), ResetTool()] p_orig = figure(plot_width=400, plot_height=400, tools=toolset) # the sorted figure p_sort = figure(plot_width=400, plot_height=400, tools=toolset) # add the circles p_orig.circle('x', 'y', size=5, color="navy", alpha=0.5, source=old_source) p_sort.circle('x', 'y', size=5, color="navy", alpha=0.5, source=new_source) # now the lines p_orig.line('x', 'y', line_width=2, color="red", source=old_source) p_sort.line('x', 'y', line_width=2, color="red", source=new_source) # return a dictionary of name, figure plots = {'original': p_orig, 'sorted': p_sort} return components(plots)
def make_tools(y): tools = [ PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[tooltip(x) for x in (y, DISTANCE_KM, LOCAL_TIME)]) ] return tools
def multi_plot(nx, ny, x, ys, source, colors, alphas=None, x_range=None, y_label=None, rescale=False, plotters=None): tools = [ PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[tooltip(x) for x in ys + [LOCAL_TIME]]) ] f = figure(plot_width=nx, plot_height=ny, x_axis_type='datetime' if TIME in x else 'linear', tools=tools) if y_label: f.yaxis.axis_label = y_label elif rescale: f.yaxis.axis_label = ys[0] else: f.yaxis.axis_label = ', '.join(ys) if rescale: f.extra_y_ranges = {} if alphas is None: alphas = [1 for _ in ys] while len(plotters) < len(ys): plotters += plotters for y, color, alpha, plotter in zip(ys, colors, alphas, plotters): mn, mx = source[y].dropna().min(), source[y].dropna().max() dy = mx - mn if rescale and y != ys[0]: f.extra_y_ranges[y] = Range1d(start=mn - 0.1 * dy, end=mx + 0.1 * dy) f.add_layout(LinearAxis(y_range_name=y, axis_label=y), 'right') plotter(f, x=x, y=y, source=source, color=color, alpha=alpha, y_range_name=y) else: f.y_range = Range1d(start=mn - 0.1 * dy, end=mx + 0.1 * dy) plotter(f, x=x, y=y, source=source, color=color, alpha=alpha) f.xaxis.axis_label = x f.toolbar.logo = None if ny < 300: f.toolbar_location = None if x_range: f.x_range = x_range return f
def list(self, request, symbol=None): API_URL = 'https://api.iextrading.com/1.0' res = requests.get(f'{API_URL}/stock/'f'{symbol}/chart/5y') data = res.json() df = pd.DataFrame(data) # Candlestick chart setup seqs = np.arange(df.shape[0]) df['seqs'] = pd.Series(seqs) df['changePercent'] = df['changePercent'].apply(lambda x: str(x)+'%') df['mid'] = df.apply(lambda x: (x['open'] + x['close']) / 2, axis=1) df['height'] = df.apply( lambda x: x['close'] - x['open'] if x['close'] != x['open'] else 0.001, axis=1) inc = df.close > df.open dec = df.close < df.open w = .3 sourceInc = bk.ColumnDataSource(df.loc[inc]) sourceDec = bk.ColumnDataSource(df.loc[dec]) hover = HoverTool( tooltips=[ ('date', '@date'), ('low', '@low'), ('high', '@high'), ('open', '@open'), ('close', '@close'), ('percent', '@changePercent'), ] ) TOOLS = [hover, BoxZoomTool(), PanTool(), ZoomInTool(), ZoomOutTool(), ResetTool()] p = bk.figure(plot_width=1500, plot_height=800, tools=TOOLS, title=symbol, toolbar_location='above') p.xaxis.major_label_orientation = np.pi/4 p.grid.grid_line_alpha = w descriptor = Label(x=70, y=70, text='Your label goes here') p.add_layout(descriptor) p.segment(df.seqs[inc], df.high[inc], df.seqs[inc], df.low[inc], color='green') p.segment(df.seqs[dec], df.high[dec], df.seqs[dec], df.low[dec], color='red') p.rect(x='seqs', y='mid', width=w, height='height', fill_color='green', line_color='green', source=sourceInc) p.rect(x='seqs', y='mid', width=w, height='height', fill_color='red', line_color='red', source=sourceDec) bk.save(p, './static/candle_stick.html', title='5yr_candlestick') return Response(bk.show(p))
def plot(df, xcol, ycol, tags, groupby, colors, outprefix): output_file(f'{outprefix}.html') tooltips = [(f"({xcol},{ycol})", f"(@{xcol}, @{ycol})")] for tag in tags: tooltips.append((f"{tag}", f"@{tag}")) hover = HoverTool(tooltips=tooltips) p = figure(title="", tools=[ hover, BoxZoomTool(), ResetTool(), WheelZoomTool(), PanTool(), SaveTool(), ZoomInTool(), ZoomOutTool() ], toolbar_location="below", toolbar_sticky=False, plot_width=800, plot_height=600, x_axis_label=xcol, y_axis_label=ycol) if groupby: for ngroup, group in enumerate(df[groupby].unique()): if type(colors) == dict: color = colors[group] else: color = colors[ngroup] source = ColumnDataSource(df.loc[df[groupby] == group, :]) p.circle(x=xcol, y=ycol, size=10, alpha=1, color=color, source=source, legend=group) p.legend.location = "top_left" p.legend.click_policy = "hide" else: source = ColumnDataSource(df) p.circle(x=xcol, y=ycol, size=10, alpha=0.8, color=colors, source=source) save(p)
def large_plot(n): from bokeh.models import ( Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, SaveTool, ResetTool ) from bokeh.models.layouts import Column from bokeh.models.glyphs import Line col = Column() objects = set([col]) for i in xrange(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, yaxis, 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 large_plot(n): from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, ResizeTool, SaveTool, ResetTool) from bokeh.models.layouts import VBox from bokeh.models.glyphs import Line vbox = VBox() objects = set([vbox]) for i in xrange(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=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) 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() resize = ResizeTool() save = SaveTool() reset = ResetTool() tools = [ pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, resize, save, reset ] plot.add_tools(*tools) vbox.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.toolbar, plot.tool_events, plot.title, box_zoom.overlay, box_select.overlay ] + tickers + tools) return vbox, objects
def comparison_line_plot(nx, ny, x, y, source, other=None, ylo=None, yhi=None, x_range=None, output_backend=DEFAULT_BACKEND): if not present(source, x, y): return None tools = [ PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[ tooltip(x) for x in (y, Names.DISTANCE_KM, Names.LOCAL_TIME) ], names=['with_hover']) ] f = figure(output_backend=output_backend, plot_width=nx, plot_height=ny, x_axis_type='datetime' if Names.TIME in x else 'linear', tools=tools) f.y_range = make_range(source[y], lo=ylo, hi=yhi) # was this ignored previously? add_tsid_line(f, x, y, source) if present(other, y): add_tsid_line(f, x, y, other, color='grey') diff = subtract(source, other, x, y) green, red, y_range2 = patches(x, y, diff) f.extra_y_ranges = {'delta': y_range2} f.patch(x=green.index, y=green, color='green', alpha=0.1, y_range_name='delta') f.patch(x=red.index, y=red, color='red', alpha=0.1, y_range_name='delta') f.yaxis.axis_label = y f.xaxis.axis_label = x f.toolbar.logo = None if x_range: f.x_range = x_range return f
def __init__(self, InverterSettings, StorageSettings): self.InvSettings = InverterSettings self.StorageSettings = StorageSettings self.clearTopologyData() self.source = ColumnDataSource(self.TopologyData) self.sourceNode = ColumnDataSource(self.NodeData) callback = CustomJS(code="""console.info("hello TapTool")""") tt = TapTool(callback=callback) map_options = GMapOptions(lat=36, lng=-106, map_type='roadmap', zoom=8) self.TopologyPlot = gmap('AIzaSyCiQT0TLjv0G25HN03eRJjQVfk6xRsMITo', map_options, plot_width=1200, plot_height=1000) self.TopologyPlot.toolbar.logo = None self.TPmulti_lines = self.TopologyPlot.multi_line(xs='Xs', ys='Ys', source=self.source, line_width=1, line_alpha=1.0,line_color="darkblue", legend='Edges') self.TPcircles = self.TopologyPlot.circle(x='X', y='Y', source=self.sourceNode, legend='Nodes', color='PV', radius=20, hover_color="red") self.TopologyPlot.toolbar.active_tap = 'auto' self.TopologyPlot.xaxis.axis_label = 'Longitude' self.TopologyPlot.yaxis.axis_label = 'Latitude' self.TopologyPlot.legend.location = "top_right" self.TopologyPlot.legend.click_policy = "hide" hoverBus = HoverTool(show_arrow=False, line_policy='next', tooltips=[ ("Element", "@Name"), ("Class", "@Class"), ("Phases", "@Phases"), ("Distance", "@D") ]) self.TopologyPlot.tools.append(hoverBus) self.TopologyPlot.tools.append(TapTool()) self.TopologyPlot.tools.append(ZoomInTool()) self.TopologyPlot.tools.append(ZoomOutTool()) self.final_layout = self.TopologyPlot self.TPcircles.data_source.on_change('selected', self.test) #taptool = self.TopologyPlot.select(type=TapTool) #taptool.callback = callback return
def _make_plot(): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) plot = Plot(height=400, width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(ZoomOutTool()) code = RECORD("xrstart", "p.x_range.start", final=False) + \ RECORD("xrend", "p.x_range.end", final=False) + \ RECORD("yrstart", "p.y_range.start", final=False) + \ RECORD("yrend", "p.y_range.end") plot.tags.append( CustomJS(name="custom-action", args=dict(p=plot), code=code)) plot.toolbar_sticky = False return plot
def map_intensity(nx, ny, source, z, power=1.0, color='red', alpha=0.01, ranges=None, output_backend=MAP_BACKEND): if not present(source, z): return None tools = [PanTool(dimensions='both'), ZoomInTool(dimensions='both'), ZoomOutTool(dimensions='both'), ResetTool(), HoverTool(tooltips=[tooltip(x) for x in (z, DISTANCE_KM, LOCAL_TIME)])] f = figure(output_backend=output_backend, plot_width=nx, plot_height=ny, x_axis_type='mercator', y_axis_type='mercator', title=z, match_aspect=True, tools=tools) tools[-1].renderers = [add_route(f, source)] mn, mx = source[z].min(), source[z].max() source['size'] = sqrt(nx * ny) * ((source[z] - mn) / (mx - mn)) ** power / 10 f.circle(x=SPHERICAL_MERCATOR_X, y=SPHERICAL_MERCATOR_Y, size='size', source=source, color=color, alpha=alpha) f.axis.visible = False f.toolbar.logo = None if ranges is not None: f.x_range = ranges.x_range f.y_range = ranges.y_range return f
def NLD_add_tools(plot): plot.add_tools(WheelZoomTool()) plot.add_tools(ZoomInTool()) plot.add_tools(ZoomOutTool()) plot.add_tools(ResetTool()) plot.add_tools(UndoTool()) plot.add_tools(RedoTool()) plot.add_tools(PanTool()) plot.add_tools(TapTool()) plot.add_tools(SaveTool()) plot.add_tools(BoxSelectTool()) plot.add_tools(LassoSelectTool()) plot.add_tools(BoxZoomTool()) # !!! Hover the node attributes !!! node_hover = HoverTool(tooltips=[('Name', '@index'), ('Degree', '@degree'), ('Min Weight', '@minweight'), ('Max Weight', '@maxweight'), ('Average Weight', '@avrweight'), ('Sum Weight', '@sumweight')]) plot.add_tools(node_hover)
def std_distance_time_plot(nx, ny, source, x_range=None, output_backend=DEFAULT_BACKEND): # avoid range errors if len(source[N.ACTIVE_TIME_S].dropna()) < 2: return None groups = [group for statistic, group in related_statistics(source, N.ACTIVE_TIME)] if not groups: # original monochrome plot return multi_dot_plot(nx, ny, N.TIME, [N.ACTIVE_TIME_H, N.ACTIVE_DISTANCE_KM], source, ['black', 'grey'], alphas=[1, 0.5], x_range=x_range, rescale=True) times = [f'{N.ACTIVE_TIME}:{group}' for group in groups] distances = [f'{N.ACTIVE_DISTANCE}:{group}' for group in groups] time_y_range = make_range(source[N.ACTIVE_TIME_H]) distance_y_range = make_range(source[N.ACTIVE_DISTANCE_KM]) colours = list(evenly_spaced_hues(len(groups))) tooltip_names = [N.ACTIVE_TIME_H, N.ACTIVE_DISTANCE_KM, N.ACTIVITY_GROUP, N.LOCAL_TIME] tooltip_names += [name for name in like(N._delta(N.FITNESS_ANY), source.columns) if ':' not in name] tooltip_names += [name for name in like(N._delta(N.FATIGUE_ANY), source.columns) if ':' not in name] tools = [PanTool(dimensions='width'), ZoomInTool(dimensions='width'), ZoomOutTool(dimensions='width'), ResetTool(), HoverTool(tooltips=[tooltip(name) for name in tooltip_names], names=['with_hover'])] f = figure(output_backend=output_backend, plot_width=nx, plot_height=ny, x_axis_type='datetime', tools=tools) f.yaxis.axis_label = f'lines - {N.ACTIVE_TIME_H}' f.y_range = time_y_range f.extra_y_ranges = {N.ACTIVE_DISTANCE: distance_y_range} f.add_layout(LinearAxis(y_range_name=N.ACTIVE_DISTANCE, axis_label=f'dots - {N.ACTIVE_DISTANCE_KM}'), 'right') plotter = comb_plotter() for time, colour, group in zip(times, colours, groups): time_h = N._slash(time, Units.H) source[time_h] = source[time] / 3600 source[N.ACTIVITY_GROUP] = group plotter(f, x=N.TIME, y=time_h, source=source, color=colour, alpha=1) plotter = dot_plotter() for distance, colour, group in zip(distances, colours, groups): distance_km = N._slash(distance, Units.KM) source[distance_km] = source[distance] source[N.ACTIVITY_GROUP] = group plotter(f, x=N.TIME, y=distance_km, source=source, color=colour, alpha=1, name='with_hover', y_range_name=N.ACTIVE_DISTANCE) f.xaxis.axis_label = N.TIME f.toolbar.logo = None if ny < 300: f.toolbar_location = None if x_range: f.x_range = x_range return f
def plot(self, source1, source2, source3, source4, source5, source6, source7, source8, source9): a = self.a b = self.b hover = HoverTool(tooltips = [ ("PCA1","($x)"), ("PCA2","($y)"), ("NAME","(@N)"), ]) p = figure( title = "CHEMICAL SPACE BY MORGAN3 FP", x_axis_label = "PC 1 " + "("+str(a)+"%)", y_axis_label="PC 2 " + "("+str(b)+"%)", x_range = (-7,7), y_range = (-7,7), tools = [hover], plot_width = 1000, plot_height = 800) FDA_plot = p.circle(x = "x", y = "y", source = source1, color = "darkslateblue", size = 5) PPI_plot = p.circle(x = "x", y = "y", source = source2, color = "yellowgreen", size = 5) MACRO_plot = p.circle(x = "x", y = "y", source = source3, color ="lightsteelblue", size = 5) NP_plot = p.circle(x = "x", y = "y", source = source4, color = "olive", size = 5) PEP_FDA_plot = p.circle(x = "x", y = "y", source = source5, color ="darkslategray", size = 5) LIN_plot = p.circle(x = "x", y = "y", source = source6, color = "aquamarine", size = 5) LIN_NM_plot = p.circle(x = "x", y = "y", source = source7, color = "teal", size = 5) CYC_plot = p.circle(x = "x", y = "y", source = source8, color = "lightpink", size = 5) CYC_NM_plot = p.circle(x = "x", y = "y", source = source9, color = "mediumvioletred", size = 5) p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), PanTool()) legend = Legend(items=[ ("FDA", [FDA_plot]), ("PPI", [PPI_plot]), ("MACRO", [MACRO_plot]), ("NP", [NP_plot]), ("PEP FDA", [PEP_FDA_plot]), ("LIN", [LIN_plot]), ("LIN NM", [LIN_NM_plot]), ("CYC", [CYC_plot]), ("CYC NM", [CYC_NM_plot]), ], location = "center", orientation = "vertical", click_policy = "hide" ) p.add_layout(legend, place = 'right') p.xaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_text_font_size = "20pt" p.xaxis.axis_label_text_color = "black" p.yaxis.axis_label_text_color = "black" p.xaxis.major_label_text_font_size = "18pt" p.yaxis.major_label_text_font_size = "18pt" p.title.text_font_size = "22pt" return p
def plot(self, source1, source2, source3, source4, source5, source6, source7, source8, source9): hover = HoverTool(tooltips = [ ("Similarity","($x)"), ("ECF","($y)"), ]) p = figure(title = "MACCS keys FP/Tanimoto Similarity", x_axis_label = "Similarity", y_axis_label="Cumulative Distribution Function", x_range = (0,1), y_range = (0,1), tools=[hover], plot_width = 1000, plot_height = 800) FDA_plot = p.line(x = "x", y = "y", source = source1, line_width = 3, color="darkslateblue") PPI_plot = p.line(x = "x", y = "y", source = source2, line_width = 3, color="yellowgreen") MACRO_plot = p.line(x = "x", y = "y", source = source3, line_width = 3, color="lightsteelblue") NP_plot = p.line(x = "x", y = "y", source = source4, line_width = 3, color="olive") PEP_FDA_plot = p.line(x = "x", y = "y", source = source5, line_width = 3, color="darkslategray") LIN_plot = p.line(x = "x", y = "y", source = source6, line_width = 3, color="aquamarine") LIN_NM_plot = p.line(x = "x", y = "y", source = source7, line_width = 3, color="teal") CYC_plot = p.line(x = "x", y = "y", source = source8, line_width = 3, color="lightpink") CYC_NM_plot = p.line(x = "x", y = "y", source = source9, line_width = 3, color="mediumvioletred") p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), PanTool()) legend = Legend(items=[ ("FDA", [FDA_plot]), ("PPI", [PPI_plot]), ("MACRO", [MACRO_plot]), ("NP", [NP_plot]), ("PEP FDA", [PEP_FDA_plot]), ("LIN", [LIN_plot]), ("LIN NM", [LIN_NM_plot]), ("CYC", [CYC_plot]), ("CYC NM", [CYC_NM_plot]), ], location = "center", orientation = "vertical", click_policy = "hide") p.add_layout(legend, place = 'right') p.xaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_text_font_size = "20pt" p.xaxis.axis_label_text_color = "black" p.yaxis.axis_label_text_color = "black" p.xaxis.major_label_text_font_size = "18pt" p.yaxis.major_label_text_font_size = "18pt" p.title.text_font_size = "22pt" return p
def map_plot(nx, ny, source, other=None): tools = [ PanTool(dimensions='both'), ZoomInTool(dimensions='both'), ZoomOutTool(dimensions='both'), ResetTool(), HoverTool(tooltips=[ tooltip(x) for x in (LATITUDE, LONGITUDE, DISTANCE_KM, LOCAL_TIME) ]) ] f = figure(plot_width=nx, plot_height=ny, x_axis_type='mercator', y_axis_type='mercator', tools=tools) add_route(f, source) if present(other, SPHERICAL_MERCATOR_X, SPHERICAL_MERCATOR_Y): add_route(f, other, color='black', line_dash='dotted') f.add_tile(tile_providers.STAMEN_TERRAIN, alpha=0.3) f.axis.visible = False f.toolbar.logo = None return f
def plot_data(df, dsn): # print("plot_data") '''Plot the data in the given dataframe Parameters: df (dataframe) - data from the given dsn dsn (str) - device identifier ''' names = [ "heart_rate_raw", "oxygen_raw", "skin_temperature", "base_state", "movement_raw" ] colors = ["red", "blue", "orange", "purple", "green"] alphas = [.8, 8, .8, .6, .5] # Where data is stored so it can be displayed and changed dynamically source_data, source_data1, source_data2, source_data3, source_data4, source_data5, min_val, max_hr = get_source( df, names) # Multiple sources because there are different lengths of data source = ColumnDataSource(data=source_data) source1 = ColumnDataSource(data=source_data1) source2 = ColumnDataSource(data=source_data2) source3 = ColumnDataSource(data=source_data3) source4 = ColumnDataSource(data=source_data4) source5 = ColumnDataSource(data=source_data5) # Build plot tools hover_tool = HoverTool( tooltips=[ ('time', '@date{%T}'), ] + [(name, '@{}'.format(name)) for name in ["heart_rate_raw", "oxygen_raw", "base_state", "movement_raw"]] + [('notification', '@notification_mask')] + [("skin_temperature", '@skin_temperature')], formatters={ 'date': 'datetime', }, # use default 'numeral' formatter for other fields mode='vline', renderers=[]) crosshair = CrosshairTool(dimensions='height', line_alpha=.6) box_zoom = BoxZoomTool(dimensions='width') zoom_out = ZoomOutTool(dimensions='width', factor=.5) save = CustomSaveTool(save_name=dsn) x_range_start = df.timestamp.min() - timedelta(minutes=30) x_range_end = df.timestamp.max() + timedelta(minutes=30) # Create figure; use webgl for better rendering tools = [save, box_zoom, 'xpan', zoom_out, hover_tool, crosshair] p = figure(width=950, height=500, title="{} Data".format(dsn), x_axis_type="datetime", tools=tools, toolbar_location="above", x_range=(x_range_start, x_range_end), y_range=(0, max_hr + (24 * (len(names) + 1))), output_backend='webgl') # To have the Legend outside the plot, each line needs to be added to it legend_it = [] for i in range(len(names)): legend_line = p.line(x=df.timestamp.iloc[-1:], y=0, color=colors[i], alpha=1, line_width=2) if names[i] in ["movement_raw", "base_state"]: legend_it.append((names[i], [ legend_line, p.multi_line(xs='plot_xs', ys='plot_' + names[i], color=colors[i], alpha=alphas[i], source=source1) ])) else: bad_data_line = p.multi_line(xs='bad_x', ys='bad_' + names[i], color=colors[i], alpha=.1, source=source3) legend_it.append((names[i], [ legend_line, p.multi_line(xs='good_x', ys='good_' + names[i], color=colors[i], alpha=alphas[i], source=source2), bad_data_line ])) legend_it.append(("Yellow notifications", [ p.multi_line(xs='yellow', ys='ys', color='#F5BE41', line_dash='dashed', line_width=1.5, source=source4) ])) legend_it.append(("Red notifications", [ p.multi_line(xs='red', ys='red_ys', color='red', line_dash='dashed', source=source5) ])) # Creating a location for the tooltip box to appear (so it doesn't cover the data) horizontal_line = p.line(x='date', y='horizontal', color='white', alpha=0, source=source) hover_tool.renderers.append(horizontal_line) p.xaxis.axis_label = 'Time' p.xaxis.formatter = DatetimeTickFormatter(days=["%m/%d %T"], months=["%m/%d %T"], hours=["%m/%d %T"], minutes=["%m/%d %T"], seconds=["%m/%d %T"], minsec=["%m/%d %T"], hourmin=["%m/%d %T"]) legend = Legend(items=legend_it) legend.click_policy = "hide" # Hide lines when they are clicked on p.add_layout(legend, 'right') return p, source, source1, source2, source3, source4, source5
def spectrum_slice_app(doc): def load_wav_cb(attr, old, new): '''Handle selection of audio file to be loaded.''' global wavname base_url, fname = os.path.split(new) wavname = get_cached_fname(fname, base_url, tempdir) if not wavname.endswith('.wav'): return update_snd() playvisbtn.channels = channels playvisbtn.visible = True playselbtn.channels = channels playselbtn.visible = True playvisbtn.fs = snd.sampling_frequency playvisbtn.start = snd.start_time playvisbtn.end = snd.end_time playselbtn.fs = snd.sampling_frequency playselbtn.start = 0.0 playselbtn.end = 0.0 ch0.visible = True update_sgram() update_spslice(t=None) def file_input_cb(attr, old, new): '''Handle audio file upload.''' with NamedTemporaryFile() as tempfile: tempfile.write(b64decode(new)) tempsnd = parselmouth.Sound(tempfile.name) ds_snd = tempsnd.resample(params['downsample_rate'], 50) cachefile = os.path.join(tempdir, file_input.filename) ds_snd.save(cachefile, parselmouth.SoundFileFormat.WAV) options = fselect.options.copy() options += [(cachefile, file_input.filename)] fselect.options = options fselect.value = fselect.options[-1][0] def update_snd(): '''Update the sound (waveform and audio button).''' global snd snd = parselmouth.Sound(wavname) if snd.n_channels > 1: snd = snd.convert_to_mono() if filter_sel.value not in ('no filter', 'no filter (clear)' ) and spselbox.right is not None: if filter_sel.value.startswith('stopband'): func = 'Filter (stop Hann band)...' if filter_sel.value.startswith('passband'): func = 'Filter (pass Hann band)...' snd = parselmouth.praat.call(snd, func, spselbox.left, spselbox.right, 100.0) source.data = dict( seconds=snd.ts().astype(np.float32), ch0=snd.values[0, :].astype(np.float32), ) def update_sgram(): '''Update spectrogram based on current values.''' if filter_sel.value == 'no filter (clear)': sgselbox.bottom = None sgselbox.top = None sgselbox.visible = False else: sgselbox.visible = True sgrams[0] = snd2specgram(snd, winsize=winsize_slider.value * 10**-3) specsource.data = dict(sgram0=[sgrams[0].values.astype(np.float32)]) spec0img.glyph.dw = sgrams[0].x_grid().max() spec0img.glyph.dh = sgrams[0].y_grid().max() spec0cmap.low = _low_thresh() spec0.visible = True def update_spslice(t=None): '''Update spslice plot with spectrum slice at time t.''' if t is not None: slidx = np.round( parselmouth.praat.call(sgrams[0], 'Get frame number from time...', t)).astype(int) spslice = sgrams[0].values[:, slidx] spdata = dict(freq=np.arange(sgrams[0].values.shape[0]) * sgrams[0].dy, power=spslice) spselbox.visible = True else: spdata = dict(freq=np.array([]), power=np.array([])) spec0_fq_marker.visible = False spslice0_fq_marker.visible = False spselbox.visible = False if filter_sel.value == 'no filter (clear)': spselbox.left = None spselbox.right = None spselbox.visible = False spslice_source.data = spdata spslice0.x_range = Range1d(0.0, sgrams[0].get_highest_y()) spslice0.y_range = Range1d(0.0, sgrams[0].get_maximum()) thresh_box.top = _low_thresh() try: fqidx = np.abs(spslice_source.data['freq'] - fq_marker_source.data['freq'][0]).argmin() fq_marker_source.data['power'] = [ spslice_source.data['power'][fqidx] ] except ValueError: pass # Not set yet def cursor_cb(e): '''Handle cursor mouse click that creates the spectrum slice.''' cursor.location = e.x update_spslice(t=e.x) idx = np.abs(spslice_source.data['freq'] - e.y).argmin() fq_marker_source.data = dict(freq=[e.y], power=[spslice_source.data['power'][idx]], time=[e.x]) params['spslice_lastx'] = e.y spec0_fq_marker.visible = True spslice0_fq_marker.visible = True def spslice_move_cb(e): '''Handle a MouseMove event on spectrum slice crosshair tool.''' try: if params[ 'spslice_lastx'] != e.x and e.x >= 0 and e.x <= spslice_source.data[ 'freq'][-1]: params['spslice_lastx'] = e.x idx = np.abs(spslice_source.data['freq'] - e.x).argmin() fq_marker_source.data['freq'] = [ spslice_source.data['freq'][idx] ] fq_marker_source.data['power'] = [ spslice_source.data['power'][idx] ] except IndexError: # data not loaded yet pass def x_range_cb(attr, old, new): '''Handle change of x range in waveform/spectrogram.''' if attr == 'start': playvisbtn.start = new elif attr == 'end': playvisbtn.end = new def selection_cb(e): '''Handle data range selection event.''' playselbtn.start = e.geometry['x0'] playselbtn.end = e.geometry['x1'] selbox.left = e.geometry['x0'] selbox.right = e.geometry['x1'] selbox.visible = True def low_thresh_cb(attr, old, new): '''Handle change in threshold slider to fade out low spectrogram values.''' params['low_thresh_power'] = new lt = _low_thresh() spec0cmap.low = lt thresh_box.top = lt def _low_thresh(): return sgrams[0].values.min() \ + sgrams[0].values.std()**params['low_thresh_power'] def winsize_cb(attr, old, new): '''Handle change in winsize slider to change spectrogram analysis window.''' params['window_size'] = new update_sgram() if cursor.location is not None: update_spslice(t=cursor.location) idx = np.abs(spslice_source.data['freq'] - params['spslice_lastx']).argmin() fq_marker_source.data = dict( freq=[spslice_source.data['freq'][idx]], power=[spslice_source.data['power'][idx]], time=[cursor.location]) def filter_sel_cb(e): '''Handle change of filter range.''' lowfq = e.geometry['x0'] highfq = e.geometry['x1'] sgselbox.bottom = lowfq sgselbox.top = highfq spselbox.left = lowfq spselbox.right = highfq range_text = f' ({lowfq:.0f}-{highfq:.0f} Hz)' # Force assignment of new options so that Bokeh detects the values have changed # and synchronizes the JS. options = filter_sel.options.copy() for idx, opt in enumerate(options): if 'stopband' in opt: options[idx] = f'stopband {range_text}' if 'stopband' in filter_sel.value: filter_sel.value = options[idx] if 'passband' in opt: options[idx] = f'passband {range_text}' if 'passband' in filter_sel.value: filter_sel.value = options[idx] filter_sel.options = options update_snd() update_sgram() update_spslice(t=cursor.location) def filter_type_cb(attr, old, new): '''Handle change in filter type.''' if 'clear' in new: # Force assignment of new options so that Bokeh detects the values have changed # and synchronizes the JS. options = filter_sel.options.copy() for idx, opt in enumerate(options): if 'passband' in opt: options[idx] = 'passband' if 'passband' in filter_sel.value: filter_sel.value = 'passband' if 'stopband' in opt: options[idx] = 'stopband' if 'stopband' in filter_sel.value: filter_sel.value = 'stopband' filter_sel.options = options update_snd() update_sgram() update_spslice(t=cursor.location) manifest_text = requests.get(resource_url + manifest_name).text manifest = yaml.safe_load(manifest_text)[manifest_key] options = [('', 'Choose an audio file to display')] + [ (resource_url + opt['fname'], opt['label']) for opt in manifest ] fselect = Select(options=options, value='') fselect.on_change('value', load_wav_cb) file_input = FileInput(accept=".wav") fselect_row = row(fselect, file_input) file_input.on_change('value', file_input_cb) source = ColumnDataSource(data=dict(seconds=[], ch0=[])) channels = ['ch0'] playvisbtn = AudioButton(label='Play visible signal', source=source, channels=channels, width=120, visible=False) playselbtn = AudioButton(label='Play selected signal', source=source, channels=channels, width=120, visible=False) # Instantiate and share specific select/zoom tools so that # highlighting is synchronized on all plots. boxsel = BoxSelectTool(dimensions='width') spboxsel = BoxSelectTool(dimensions='width') boxzoom = BoxZoomTool(dimensions='width') zoomin = ZoomInTool(dimensions='width') zoomout = ZoomOutTool(dimensions='width') crosshair = CrosshairTool(dimensions='height') shared_tools = [ 'xpan', boxzoom, boxsel, crosshair, 'undo', 'redo', zoomin, zoomout, 'reset' ] figargs = dict(tools=shared_tools, ) cursor = Span(dimension='height', line_color='red', line_dash='dashed', line_width=1) ch0 = figure(name='ch0', tooltips=[("time", "$x{0.0000}")], **figargs) ch0.line(x='seconds', y='ch0', source=source, nonselection_line_alpha=0.6) # Link pan, zoom events for plots with x_range. ch0.x_range.on_change('start', x_range_cb) ch0.x_range.on_change('end', x_range_cb) ch0.on_event(SelectionGeometry, selection_cb) ch0.on_event(Tap, cursor_cb) ch0.add_layout(cursor) low_thresh = 0.0 sgrams = [np.ones((1, 1))] specsource = ColumnDataSource(data=dict(sgram0=[sgrams[0]])) fq_marker_source = ColumnDataSource( data=dict(freq=[0.0], power=[0.0], time=[0.0])) spec0 = figure( name='spec0', x_range=ch0.x_range, # Keep times synchronized tooltips=[("time", "$x{0.0000}"), ("freq", "$y{0.0000}"), ("value", "@sgram0{0.000000}")], **figargs) spec0.add_layout(cursor) spec0_fq_marker = spec0.circle(x='time', y='freq', source=fq_marker_source, size=6, line_color='red', fill_color='red', visible=False) spec0.x_range.range_padding = spec0.y_range.range_padding = 0 spec0cmap = LogColorMapper(palette=r_Greys256, low_color=params['low_thresh_color']) low_thresh_slider = Slider(start=1.0, end=12.0, step=0.125, value=params['low_thresh_power'], title='Low threshold') winsize_slider = Slider(start=5.0, end=40.0, step=5.0, value=params['window_size'], title='Analysis window (ms)') filter_sel = Select( options=['no filter (clear)', 'no filter', 'passband', 'stopband'], value='no filter (clear)') spec0img = spec0.image(image='sgram0', x=0, y=0, color_mapper=spec0cmap, level='image', source=specsource) spec0.grid.grid_line_width = 0.0 low_thresh_slider.on_change('value', low_thresh_cb) winsize_slider.on_change('value', winsize_cb) filter_sel.on_change('value', filter_type_cb) selbox = BoxAnnotation(name='selbox', left=None, right=None, fill_color='green', fill_alpha=0.1, line_color='green', line_width=1.5, line_dash='dashed', visible=False) sgselbox = BoxAnnotation(name='sgselbox', top=None, bottom=None, fill_color='red', fill_alpha=0.1, line_color='red', line_width=1.5, line_dash='dashed', visible=False) ch0.add_layout(selbox) spec0.add_layout(selbox) spec0.add_layout(sgselbox) spec0.on_event(SelectionGeometry, selection_cb) spec0.on_event(Tap, cursor_cb) grid = gridplot([ch0, spec0], ncols=1, plot_height=200, toolbar_location='left', toolbar_options={'logo': None}, merge_tools=True) spslice_chtool = CrosshairTool(dimensions='height') spslice0 = figure(name='spslice0', plot_width=400, plot_height=250, y_axis_type='log', y_range=(10**-9, 1), tools=[spboxsel, spslice_chtool], toolbar_location='left') spslice0.toolbar.logo = None spslice_source = ColumnDataSource( data=dict(freq=np.array([]), power=np.array([]))) spslice0.line(x='freq', y='power', source=spslice_source) spselbox = BoxAnnotation(name='spselbox', left=None, right=None, fill_color='red', fill_alpha=0.1, line_color='red', line_width=1.5, line_dash='dashed', visible=False) spslice0.add_layout(spselbox) spslice0.on_event(SelectionGeometry, filter_sel_cb) thresh_box = BoxAnnotation(fill_color=params['low_thresh_color']) spslice0.add_layout(thresh_box) spslice0.on_event(MouseMove, spslice_move_cb) spslice0_fq_marker = spslice0.circle(x='freq', y='power', source=fq_marker_source, size=6, line_color='red', fill_color='red', visible=False) num_fmtr = NumberFormatter(format='0.0000') det_num_fmtr = NumberFormatter(format='0.000000000') fq_marker_table = DataTable(source=fq_marker_source, columns=[ TableColumn(field="freq", title="Frequency", formatter=num_fmtr), TableColumn(field="power", title="Power", formatter=det_num_fmtr), TableColumn(field="time", title="Time", formatter=num_fmtr), ], width=300) control_col = column(row(playvisbtn, playselbtn), low_thresh_slider, winsize_slider, filter_sel, fq_marker_table) grid2 = gridplot([spslice0, control_col], ncols=2) mainLayout = column( fselect_row, grid, #low_thresh_slider, winsize_slider, grid2, name='mainLayout') doc.add_root(mainLayout) return doc
def draw(S, position=None, with_labels=False): """Plot the given signed social network. Args: S: The network position (dict, optional): The position for the nodes. If no position is provided, a layout will be calculated. If the nodes have 'color' attributes, a Kamanda-Kawai layout will be used to group nodes of the same color together. Otherwise, a circular layout will be used. Returns: A dictionary of positions keyed by node. Examples: >>> import dwave_structural_imbalance_demo as sbdemo >>> gssn = sbdemo.GlobalSignedSocialNetwork() >>> nld_before = gssn.get_node_link_data('Syria', 2013) >>> nld_after = gssn.solve_structural_imbalance('Syria', 2013) # draw Global graph before solving; save node layout for reuse >>> position = sbdemo.draw('syria.png', nld_before) # draw the Global graph; reusing the above layout, and calculating a new grouped layout >>> sbdemo.draw('syria_imbalance.png', nld_after, position) >>> sbdemo.draw('syria_imbalance_grouped', nld_after) """ # we need a consistent ordering of the edges edgelist = S.edges() nodelist = S.nodes() def layout_wrapper(S): pos = position if pos is None: try: # group bipartition if nodes are colored dist = defaultdict(dict) for u, v in product(nodelist, repeat=2): if u == v: # node has no distance from itself dist[u][v] = 0 elif nodelist[u]['color'] == nodelist[v]['color']: # make same color nodes closer together dist[u][v] = 1 else: # make different color nodes further apart dist[u][v] = 2 pos = nx.kamada_kawai_layout(S, dist) except KeyError: # default to circular layout if nodes aren't colored pos = nx.circular_layout(S) return pos # call layout wrapper once with all nodes to store position for calls with partial graph position = layout_wrapper(S) plot = Plot(plot_width=600, plot_height=400, x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2)) tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool()] plot.add_tools(*tools) plot.toolbar.active_scroll = tools[0] def get_graph_renderer(S, line_dash): # we need a consistent ordering of the edges edgelist = S.edges() nodelist = S.nodes() # get the colors assigned to each edge based on friendly/hostile sign_edge_color = ['#87DACD' if S[u][v]['sign'] == 1 else '#FC9291' for u, v in edgelist] # get the colors assigned to each node by coloring try: coloring_node_color = ['#4378F8' if nodelist[v]['color'] else '#FFE897' for v in nodelist] except KeyError: coloring_node_color = ['#FFFFFF' for __ in nodelist] graph_renderer = from_networkx(S, layout_wrapper) circle_size = 10 graph_renderer.node_renderer.data_source.add(coloring_node_color, 'color') graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color='color') edge_size = 2 graph_renderer.edge_renderer.data_source.add(sign_edge_color, 'color') try: graph_renderer.edge_renderer.data_source.add([S[u][v]['event_year'] for u, v in edgelist], 'event_year') graph_renderer.edge_renderer.data_source.add( [S[u][v]['event_description'] for u, v in edgelist], 'event_description') plot.add_tools(HoverTool(tooltips=[("Year", "@event_year"), ("Description", "@event_description")], line_policy="interp")) except KeyError: pass graph_renderer.edge_renderer.glyph = MultiLine(line_color='color', line_dash=line_dash) graph_renderer.inspection_policy = EdgesAndLinkedNodes() return graph_renderer try: S_dash = S.edge_subgraph(((u, v) for u, v in edgelist if S[u][v]['frustrated'])) S_solid = S.edge_subgraph(((u, v) for u, v in edgelist if not S[u][v]['frustrated'])) plot.renderers.append(get_graph_renderer(S_dash, 'dashed')) plot.renderers.append(get_graph_renderer(S_solid, 'solid')) except KeyError: plot.renderers.append(get_graph_renderer(S, 'solid')) plot.background_fill_color = "#202239" positions = layout_wrapper(S) if with_labels: data = { 'xpos': [], 'ypos': [], 'label': [] } for label, pos in positions.items(): data['label'].append(label) data['xpos'].append(pos[0]) data['ypos'].append(pos[1]) labels = LabelSet(x='xpos', y='ypos', text='label', level='glyph', source=ColumnDataSource(data), x_offset=-5, y_offset=10, text_color="#F5F7FB", text_font_size='12pt') plot.add_layout(labels) show(Row(plot)) return positions
def _make_plot(): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(ZoomOutTool()) code = RECORD("xrstart", "p.x_range.start") + RECORD("xrend", "p.x_range.end") + RECORD("yrstart", "p.y_range.start") + RECORD("yrend", "p.y_range.end") plot.add_tools(CustomAction(callback=CustomJS(args=dict(p=plot), code=code))) plot.toolbar_sticky = False return plot