我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用bokeh.models.HoverTool()。
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure( x_axis_type="datetime", plot_width=400, plot_height=300, tools='', toolbar_location=None) vbar = self.plot.vbar( x='date', top='prcp', width=1, color='#fdae61', source=self.source) hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[vbar]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure( x_axis_type="datetime", plot_width=600, plot_height=300, tools='', toolbar_location=None) self.plot.quad( top='max_temp', bottom='min_temp', left='left', right='right', color=Blues4[2], source=self.source, legend='Magnitude') line = self.plot.line( x='date', y='avg_temp', line_width=3, color=Blues4[1], source=self.source, legend='Average') hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[line]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) palette = all_palettes['Set2'][6] hover_tool = HoverTool(tooltips=[ ("Value", "$y"), ("Year", "@year"), ]) self.plot = figure( plot_width=600, plot_height=300, tools=[hover_tool], toolbar_location=None) columns = { 'pm10': 'PM10 Mass (µg/m³)', 'pm25_frm': 'PM2.5 FRM (µg/m³)', 'pm25_nonfrm': 'PM2.5 non FRM (µg/m³)', 'lead': 'Lead (¹/??? µg/m³)', } for i, (code, label) in enumerate(columns.items()): self.plot.line( x='year', y=code, source=self.source, line_width=3, line_alpha=0.6, line_color=palette[i], legend=label) self.title = Paragraph(text=TITLE) return column(self.title, self.plot) # [END make_plot]
def get_states_plot(): source = AjaxDataSource( data={'STATE': [], 'STNAME': [], 'STUSAB': [], 'TOT_POP': [], 'TOT_MALE': [], 'TOT_FEMALE': []}, data_url='/api/states/', mode='replace', method='GET') hover = HoverTool( tooltips=[ ("State", "@STNAME"), ("Population", "@TOT_POP"), ("Female Population", "@TOT_FEMALE"), ("Male Population", "@TOT_MALE"), ] ) plot = figure(title='Population by State', plot_width=1200, plot_height=500, x_range=FactorRange(factors=get_state_abbreviations()), y_range=(0, 40000000), tools=[hover, 'tap','box_zoom','wheel_zoom','save','reset']) plot.toolbar.active_tap = 'auto' plot.xaxis.axis_label = 'State' plot.yaxis.axis_label = 'Population' plot.yaxis.formatter = NumeralTickFormatter(format="0a") plot.sizing_mode = 'scale_width' plot.vbar(bottom=0, top='TOT_POP', x='STUSAB', legend=None, width=0.5, source=source) url = "/counties/@STATE/" taptool = plot.select(type=TapTool) taptool.callback = OpenURL(url=url) return plot
def bokeh_scatter_plot(tsne_df): output_file("results\\Anime_similarity.html") # Prep plot plot_anime_sim = bp.figure(plot_width=700, plot_height=600, title="Anime Similarity plotted with tSNE", tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave,tap", x_axis_type=None, y_axis_type=None, toolbar_location="below", toolbar_sticky=False) # Plotting the anime data plot_anime_sim.scatter(x='x', y='y', source=tsne_df) # Handle hover tools hover = plot_anime_sim.select(dict(type=HoverTool)) hover.tooltips={"Anime":"@anime_name [@rating]"} # Add ability to click links: url = "http://www.myanimelist.net/anime/@anime_id" taptool = plot_anime_sim.select(type=TapTool) taptool.callback = OpenURL(url=url) # Show the file: show(plot_anime_sim) script, div = components(plot_anime_sim) with open("results\\sim_script.js", "w") as text_file: text_file.write(script[37:-10]) with open("results\\sim_html.html", "w") as text_file: text_file.write(div) #%% Main code:
def location_plot(title, colors): output_file(title+".html") location_source = ColumnDataSource( data={ "x": whisky[" Latitude"], "y": whisky[" Longitude"], "colors": colors, "regions": whisky.Region, "distilleries": whisky.Distillery } ) fig = figure(title = title, x_axis_location = "above", tools="resize, hover, save") fig.plot_width = 400 fig.plot_height = 500 fig.circle("x", "y", 10, 10, size=9, source=location_source, color='colors', line_color = None) fig.xaxis.major_label_orientation = np.pi / 3 hover = fig.select(dict(type = HoverTool)) hover.tooltips = { "Distillery": "@distilleries", "Location": "(@x, @y)" } show(fig)
def location_plot(title, colors): output_file(title + ".html") location_source = ColumnDataSource( data={ "x": whisky[" Latitude"], "y": whisky[" Longitude"], "colors": colors, "regions": whisky.Region, "distilleries": whisky.Distillery } ) fig = figure(title=title, x_axis_location="above", tools="resize, hover, save") fig.plot_width = 400 fig.plot_height = 500 fig.circle("x", "y", 10, 10, size=9, source=location_source, color='colors', line_color=None) fig.xaxis.major_label_orientation = np.pi / 3 hover = fig.select(dict(type=HoverTool)) hover.tooltips = { "Distillery": "@distilleries", "Location": "(@x, @y)" } show(fig)
def plot_bokeh(df,sublist,filename): lenlist=[0] df_sub = df[df['cuisine']==sublist[0]] lenlist.append(df_sub.shape[0]) for cuisine in sublist[1:]: temp = df[df['cuisine']==cuisine] df_sub = pd.concat([df_sub, temp],axis=0,ignore_index=True) lenlist.append(df_sub.shape[0]) df_X = df_sub.drop(['cuisine','recipeName'],axis=1) print df_X.shape, lenlist dist = squareform(pdist(df_X, metric='cosine')) tsne = TSNE(metric='precomputed').fit_transform(dist) #cannot use seaborn palette for bokeh palette =['red','green','blue','yellow'] colors =[] for i in range(len(sublist)): for j in range(lenlist[i+1]-lenlist[i]): colors.append(palette[i]) #plot with boken output_file(filename) source = ColumnDataSource( data=dict(x=tsne[:,0],y=tsne[:,1], cuisine = df_sub['cuisine'], recipe = df_sub['recipeName'])) hover = HoverTool(tooltips=[ ("cuisine", "@cuisine"), ("recipe", "@recipe")]) p = figure(plot_width=1000, plot_height=1000, tools=[hover], title="flavor clustering") p.circle('x', 'y', size=10, source=source,fill_color=colors) show(p)
def _draw_contigCirclePlot(self): hover = HoverTool(tooltips=[('Length', '@contigs')]) hover.point_policy = "follow_mouse" plot = figure(x_axis_type=None, y_axis_type=None, tools=[hover], title='Contig lengths') plot.annular_wedge(x=0, y=0, inner_radius=0.5, outer_radius=0.7, start_angle='start', end_angle='stop', color='colors', alpha=0.9, source=self.contig_dist_src) plot.yaxis.axis_label_text_font_size = '14pt' plot.xaxis.axis_label_text_font_size = '14pt' plot.yaxis.major_label_text_font_size = '14pt' plot.xaxis.major_label_text_font_size = '14pt' plot.title.text_font_size = '16pt' return plot
def plot_Trun(self): star = self.star inst_date = self.inst_date data = self.selected_df idx = data.groupby(['T']).apply(lambda x: x['ccf_max'].idxmax()) highest = data.ix[idx].copy() source = ColumnDataSource(data=highest) self.current_source = source p = figure( title="{} - {}".format(star, inst_date), plot_width=800, plot_height=400, tools="pan,wheel_zoom,tap,hover,reset", title_text_font_size="20pt", ) p.circle("T", "ccf_max", size=10, nonselection_alpha=0.6, source=source ) p.xaxis[0].axis_label = 'Temperature (K)' p.yaxis[0].axis_label = 'CCF Peak Value' hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Temperature", "@T"), ("vsini", "@vsini"), ("[Fe/H]", "@feh"), ("log(g)", "@logg"), ("Radial Velocity (km/s)", "@vel_max"), ("ccf peak height", "@ccf_max"), ]) return p, highest
def scatterplot_vis(df, **kwargs): plot_width = kwargs.get('plot_width',300) plot_height = kwargs.get('plot_height',300) size = kwargs.get('size',10) hover = HoverTool( tooltips=""" <div> <div> <img src="@img_filepath" height="200" alt="@img_filepath" width="200" style="float: left; margin: 0px 15px 15px 0px;" border="2" ></img> </div> </div> """ ) p = figure(plot_width=plot_width, plot_height=plot_height, toolbar_location = 'right', tools='pan,box_zoom,wheel_zoom,reset,resize') p.add_tools(hover) df['label_color'] = df['label'].apply(lambda x: COLOR_PALETTE.as_hex()[int(x)]) source = ColumnDataSource(df) circles = p.circle('x', 'y', size=size, source=source) circles.glyph.fill_color = 'label_color' output_notebook() show(p)
def scatterplot_text(df, **kwargs): plot_width = kwargs.get('plot_width',300) plot_height = kwargs.get('plot_height',300) size = kwargs.get('size',10) hover = HoverTool( tooltips=""" <div> <div> <p> @text </p> </div> </div> """ ) p = figure(plot_width=plot_width, plot_height=plot_height, toolbar_location = 'right', tools='pan,box_zoom,wheel_zoom,reset,resize') p.add_tools(hover) df['label_color'] = df['label'].apply(lambda x: COLOR_PALETTE.as_hex()[int(x)]) source = ColumnDataSource(df) circles = p.circle('x', 'y', size=size, source=source) circles.glyph.fill_color = 'label_color' output_notebook() show(p)
def _add_hover(p): p.select_one(HoverTool).tooltips = [ ('names', '@yname, @xname'), ('weight', '@weight'), ] return p
def make_plot(results, title, xlabel, ylabel, baseline, ycolname, yaxis_format): p = plotting.figure(plot_width=WIDTH, plot_height=250, title=title, x_axis_label=xlabel, y_axis_label=ylabel, toolbar_location="above", tools='box_zoom,reset') legend_items = [] baseline_times = [t * 1e6 for t in results[baseline]['times']] for i, (impl_name, impl_data) in enumerate(results.items()): color = IMPL_COLORS[i % len(IMPL_COLORS)] style = IMPL_STYLES[i % len(IMPL_STYLES)] data = dict(x=impl_data['x']) # convert to microseconds data['times'] = [t * 1e6 for t in impl_data['times']] data['name'] = [impl_name] * len(data['x']) data['speedup'] = [b/t for (t,b) in zip(data['times'], baseline_times)] # not this is items/sec data['throughput'] = [items/t for (t, items) in zip(impl_data['times'], impl_data['x'])] source = plotting.ColumnDataSource(data=data) line = p.line('x', ycolname, source=source, line_width=2, line_color=color, line_dash=style) marker = p.circle('x', ycolname, source=source, size=10, fill_color=color) legend_items.append( (impl_name, [line, marker]) ) hover = HoverTool( tooltips=[ ('implementation', '@name'), ('x', '@x{%1.0e}'), ('time per call', '@times{%1.1e} usec'), ('speedup', '@{speedup}{%1.1f}x'), ('throughput', '@{throughput}{%1.1e}'), ], formatters={ 'x': 'printf', 'times': 'printf', 'speedup': 'printf', 'throughput': 'printf', } ) p.add_tools(hover) p.xaxis[0].formatter = PrintfTickFormatter(format='%1.0e') p.yaxis[0].formatter = PrintfTickFormatter(format=yaxis_format) legend = Legend(items=legend_items, location=(0, -30)) p.add_layout(legend, 'right') return p
def map(h2, show=True, cmap="gray", cmap_reverse=True, **kwargs): """Heat map.""" density = kwargs.pop("density", False) data = get_data(h2, density=density) show_colorbar = kwargs.pop("show_colorbar", True) X, Y = np.meshgrid(h2.get_bin_centers(0), h2.get_bin_centers(1)) dX, dY = np.meshgrid(h2.get_bin_widths(0), h2.get_bin_widths(1)) source = ColumnDataSource({ "frequency": data.T.flatten(), "x": X.flatten(), "y": Y.flatten(), "width": dX.flatten(), "height": dY.flatten() }) import bokeh.palettes if cmap in named_palettes: palette_generator = getattr(bokeh.palettes, cmap) palette = palette_generator(256) elif cmap in bokeh.palettes.all_palettes: palette = bokeh.palettes.all_palettes[cmap] else: raise RuntimeError("Unknown palette") if cmap_reverse: palette = palette[::-1] mapper = LinearColorMapper(palette=palette, low=data.min(), high=data.max()) p = kwargs.pop("figure", _create_figure(h2)) p.rect(source=source, x="x", y="y", width="width", height="height", fill_color={"field" : "frequency", "transform" : mapper}, line_color="white") p.select_one(HoverTool).tooltips = [ ("frequency", "@frequency") ] if show_colorbar: from bokeh.models import ColorBar, BasicTicker color_bar = ColorBar(color_mapper=mapper, #, major_label_text_font_size="5pt", ticker=BasicTicker(desired_num_ticks=6), # formatter=PrintfTickFormatter(format="%d%%"), # label_standoff=6, border_line_color=None, location=(0, 0) ) p.add_layout(color_bar, 'right') if show: bokeh_show(p) return p
def create_figure(df,x,y,discrete,quantileable,continuous,size,color,controls): xs = df[x.value].values ys = df[y.value].values # x_title = x.value.title() # y_title = y.value.title() x_title = "Marginal Effective Tax Rate" y_title = "Asset Category" source = ColumnDataSource(ColumnDataSource.from_df(df)) kw = dict() if x.value in discrete: kw['x_range'] = sorted(set(xs)) if y.value in discrete: kw['y_range'] = sorted(set(ys)) # kw['title'] = "%s vs %s" % (x_title, y_title) #kw['title'] = "Marginal Effective Tax Rates on Typically Financed Corporate Investments, 2016 Law" # kw['title'] = "Marginal Effective Tax Rates on Corporate Investments, 2016 Law" kw['title'] = "METRs on Corporate Investments, 2016 Law" p = figure(plot_height=400, plot_width=600, tools='pan,box_zoom,reset,hover', **kw) p.xaxis.axis_label = x_title p.yaxis.axis_label = y_title hover = p.select(dict(type=HoverTool)) hover.tooltips = [('Asset', '@Asset')] if x.value in discrete: p.xaxis.major_label_orientation = pd.np.pi / 4 sz = 9 if size.value != 'None': groups = pd.qcut(df[size.value].values, len(SIZES)) sz = [SIZES[xx] for xx in groups.codes] c = "#73000A" if color.value != 'None': groups = pd.qcut(df[color.value].values, len(COLORS)) c = [COLORS[xx] for xx in groups.codes] p.circle(x=xs, y=ys, source=source, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5) # p.title.text_color = "black" # p.title.text_font = "Georgia" return p
def scatter_with_hover(x, y, in_notebook=True, show_plt=True, fig=None, name=None, marker='o', fig_width=500, fig_height=500, x_label=None, y_label=None, title=None, color="blue"): """ Plots an interactive scatter plot of `x` vs `y` using bokeh, with automatic tooltips showing columns from `df`. Modified from: http://blog.rtwilson.com/bokeh-plots-with-dataframe-based-tooltips/ Args: x (numpy.ndarray): The data for the x-axis. y (numpy.ndarray): The data for the y-axis. fig (bokeh.plotting.Figure, optional): Figure on which to plot (if not given then a new figure will be created) name (str, optional): Series name to give to the scattered data marker (str, optional): Name of marker to use for scatter plot Returns: fig (bokeh.plotting.Figure): Figure (the same as given, or the newly created figure) if show is False """ # Make it so it works for ipython. if in_notebook: #pragma: no cover output_notebook() # insert the correct hover identifier. hover = HoverTool(tooltips=[("entry#", "@label"),]) # If we haven't been given a Figure obj then create it with default # size etc. if fig is None: # if title is None: # fig = figure(width=fig_width, height=fig_height, tools=['box_zoom', 'reset',hover]) # else: fig = figure(width=fig_width, height=fig_height, tools=['box_zoom', 'reset',hover],title=title) # We're getting data from the given dataframe source = ColumnDataSource(data=dict(x=x,y=y,label=range(1,len(x)+1))) # Actually do the scatter plot - the easy bit # (other keyword arguments will be passed to this function) fig.scatter('x', 'y', source=source, marker=marker,color=color,name=name) if x_label is not None: fig.xaxis.axis_label = x_label if y_label is not None: fig.yaxis.axis_label = y_label if show_plt: # pragma: no cover show(fig) else: return(fig)
def plot_detection_history(): # Rectangle grid with detection history cols = np.shape(audio.predictions)[1] plt = figure(plot_width=WIDTHS[0], plot_height=HEIGHTS[1], toolbar_location=None, tools="hover", x_range=[-cols, 0], y_range=labels[::-1]) plt.rect(x='x', y='y', width=0.95, height=0.8, color='color', source=HISTORY) # X ticks plt.xaxis[0].ticker = FixedTicker(ticks=np.arange(-cols, 1, 1).tolist()) plt.xaxis[0].formatter = FuncTickFormatter(code=""" return (tick * {} / 1000).toFixed(1) + " s" """.format(PREDICTION_STEP_IN_MS)) plt.xaxis.major_tick_line_color = GRID_COLOR plt.xaxis.major_label_text_font_size = '7pt' plt.xaxis.major_label_text_font = TEXT_FONT plt.xaxis.major_label_text_color = TEXT_COLOR # X axis plt.xaxis.axis_line_color = None # Y ticks plt.yaxis.major_tick_line_color = None plt.yaxis.major_label_text_font_size = '7pt' plt.yaxis.major_label_text_font = TEXT_FONT plt.yaxis.major_label_text_color = TEXT_COLOR # Y axis plt.yaxis.axis_line_color = GRID_COLOR # Grid plt.ygrid.grid_line_color = None plt.xgrid.grid_line_color = None # Plot fill/border plt.background_fill_color = GRID_COLOR plt.outline_line_color = GRID_COLOR plt.min_border = 10 # Plot title plt.title.text = 'Detection history:' plt.title.align = 'left' plt.title.text_color = TEXT_COLOR plt.title.text_font = TEXT_FONT plt.title.text_font_size = '9pt' plt.title.text_font_style = 'normal' # Hover tools hover = plt.select(dict(type=HoverTool)) hover.tooltips = [ ("Event", "@label"), ('Probability', '@pretty_value'), ] return plt
def plot_detection_last(): # Horizontal bars with current probabilities plt = figure(plot_width=WIDTHS[1], plot_height=HEIGHTS[1], toolbar_location=None, tools='hover', x_range=[0., 1.], y_range=labels[::-1]) plt.hbar(y='pos', height=0.9, left=0, right='value', color='color', source=DETECTION, name='bars', line_color=None) # Threshold annotation plt.quad(left=-0.1, right='threshold', bottom=-0.1, top=len(labels) + 1, source=THRESHOLD, fill_color='#000000', fill_alpha=0.1, line_color='red', line_dash='dashed') # X ticks plt.xaxis[0].ticker = FixedTicker(ticks=[0, 1]) plt.xaxis.major_tick_line_color = GRID_COLOR plt.xaxis.major_label_text_font_size = '7pt' plt.xaxis.major_label_text_font = TEXT_FONT plt.xaxis.major_label_text_color = TEXT_COLOR # X axis plt.xaxis.axis_line_color = None # Y ticks plt.yaxis[0].ticker = FixedTicker(ticks=np.arange(1, len(labels) + 1, 1).tolist()) plt.yaxis.major_label_text_font_size = '0pt' plt.yaxis.major_tick_line_color = None # Y axis plt.yaxis.axis_line_color = GRID_COLOR # Grid plt.xgrid.grid_line_color = None plt.ygrid.grid_line_color = None # Band fill plt.hbar(y=np.arange(1, len(labels) + 1, 2), height=1., left=0, right=1., color='#000000', alpha=0.1, level='image', name='bands') # Plot fill/border plt.outline_line_color = GRID_COLOR plt.min_border = 10 # Plot title plt.title.text = 'Current frame:' plt.title.text_color = TEXT_COLOR plt.title.text_font = TEXT_FONT plt.title.text_font_size = '9pt' plt.title.text_font_style = 'normal' # Hover tools hover = plt.select(dict(type=HoverTool)) hover.names = ['bars'] hover.tooltips = [ ('Event', '@label'), ('Probability', '@pretty_value'), ] return plt