def stations_plot(self): """ Plot subway stations. .. warning:: This method requires a Google API Key """ plot = self.map_plot plot.title.text = 'New York City Subway Stations' subway_stations = bkm.sources.ColumnDataSource( data=(self.data.loc[:, ['name', 'latitude', 'longitude']].join( self.data.loc[:, 'entrance_type'].astype(str)).join( self.data.loc[:, 'exit_only'].astype(str).str.replace( 'nan', 'No')).drop_duplicates())) plot.add_glyph(subway_stations, self.map_glyph_subway) hover = bkm.HoverTool() hover.tooltips = [ ('Location', '@name'), ('Entrance Type', '@entrance_type'), ('Exit Only', '@exit_only'), ] plot.add_tools( hover, bkm.PanTool(), bkm.WheelZoomTool(), ) bkio.output_file('stations.html') bkio.show(plot)
def cv_curve_for_source(source): ordinal = True hover = bm.HoverTool() hover.tooltips = [("parameters", "@params")] fig = bp.figure(plot_width=900, plot_height=300, x_axis_type='linear' if ordinal else 'datetime', x_axis_label='iteration' if ordinal else 'time', y_axis_label='mean cv score', tools="pan,wheel_zoom,box_select,reset", logo=None) fig.grid.visible = False x_val = 'index' if ordinal else 'tstamp' fig.line(x_val, 'mean_test_score', source=source, line_width=1.5, line_join='round', alpha=0.5) fig.scatter(x_val, 'mean_test_score', source=source, size=3, alpha=0.5) fig.line(x_val, 'cummax_score', source=source, color='orange', line_width=1.5, line_join='round') fig.scatter(x_val, 'cummax_score', source=source, size=3, color='orange') return fig
def _create_sorted_plt(comptable_cds, n_comps, x_var, y_var, title=None, x_label=None, y_label=None): """ Create dynamic sorted plots Parameters ---------- comptable_ds: bokeh.models.ColumnDataSource Data structure containing a limited set of columns from the comp_table x_var: str Name of variable for the x-axis y_var: str Name of variable for the y-axis title: str Plot title x_label: str X-axis label y_label: str Y-axis label Returns ------- fig: bokeh.plotting.figure.Figure Bokeh plot of components ranked by a given feature """ hovertool = models.HoverTool( tooltips=[('Component ID', '@component'), ( 'Kappa', '@kappa{0.00}'), ('Rho', '@rho{0.00}'), ('Var. Expl.', '@varexp{0.00}%')]) fig = plotting.figure( plot_width=400, plot_height=400, tools=["tap,wheel_zoom,reset,pan,crosshair,save", hovertool], title=title) fig.line(x=np.arange(1, n_comps + 1), y=comptable_cds.data[y_var].sort_values(ascending=False).values, color='black') fig.circle(x_var, y_var, source=comptable_cds, size=5, color='color', alpha=0.7) fig.xaxis.axis_label = x_label fig.yaxis.axis_label = y_label fig.x_range = models.Range1d(-1, n_comps + 1) fig.toolbar.logo = None return fig
def draw_tsne(df, fp, alpha=0.69, width=1200, height=1000, show=True, title="Homer Embeddings"): """ draws an interactive plot for data points with auxilirary info on hover """ output_file(fp, title=title) src = bm.ColumnDataSource(df) y = df['y'] mapper = linear_cmap(field_name='y', palette=Category20_9, low=min(y), high=max(y)) fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height, title=title) fig.scatter('x', 'y', size=10, line_color=mapper, color=mapper, fill_alpha=alpha, source=src) fig.add_tools(bm.HoverTool(tooltips=[("token", "@word")])) pl.save(fig, title=title) if show: pl.show(fig)
def _create_kr_plt(comptable_cds): """ Create Dymamic Kappa/Rho Scatter Plot Parameters ---------- comptable_cds: bokeh.models.ColumnDataSource Data structure containing a limited set of columns from the comp_table Returns ------- fig: bokeh.plotting.figure.Figure Bokeh scatter plot of kappa vs. rho """ # Create Panel for the Kappa - Rho Scatter kr_hovertool = models.HoverTool(tooltips=[('Component ID', '@component'), ('Kappa', '@kappa{0.00}'), ('Rho', '@rho{0.00}'), ('Var. Expl.', '@varexp{0.00}%')]) fig = plotting.figure(plot_width=400, plot_height=400, tools=["tap,wheel_zoom,reset,pan,crosshair,save", kr_hovertool], title="Kappa / Rho Plot") diagonal = models.Slope(gradient=1, y_intercept=0, line_color='#D3D3D3') fig.add_layout(diagonal) fig.circle('kappa', 'rho', size='size', color='color', alpha=0.5, source=comptable_cds, legend_group='classif') fig.xaxis.axis_label = 'Kappa' fig.yaxis.axis_label = 'Rho' fig.toolbar.logo = None fig.legend.background_fill_alpha = 0.5 fig.legend.orientation = 'horizontal' fig.legend.location = 'bottom_right' return fig
def draw_main(bkplot, geo_df, y_var, y_type, geolabel, formatting): """ Adds choropleth based on specified y_var to an existing Bokeh plot. :param (Bokeh object) plot: pre-defined Bokeh figure :param (gpd.DataFrame) geo_df: merged geopandas DataFrame from merge_to_geodf() :param (str) y_var: column name of variable to plot :param (str) y_type: palette type: 'sequential', sequential_single', 'divergent', 'categorical' :param (str) geolabel: column name to use. default is county/state name from shapefile :param (dict) formatting: see DEFAULTFORMAT from params.py :return: None (adds to Bokeh object) """ geo_src = models.GeoJSONDataSource(geojson=geo_df.to_json()) cmap = make_color_mapper(geo_df[y_var], y_type, formatting) shapes = bkplot.patches('xs', 'ys', fill_color={ 'field': y_var, 'transform': cmap }, fill_alpha=formatting['fill_alpha'], line_color=formatting['line_color'], line_width=formatting['line_width'], source=geo_src) if y_type != 'categorical': cbar = make_color_bar(cmap, formatting) bkplot.add_layout(cbar) hover = models.HoverTool(renderers=[shapes]) hover_ylabel = y_var if formatting['hover_ylabel'] is None else formatting[ 'hover_ylabel'] hover.tooltips = [(formatting['hover_geolabel'], f'@{geolabel}'), (hover_ylabel, f'@{y_var}{formatting["tooltip_text"]}')] bkplot.add_tools(hover)
def draw_vectors(x, y, radius=10, alpha=0.25, color='blue', width=600, height=400, show=True, **kwargs): """ draws an interactive plot for data points with auxilirary info on hover """ if isinstance(color, str): color = [color] * len(x) data_source = bm.ColumnDataSource({ 'x': x, 'y': y, 'color': color, **kwargs }) fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height) fig.scatter('x', 'y', size=radius, color='color', alpha=alpha, source=data_source) fig.add_tools( bm.HoverTool(tooltips=[(key, "@" + key) for key in kwargs.keys()])) if show: pl.show(fig) return fig
def stations_locations_plot(self): """ Plot subway stations and interest locations. .. warning:: This method requires a Google API Key """ plot = self.map_plot plot.title.text = 'New York City Hospitals and Subway Stations' hospitals = bkm.sources.ColumnDataSource(self.hosp.hospitals) plot.add_glyph(hospitals, self.map_glyph_hospital) subway_stations = bkm.sources.ColumnDataSource(data=( self.data.loc[:, ['name', 'latitude', 'longitude']].drop_duplicates() )) plot.add_glyph(subway_stations, self.map_glyph_subway) hover = bkm.HoverTool() hover.tooltips = [ ('Location', '@name'), ] plot.add_tools( hover, bkm.PanTool(), bkm.WheelZoomTool(), ) bkio.output_file('stations_locations.html') bkio.show(plot)
def new_plot(self, title, units, *, line_width=None, precision=2): """ Creates a blank line plot for with timestamps on the x-axis and a line for each data series on the y-axis. """ plot = plotting.figure(title=title, tools=[]) self.active_plot = plot self.plots.append(plot) self.colors = list(colors) self.units = units self.line_width = line_width or self.line_width plot.plot_width = self.width plot.plot_height = self.height plot.x_range = self.x_range datetime_tick_formats = { key: ["%a %b %d %H:%M:%S"] for key in ("seconds", "minsec", "minutes", "hourmin", "hours", "days") } plot.xaxis.formatter = models.DatetimeTickFormatter(**datetime_tick_formats) # https://bokeh.pydata.org/en/latest/docs/reference/models/formatters.html # plot.yaxis.formatter = models.NumeralTickFormatter(format="0a") plot.yaxis.formatter = models.NumeralTickFormatter(format="0,0.00 a") # With default precision level 2 (decimal places) # The units_formats = "@y{0,0.00}" # and the value would look like 1,234,567.89 units_formats = f"@y{{0,0.{'0' * precision}}}" hover = models.HoverTool( # mode = vline would be nice to use, # but then separate hovers block each when lines are too close. # Would like a single hover box with time once, and a value per line # perhaps this will help acheive that: # https://stackoverflow.com/questions/29435200/bokeh-plotting-enable-tooltips-for-only-some-glyphs mode="mouse", # other optins: vline line_policy="nearest", # other optins: prev, next, nearest, interp, none tooltips=[ ("Name", "$name"), ("Time", "@x{%a %m/%d %H:%M:%S}"), (self.units, units_formats), ], formatters={"x": "datetime", "Time": "datetime", "@x": "datetime"}, ) plot.add_tools(hover) plot.add_tools(models.BoxZoomTool()) plot.add_tools(models.HelpTool()) plot.add_tools(models.PanTool()) plot.add_tools(models.WheelZoomTool(dimensions="width")) plot.toolbar.active_scroll = plot.select_one(models.WheelZoomTool) plot.add_tools(models.WheelZoomTool(dimensions="height")) plot.add_tools(models.UndoTool()) plot.add_tools(models.RedoTool()) plot.add_tools(models.ResetTool()) plot.add_tools(models.SaveTool())
def volcanoPlot(df, vertical_line_r=None, vertical_line_l=None, horizontal_line=None, plotWidth=1000, plotHeight=1000, x_label="x-label", y_label="y-label", title="Volcano plot of Proteins", outputFile=None): plot_width = plotWidth plot_height = plotHeight title = title source = bpl.ColumnDataSource.from_df(df) hover = bmo.HoverTool(tooltips=[ ("(log2fc,logFDR)", "(@log2fc, @logFDR)"), ('protein', '@protein'), ]) boxSelect = bmo.BoxSelectTool() p = bpl.figure(plot_width=plot_width, plot_height=plot_height, tools=[hover, boxSelect], title=title, x_axis_label=x_label, y_axis_label=y_label) # Vertical line if vertical_line_r != None: vline_r = bmo.Span(location=vertical_line_r, dimension='height', line_color='red', line_dash="dashed", line_width=1, line_alpha=0.8) p.renderers.extend([vline_r]) if vertical_line_l != None: vline_l = bmo.Span(location=vertical_line_l, dimension='height', line_color='red', line_dash="dashed", line_width=1, line_alpha=0.8) p.renderers.extend([vline_l]) # Horizontal line if horizontal_line != None: hline = bmo.Span(location=horizontal_line, dimension='width', line_color='red', line_dash="dashed", line_width=1, line_alpha=0.8) p.renderers.extend([hline]) p.scatter('log2fc', 'logFDR', source=source, color='color') if outputFile != None: bpl.output_file(outputFile) #bpl.show(p) bpl.save(p)
def imshow(im, im2=None, p1=None, p2=None): # Bokeh Plotting io.reset_output() io.output_file('bokeh plots.html', title='imshow') colorImage = (len(im.shape) == 3) if colorImage: h, w, _ = im.shape else: h, w = im.shape # Setup tools hoverImage = models.HoverTool(tooltips=[('index', '$index'), ('(x, y)', '($x{(1.11)}, $y{(1.11)})')], point_policy='follow_mouse') p = plotting.figure(x_range=(0, w), y_range=(h, 0), plot_width=round(800 * w / h), plot_height=800, x_axis_label='pixel (1 - ' + str(w) + ')', y_axis_label='pixel (1 - ' + str(h) + ')', title='image', tools='box_zoom,pan,save,reset,wheel_zoom,crosshair', active_scroll='wheel_zoom', active_inspect=None) # Plot image if colorImage: # RGB imc = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint32) * 255 imc[:, :, 0:3] = im img = np.empty((h, w), dtype=np.uint32) view = img.view(dtype=np.uint8).reshape((h, w, 4)) view[:, :, :] = np.flipud(np.asarray(imc)) p.image_rgba(image=[img], x=0, y=h, dw=w, dh=h) else: p.image(image=[np.flip(im, 0)], x=0, y=h, dw=w, dh=h, palette=palettes.Greys256) p.quad(top=[h], bottom=[0], left=[0], right=[w], alpha=0) # clear rectange hack for tooltip image x,y p.add_tools(hoverImage) # Show plot colors = bokeh_colors(3) if im2 is None: if p1 is not None: p.circle(p1[:, 0], p1[:, 1], color=colors[0], line_width=2) if p2 is not None: p.circle(p2[:, 0], p2[:, 1], color=colors[1], line_width=2) p.multi_line(np.concatenate((p1[:, 0, None], p2[:, 0, None]), 1).tolist(), np.concatenate((p1[:, 1, None], p2[:, 1, None]), 1).tolist(), color='white', alpha=.3, line_width=1) io.show(p) # open a browser else: h, w = im2.shape q = plotting.figure(x_range=(0, w), y_range=(h, 0), plot_width=round(600 * w / h), plot_height=600, x_axis_label='pixel (1 - ' + str(w) + ')', y_axis_label='pixel (1 - ' + str(h) + ')', title='image', tools='box_zoom,pan,save,reset,wheel_zoom,crosshair', active_scroll='wheel_zoom', active_inspect=None) q.add_tools(hoverImage) # Plot image q.image(image=[np.flip(im2, 0)], x=0, y=h, dw=w, dh=h, palette=palettes.Greys256) q.quad(top=[h], bottom=[0], left=[0], right=[w], alpha=0) # clear rectange hack for tooltip image x,y # Show plots io.show(column(p, q)) # open a browser
def get_map(self): import bokeh.plotting as bplt import bokeh.models as bm wheel_zoom = bm.WheelZoomTool() self.hover = bm.HoverTool(tooltips=[ ("Navn", "@kommuner"), #("(Long, Lat)", "($x, $y)"), ("Dato", "@kommuner_dates"), ("stemme pct", "@stemme_pct %"), ]) self.hover.point_policy = "follow_mouse" tools = [ bm.PanTool(), bm.BoxZoomTool(), wheel_zoom, bm.SaveTool(), bm.ResetTool(), bm.UndoTool(), bm.RedoTool(), bm.CrosshairTool(), self.hover ] fig = bplt.figure(title="Test", tools=tools, x_axis_location=None, y_axis_location=None, match_aspect=True) # Activate scrool fig.toolbar.active_scroll = wheel_zoom # Remove grid lines fig.grid.grid_line_color = None # Check if source exists if not hasattr(self, 'source'): self.make_map_source() # Make color mapper #from bokeh.palettes import Viridis6 as palette #from bokeh.palettes import Spectral11 as palette from bokeh.palettes import RdYlGn11 as palette palette.reverse() #color_mapper = bm.LogColorMapper(palette=palette, high=90., low=50.) color_mapper = bm.LinearColorMapper(palette=palette, high=90., low=50.) # Plot fig.patches(xs='x_lon', ys='y_lat', source=self.source, fill_color={ 'field': 'stemme_pct', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) return fig
def plot_bokeh(self, labels, output_file=None, node_size=4, node_color=None, edge_color=None, width=None, **kwargs): # Unfortunately, nodes in Bokeh have to be strings or ints plot_d = nx.relabel.relabel_nodes(self, labels) tooltips = [] for node, data in plot_d.nodes(data=True): for key in data: tooltips += [(key, f"@{key}")] break if node_color is None: node_color = {labels[node]: "green" if node in self.path else "lightgray" for node in self.nodes} nx.set_node_attributes(plot_d, node_color, "node_color") fill_color = "node_color" if edge_color is None: edge_color = {(labels[edge[0]], labels[edge[1]]): "limegreen" if edge in self.solution or edge[::-1] in self.solution else "gray" for edge in self.edges} nx.set_edge_attributes(plot_d, edge_color, "edge_color") line_color = "edge_color" if width is None: width = {(labels[edge[0]], labels[edge[1]]): 2 if edge in self.solution else 0.1 for edge in self.edges} nx.set_edge_attributes(plot_d, width, "edge_width") line_width = "edge_width" graph = bkplt.from_networkx(plot_d, nx.circular_layout) graph.node_renderer.glyph = mod.Circle(size=node_size, line_color=fill_color, fill_color=fill_color) graph.edge_renderer.glyph = mod.MultiLine(line_color=line_color, line_width=line_width) plot = mod.Plot() plot.renderers.append(graph) tooltips = [("Label", "@index")] + tooltips node_hover_tool = mod.HoverTool(tooltips=tooltips) plot.add_tools(node_hover_tool, mod.PanTool(), mod.BoxZoomTool(), mod.WheelZoomTool(), mod.SaveTool(), mod.ResetTool()) if output_file: bkplt.output_file(output_file) bkplt.show(plot)
def create_plot(self, counties): filename = self.create_filename() bp.output_file(filename, title=self.title) p = bp.figure(title=self.title, x_axis_type="datetime", width=1200, height=700) legend_items = [] for a, b in counties: if self.dublin == False and a == "Dublin": continue temp = b.copy() temp['StrDate'] = temp['TimeStamp'].apply( lambda x: x.strftime("%a, %b %d")) source = bp.ColumnDataSource(temp) leg = p.line("TimeStamp", self.metric, source=source, line_width=2, line_color=self.counties[a]['color'], line_dash=self.counties[a]['dash']) legend_items.append((a, [leg])) legend = bm.Legend(items=legend_items, location='top_right', orientation='vertical', border_line_color="black") p.add_layout(legend, 'right') p.legend.click_policy = "hide" p.legend.label_text_font_size = '12px' p.legend.label_text_font = 'Helvetica' p.legend.location = "top_left" p.legend.background_fill_color = 'slategray' p.legend.background_fill_alpha = 0.5 tools = bm.HoverTool( tooltips=[("Date", "@StrDate"), ( "County", "@CountyName"), ("Cases", "@ConfirmedCovidCases{0, 0}")]) p.add_tools(tools) p.title.text_font = "Helvetica" p.title.text_font_size = "18px" p.background_fill_color = 'slategray' p.background_fill_alpha = 0.5 p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"], days=["%b, %d"], hours=["%H:%M"]) bp.show(p)
def create_clusters_mean_plot(source: bm.ColumnDataSource, filter_source: dict = None) -> bm.Box: figure_opts = dict(plot_width=600, plot_height=620, title="Cluster mean trends (pchip spline)") hover_opts = dict(tooltips=[('Cluster', '@legend')], show_arrow=False, line_policy='next') line_opts = dict( legend_field='legend', line_color='color', line_width=5, line_alpha=0.4, hover_line_color='color', hover_line_alpha=1.0, ) p: bp.Figure = bp.figure(tools=[bm.HoverTool(**hover_opts), bm.TapTool()], **figure_opts) p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.axis.minor_tick_line_color = None # p.xaxis.ticker = list(range(1945, 1990)) p.y_range.start = 0 _ = p.multi_line(source=source, xs='xs', ys='ys', **line_opts) p.legend.location = "top_left" p.legend.click_policy = "hide" if filter_source is not None: callback: bm.CustomJS = _create_multiline_multiselect_callback(source) multi_select: bm.MultiSelect = bm.MultiSelect( title='Show/hide', options=filter_source['options'], value=filter_source['values'], size=min(len(filter_source['options']), 30), ) multi_select.js_on_change('value', callback) p: bm.Box = bokeh.layouts.row(p, multi_select) return p
def plot_energy_steps(dftopt_out): #pylint: disable=too-many-locals """Plot the total energy graph.""" units = 'eV' ha2u = {'eV': 27.211399} out_dict = dftopt_out.get_dict() tooltips = [("Step (total)", "@index"), ("Step (stage)", "@step"), ("Energy", "@energy eV/atom"), ("Energy (dispersion)", "@dispersion_energy_au Ha"), ("SCF converged", "@scf_converged"), ("Cell A", "@cell_a_angs Angs"), ("Cell Vol", "@cell_vol_angs3 Angs^3"), ("MAX Step", "@max_step_au Bohr"), ("Pressure", "@pressure_bar bar")] hover = bmd.HoverTool(tooltips=tooltips) TOOLS = ["pan", "wheel_zoom", "box_zoom", "reset", "save", hover] natoms = out_dict['natoms'] values = [x / natoms * ha2u[units] for x in out_dict['step_info']['energy_au']] values = [x - min(values) for x in values] data = bmd.ColumnDataSource(data=dict( index=range(len(values)), step=out_dict['step_info']['step'], energy=values, dispersion_energy_au=out_dict['step_info']['dispersion_energy_au'], scf_converged=out_dict['step_info']['scf_converged'], cell_a_angs=out_dict['step_info']['cell_a_angs'], cell_vol_angs3=out_dict['step_info']['cell_vol_angs3'], max_step_au=out_dict['step_info']['max_step_au'], pressure_bar=out_dict['step_info']['pressure_bar'], )) p = figure(tools=TOOLS, title='Energy profile of the DFT minimization', height=350, width=550) p.xgrid.grid_line_color = None p.xaxis.axis_label = 'Steps' p.yaxis.axis_label = 'Energy ({}/atom)'.format(units) # Colored background colors = ['red', 'orange', 'green', 'yellow', 'cyan', 'pink', 'palegreen'] start = 0 for i, steps in enumerate(out_dict['stage_info']['nsteps']): end = start + steps p.add_layout(bmd.BoxAnnotation(left=start, right=end, fill_alpha=0.2, fill_color=colors[i])) start = end # Trace line and markers p.line('index', 'energy', source=data, line_color='blue') p.circle('index', 'energy', source=data, line_color='blue', size=3) return p
def user_hist_monthly(data): ds = bplt.ColumnDataSource( data=dict(month=[datum.date_label for datum in data], count=[len(datum.df.UserId.unique()) for datum in data])) hover = bmodels.HoverTool(tooltips=[('month', '@month'), ('num users', '@count')]) fig = bplt.figure(plot_width=900, plot_height=600, x_range=ds.data['month'], x_axis_label='Month', y_axis_label='Number of Users', tools=[hover], title='Num Users vs Month') fig.vbar(x='month', top='count', bottom=0, width=0.5, source=ds) bplt.show(fig)
def visualize_clusters(peaklistpath, plotfilepath, title, x, y): """Visualize cluster in 2D space.""" TOOLS = "pan,box_zoom,box_select,resize,reset,wheel_zoom,save" bkp.output_file(plotfilepath) plot = bkp.figure(tools=TOOLS, title=title) plot.xaxis.axis_label, plot.yaxis.axis_label = "{}, ppm".format( x), "{}, ppm".format(y) for cluster, color in zip( grouping.DBSCAN.global_clusters[peaklistpath].values(), COLOR_HEX): x_coords = cluster.coordinates(x) y_coords = cluster.coordinates(y) assignments = cluster.assignments() source = bkp.ColumnDataSource( data=dict(x=x_coords, y=y_coords, assignment=assignments)) for point in cluster.members: if cluster.label == -1: g = bkm.CircleX(x='x', y='y', line_color='#6666ee', fill_color='black', fill_alpha=0.5, size=5) else: g = bkm.Circle(x='x', y='y', line_color='#6666ee', fill_color=color, fill_alpha=0.5, size=10) gr = plot.add_glyph(source_or_glyph=source, glyph=g) g_hover = bkm.HoverTool(renderers=[gr], tooltips=[('x', '@x'), ('y', '@y'), ('assignment', '@assignment')]) plot.add_tools(g_hover) plot.text(np.mean(x_coords), np.mean(y_coords), text=[cluster.label], text_color='black', text_align='center', text_font_size='10pt') # bkp.show(plot) bkp.save(plot)
def draw_basic_graph(title): plot = plt.figure(x_axis_type="linear", title=title) plot.title.text_font_size = "16px" plot.title.align = "center" plot.grid.grid_line_alpha = 0.3 plot.xaxis.axis_label = 'step' plot.yaxis.axis_label = title.lower() plot.legend.location = "top_left" hover = pltm.HoverTool(tooltips=[ ("value", "@y{1.1111}"), ("iteration", "@x{int}"), ], names=["discrete_loss"]) plot.add_tools(hover) return plot
def plot_parameters(parameters, **kwargs): """ Makes a simple plot of the given parameters """ xpar = parameters.get('xaxis', 'p') ypar = parameters.get('yaxis', 'e') data, parameters = get_data(parameters) statistics = get_parameter_statistics(data, parameters) #-- datasource for bokeh datasource = bpl.ColumnDataSource(data=data) tooltips = [('System', '@system')] + \ [(p, '@{} +- @e_{}'.format(p, p)) for p in parameters] hover = mpl.HoverTool(tooltips=tooltips) TOOLS = [ mpl.PanTool(), mpl.WheelZoomTool(), mpl.BoxZoomTool(), mpl.ResetTool(), hover ] fig = bpl.figure(plot_width=800, plot_height=600, toolbar_location='right', tools=TOOLS) fig.circle(xpar, ypar, source=datasource, size=5) # Make sure xpar is filled otherwise avoid plotting if xpar != '': plot_errorbars(fig, data[xpar], data[ypar], xerr=data['e_' + xpar], yerr=data['e_' + ypar]) fig.toolbar.logo = None fig.yaxis.axis_label = ypar fig.xaxis.axis_label = xpar fig.yaxis.axis_label_text_font_size = '10pt' fig.xaxis.axis_label_text_font_size = '10pt' fig.min_border = 5 return fig, statistics
def hospital_plot(self): """ Plot hospital locations. .. warning:: This method requires a Google API Key """ map_options = { 'lat': 40.70, 'lng': -73.92, 'map_type': 'roadmap', 'zoom': 10, } plot = bkm.GMapPlot( api_key=keys.GOOGLE_API_KEY, x_range=bkm.Range1d(), y_range=bkm.Range1d(), map_options=bkm.GMapOptions(**map_options), plot_width=400, plot_height=600, ) plot.title.text = 'New York City Hospitals' hospital = bkm.Circle( x='longitude', y='latitude', fill_alpha=0.8, fill_color='#cd5b1b', line_color=None, size=14, ) hospitals = bkm.sources.ColumnDataSource(self.hospitals) plot.add_glyph(hospitals, hospital) hover = bkm.HoverTool() hover.tooltips = [ ('Location', '@name'), ] plot.add_tools( hover, bkm.PanTool(), bkm.WheelZoomTool(), ) bkio.output_file('hospitals.html') bkio.show(plot)
def display_pca_scatterplot_interactive(model, words=None, sample=0, radius=10, alpha=0.25, color='blue', width=600, height=400, show=True): # https://github.com/yandexdataschool/nlp_course/blob/2019/week01_embeddings/seminar.ipynb """ draws an interactive plot for data points with auxilirary info on hover """ from sklearn.decomposition import PCA import numpy as np import bokeh.models as bm, bokeh.plotting as pl from bokeh.io import output_notebook output_notebook() words = _sample_words(model, words=words, sample=sample) kwargs = {'token': words} word_vectors = np.array([model[w] for w in words]) twodim = PCA().fit_transform(word_vectors)[:, :2] x, y = twodim[:, 0], twodim[:, 1] if isinstance(color, str): color = [color] * len(x) data_source = bm.ColumnDataSource({ 'x': x, 'y': y, 'color': color, **kwargs }) fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height) fig.scatter('x', 'y', size=radius, color='color', alpha=alpha, source=data_source) fig.add_tools( bm.HoverTool(tooltips=[(key, "@" + key) for key in kwargs.keys()])) if show: pl.show(fig) return fig
def main() -> None: """メイン処理 Note: from_networkx ではランダム値によりグラフ中のノード位置が決定する。 そのため、 numpy の random seed を固定することで、毎回同じ形のグラフが出力されるようにする。 """ # グラフデータ graph = nx.karate_club_graph() # エッジの色を設定 SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red" edge_attrs = {} for start_node, end_node, _ in graph.edges(data=True): edge_attrs[(start_node, end_node)] = ( SAME_CLUB_COLOR if graph.nodes[start_node]["club"] == graph.nodes[end_node]["club"] else DIFFERENT_CLUB_COLOR) nx.set_edge_attributes(graph, edge_attrs, "edge_color") # グラフ初期設定 p = bkplotting.figure( tools=("pan,box_zoom,lasso_select,box_select,poly_select" ",tap,wheel_zoom,reset,save,zoom_in"), title="Networkx Integration Demonstration", x_range=(-2.1, 2.1), y_range=(-2.1, 2.1), ) p.add_tools( bkmodels.HoverTool(tooltips=[("index", "@index"), ("club", "@club")])) np.random.seed(0) render = bkgraphs.from_networkx(graph, nx.spring_layout, scale=2, center=(0, 0)) render.node_renderer.glyph = bkmodels.Circle( size=15, fill_color=bkpalettes.Spectral4[0]) render.edge_renderer.glyph = bkmodels.MultiLine(line_color="edge_color", line_alpha=0.6, line_width=2) p.renderers.append(render) # レイアウト layout = bklayouts.layout([p], sizing_mode="stretch_both") bkio.curdoc().add_root(layout)
def create_plot(self, data): filename = self.create_filename() bp.output_file(filename, title=self.title) p = bp.figure(title=self.title, x_axis_type="datetime", width=1200, height=700) temp = data.copy() temp['StrDate'] = temp['TimeStamp'].apply( lambda x: x.strftime("%a, %b %d")) temp['Base'] = 0 source = bp.ColumnDataSource(temp) p.varea("TimeStamp", "Daily", "Base", source=source, fill_color="pink", fill_alpha=0.5, legend_label="Daily Cases") p.line("TimeStamp", "Average", source=source, line_width=3, line_color="crimson", legend_label="Average Daily Cases") tools = bm.HoverTool(tooltips=[("Date", "@StrDate"), ("Daily Cases", "@Daily{0, 0}"), ("Average Cases", "@Average{0, 0}")], mode="vline") p.add_tools(tools) p.legend.location = "top_left" p.legend.click_policy = "hide" p.title.text_font = "Helvetica" p.title.text_font_size = "18px" p.background_fill_color = 'slategray' # p.background_fill_alpha = 0.25 p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"], days=["%b, %d"], hours=["%H:%M"]) bp.show(p)
def _create_kr_plt(comptable_cds): """ Create Dymamic Kappa/Rho Scatter Plot Parameters ---------- comptable_cds: bokeh.models.ColumnDataSource Data structure containing a limited set of columns from the comp_table Returns ------- fig: bokeh.plotting.figure.Figure Bokeh scatter plot of kappa vs. rho """ # Create Panel for the Kappa - Rho Scatter kr_hovertool = models.HoverTool(tooltips=[ ("Component ID", "@component"), ("Kappa", "@kappa{0.00}"), ("Rho", "@rho{0.00}"), ("Var. Expl.", "@varexp{0.00}%"), ]) fig = plotting.figure( plot_width=400, plot_height=400, tools=["tap,wheel_zoom,reset,pan,crosshair,save", kr_hovertool], title="Kappa / Rho Plot", ) diagonal = models.Slope(gradient=1, y_intercept=0, line_color="#D3D3D3") fig.add_layout(diagonal) fig.circle( "kappa", "rho", size="size", color="color", alpha=0.5, source=comptable_cds, legend_group="classif", ) fig.xaxis.axis_label = "Kappa" fig.yaxis.axis_label = "Rho" fig.toolbar.logo = None fig.legend.background_fill_alpha = 0.5 fig.legend.orientation = "horizontal" fig.legend.location = "bottom_right" return fig
def build_spread_fig(data, action_df): palette = ["#053061", "#67001f"] LINE_WIDTH = 1.5 LINE_COLOR = palette[-1] TITLE = "RULE BASED SPREAD TRADING" HEIGHT = 250 WIDTH = 600 # ========== data ============= # # TODO: get action_source array # TODO: map actions to colours so can map to palette[i] dates = np.array(data['date'], dtype=np.datetime64) spread_source = ColumnDataSource(data=dict(date=dates, spread=data['spread'])) action_source = ColumnDataSource(action_df) # action_source['colors'] = [palette[i] x for x in action_source['actions']] # ========== figure INTERACTION properties ============= # TOOLS = "hover,pan,wheel_zoom,box_zoom,reset,save" spread_p = figure(tools=TOOLS, toolbar_location=None, plot_height=HEIGHT, plot_width=WIDTH, title=TITLE) # spread_p.background_fill_color = "#dddddd" spread_p.xaxis.axis_label = "Backtest Period" spread_p.yaxis.axis_label = "Spread" # spread_p.grid.grid_line_color = "white" # ========== plot data points ============= # # plot the POINT coords of the ACTIONS circles = spread_p.circle("date", "spread", size=12, source=action_source, fill_alpha=0.8) circles_hover = bkm.HoverTool(renderers=[circles], tooltips = [ ("Action", "@latest_trade_action"), ("Stock Bought", "@buy_stk"), ("Bought Amount", "@buy_amt"), ("Stock Sold", "@sell_stk"), ("Sold Amount", "@sell_amt") ]) spread_p.add_tools(circles_hover) # plot the spread over time spread_p.line('date', 'spread', source=spread_source, line_color = LINE_COLOR, line_width = LINE_WIDTH) spread_p.xaxis[0].formatter = DatetimeTickFormatter() return spread_p
def hoverPlot(DataFrame, ID, x, y, plotname='temp_intr_plot'): source = bp.ColumnDataSource(data=DataFrame) bp.output_file('{}.html'.format(plotname)) hover = bm.HoverTool() hover.tooltips = [ ( ID, '@{{{}}}'.format(ID) ), # this {{{ }}} shenanigans are to scape ( {{ ) a curly brace on either side (x, '@{{{}}}'.format(x)), (y, '@{{{}}}'.format(y)) ] fig = bp.figure( plot_width=800, plot_height=800, title=plotname, toolbar_location="right", toolbar_sticky=False, tools=[hover, bm.PanTool(), bm.WheelZoomTool(), bm.ResetTool()]) # scatter fig.circle(x, y, size=10, color='black', source=source) # trendline linfit = stats.linregress(DataFrame[x], DataFrame[y]) legend = 'slope: {} \n rvalue: {} \n pvalue {}'.format( linfit.slope, linfit.rvalue, linfit.pvalue) def linfunct(a): return a * linfit[0] + linfit[1] min = DataFrame[x].min() max = DataFrame[x].max() fig.line([min, max], [linfunct(min), linfunct(max)], color='red', legend=legend) # Formating fig.legend.location = 'top_left' fig.xaxis.axis_label = x fig.yaxis.axis_label = y bp.show(fig)
def get_hover(inp_x, inp_y, inp_clr): """Returns hover tool""" q_x = config.quantities[inp_x] q_y = config.quantities[inp_y] q_clr = config.quantities[inp_clr] xhover = (q_x["label"], "@x {}".format(q_x["unit"])) yhover = (q_y["label"], "@y {}".format(q_y["unit"])) if 'unit' not in list(q_clr.keys()): clr_val = "@color" else: clr_val = "@color {}".format(q_clr['unit']) tooltips = [ ("name", "@name"), xhover, yhover, (q_clr["label"], clr_val), ] return bmd.HoverTool(tooltips=tooltips)
def get_bokeh_plot(isotherm_dict, pressure_scale='linear'): """Plot isotherm using bokeh. :returns: bokeh Figure instance """ p = figure(tools=TOOLS, x_axis_type=pressure_scale) # pylint: disable=invalid-name pressures = [point['pressure'] for point in isotherm_dict['isotherm_data']] for i in range(len(isotherm_dict['adsorbates'])): adsorbate = isotherm_dict['adsorbates'][i] adsorption = [ point['species_data'][i]['adsorption'] for point in isotherm_dict['isotherm_data'] ] data = bmd.ColumnDataSource(data=dict(index=range(len(pressures)), pressure=pressures, adsorption=adsorption)) p.line( # pylint: disable=too-many-function-args 'pressure', 'adsorption', source=data, legend_label=adsorbate['name']) p.circle( # pylint: disable=too-many-function-args 'pressure', 'adsorption', source=data, legend_label=adsorbate['name']) # update labels p.xaxis.axis_label = 'Pressure [{}]'.format(isotherm_dict['pressureUnits']) p.yaxis.axis_label = 'Adsorption [{}]'.format( isotherm_dict['adsorptionUnits']) tooltips = [(p.xaxis.axis_label, '@pressure'), (p.yaxis.axis_label, '@adsorption')] hover = bmd.HoverTool(tooltips=tooltips) p.tools.pop() p.tools.append(hover) return p
def get_fig(self): import bokeh.plotting as bplt # Make tools wheel_zoom = bm.WheelZoomTool() self.hover = bm.HoverTool(tooltips=[ #("index", "$index"), ("(x,y)", "($x, $y)"), ("int", "@intensity"), ("VOL", "@VOL"), #("fill color", "$color[hex, swatch]:fill_color"), #("Color", "@line_color"), ]) tools = [bm.PanTool(), bm.BoxZoomTool(), wheel_zoom, bm.SaveTool(), bm.ResetTool(), bm.UndoTool(), bm.RedoTool(), bm.CrosshairTool(), self.hover] # Make figure if self.dic: self.fig = bplt.figure(plot_width=400,plot_height=400, x_range=(self.x0_ppm, self.x1_ppm), y_range=(self.y0_ppm, self.y1_ppm), tools=tools) else: self.fig = bplt.figure(plot_width=400,plot_height=400, tools=tools) # Activate scrool self.fig.toolbar.active_scroll = wheel_zoom # If not ColumnDataSource exists, then create if not self.ColumnDataSource: self.create_ColumnDataSource() # Create figure self.fig_multi = self.fig.multi_line(xs='xs', ys='ys', line_color='line_color', source=self.ColumnDataSource, legend="Contours") # Possible for text: angle, angle_units, js_event_callbacks, js_property_callbacks, name, # subscribed_events, tags, text, text_align, text_alpha, text_baseline, text_color, text_font, text_font_size, # text_font_style, x, x_offset, y or y_offset #fig.text(x='xt',y='yt',text='text', source=self.ColumnDataSourceText, # text_baseline='middle', text_align='center', text_font_size="10px", legend="Text") # Hide glyphs in Interactive Legends self.fig.legend.click_policy="hide" # "mute" # Set label if self.dic: self.fig.xaxis.axis_label = self.udic[1]['label'] + ' ppm' self.fig.yaxis.axis_label = self.udic[0]['label'] + ' ppm' return self.fig