Python bokeh.models.HoverTool() Examples
The following are 28
code examples of bokeh.models.HoverTool().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bokeh.models
, or try the search function
.
Example #1
Source File: temperature.py From bigquery-bokeh-dashboard with Apache License 2.0 | 7 votes |
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)
Example #2
Source File: air.py From bigquery-bokeh-dashboard with Apache License 2.0 | 6 votes |
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]
Example #3
Source File: precipitation.py From bigquery-bokeh-dashboard with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: plotting.py From REDPy with GNU General Public License v3.0 | 6 votes |
def createHoverTool(): """ Helper function to create family hover preview """ hover = HoverTool( tooltips=""" <div> <div> <img src="./clusters/@famnum.png" style="height: 100px; width: 500px; vertical-align: middle;" /> <span style="font-size: 9px; font-family: Helvetica;">Cluster ID: </span> <span style="font-size: 12px; font-family: Helvetica;">@famnum</span> </div> </div> """, names=["patch"]) return hover
Example #5
Source File: viz2.py From scipy2015-blaze-bokeh with MIT License | 6 votes |
def timeseries(): # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] df['moving_average'] = pd.rolling_mean(df['anomaly'], 12) df = df.fillna(0) # List all the tools that you want in your plot separated by comas, all in one string. TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" # New figure t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS) # Data processing # The hover tools doesn't render datetime appropriately. We'll need a string. # We just want dates, remove time f = lambda x: str(x)[:7] df["datetime_s"]=df[["datetime"]].applymap(f) source = ColumnDataSource(df) # Create plot t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source) t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva") # Style xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"])) t.xaxis[0].formatter = xformatter t.xaxis.major_label_orientation = math.pi/4 t.yaxis.axis_label = 'Anomaly(ºC)' t.legend.orientation = "bottom_right" t.grid.grid_line_alpha=0.2 t.toolbar_location=None # Style hover tool hover = t.select(dict(type=HoverTool)) hover.tooltips = """ <div> <span style="font-size: 15px;">Anomaly</span> <span style="font-size: 17px; color: red;">@anomaly</span> </div> <div> <span style="font-size: 15px;">Month</span> <span style="font-size: 10px; color: grey;">@datetime_s</span> </div> """ hover.renderers = t.select("mva") # Show plot #show(t) return t # Add title
Example #6
Source File: code.py From Code-Sleep-Python with MIT License | 6 votes |
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)
Example #7
Source File: viz.py From scipy2015-blaze-bokeh with MIT License | 5 votes |
def timeseries(): # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] df['moving_average'] = pd.rolling_mean(df['anomaly'], 12) df = df.fillna(0) # List all the tools that you want in your plot separated by comas, all in one string. TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" # New figure t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS) # Data processing # The hover tools doesn't render datetime appropriately. We'll need a string. # We just want dates, remove time f = lambda x: str(x)[:7] df["datetime_s"]=df[["datetime"]].applymap(f) source = ColumnDataSource(df) # Create plot t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source) t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva") # Style xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"])) t.xaxis[0].formatter = xformatter t.xaxis.major_label_orientation = math.pi/4 t.yaxis.axis_label = 'Anomaly(ºC)' t.legend.orientation = "bottom_right" t.grid.grid_line_alpha=0.2 t.toolbar_location=None # Style hover tool hover = t.select(dict(type=HoverTool)) hover.tooltips = """ <div> <span style="font-size: 15px;">Anomaly</span> <span style="font-size: 17px; color: red;">@anomaly</span> </div> <div> <span style="font-size: 15px;">Month</span> <span style="font-size: 10px; color: grey;">@datetime_s</span> </div> """ hover.renderers = t.select("mva") # Show plot #show(t) return t
Example #8
Source File: testoverlayplot.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_hover_tool_instance_renderer_association(self): tooltips = [("index", "$index")] hover = HoverTool(tooltips=tooltips) opts = dict(tools=[hover]) overlay = Curve(np.random.rand(10,2)).opts(plot=opts) * Points(np.random.rand(10,2)) plot = bokeh_renderer.get_plot(overlay) curve_plot = plot.subplots[('Curve', 'I')] self.assertEqual(len(curve_plot.handles['hover'].renderers), 1) self.assertIn(curve_plot.handles['glyph_renderer'], curve_plot.handles['hover'].renderers) self.assertEqual(plot.handles['hover'].tooltips, tooltips)
Example #9
Source File: harvest.py From memex-explorer with BSD 2-Clause "Simplified" License | 5 votes |
def create(self): self.source = self.update_source() p = figure(plot_width=400, plot_height=400, title="Harvest Plot", x_axis_type='datetime', tools='pan, wheel_zoom, box_zoom, reset, resize, save, hover') p.line(x="timestamp", y="relevant_pages", color=GREEN, line_width=0.2, legend="relevant", source=self.source) p.scatter(x="timestamp", y="relevant_pages", fill_alpha=0.6, color=GREEN, source=self.source) p.line(x="timestamp", y="downloaded_pages", color=DARK_GRAY, line_width=0.2, legend="downloaded", source=self.source) p.scatter(x="timestamp", y="downloaded_pages", fill_alpha=0.6, color=DARK_GRAY, source=self.source) hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("harvest_rate", "@harvest_rate"), ]) p.legend.orientation = "top_left" script, div = components(p) return (script, div)
Example #10
Source File: figureenvelope.py From backtrader_plotting with GNU General Public License v3.0 | 5 votes |
def __init__(self, strategy: bt.Strategy, cds: ColumnDataSource, hoverc: HoverContainer, start, end, scheme, master, plotorder, is_multidata): self._strategy = strategy self._cds: ColumnDataSource = cds self._scheme = scheme self._start = start self._end = end self.figure: figure = None self._hover_line_set = False self._hover: Optional[HoverTool] = None self._hoverc = hoverc self._coloridx = collections.defaultdict(lambda: -1) self.master = master self.plottab = None self.plotorder = plotorder self.datas = [] # list of all datas that have been plotted to this figure self._is_multidata = is_multidata self._tradingdomain = None self._init_figure()
Example #11
Source File: figureenvelope.py From backtrader_plotting with GNU General Public License v3.0 | 5 votes |
def apply_hovertips(self, figures: List['FigureEnvelope']) -> None: """Add hovers to to all figures from the figures list""" for f in figures: for t in f.figure.tools: if not isinstance(t, HoverTool): continue self._apply_to_figure(f, t) break
Example #12
Source File: testheatmapplot.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_heatmap_custom_string_tooltip_hover(self): tooltips = "<div><h1>Test</h1></div>" custom_hover = HoverTool(tooltips=tooltips) hm = HeatMap([(1,1,1), (2,2,0)], kdims=['x with space', 'y with $pecial symbol']) hm = hm.options(tools=[custom_hover]) plot = bokeh_renderer.get_plot(hm) hover = plot.handles['hover'] self.assertEqual(hover.tooltips, tooltips) self.assertEqual(hover.renderers, [plot.handles['glyph_renderer']])
Example #13
Source File: recipe_clustering.py From Flavor-Network with GNU General Public License v3.0 | 5 votes |
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)
Example #14
Source File: unemployment_example.py From spyre with MIT License | 5 votes |
def getHTML(self, params): state = params['state'] if state == 'all': data = self.data else: data = self.data[self.data['state'] == state] TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,previewsave" try: fig = plotting.patches( data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, tools=TOOLS, line_color="white", line_width=0.5, title=state.upper() + " Unemployment 2009" ) except Exception: fig = plotting.figure(title=state.upper() + " Unemployment 2009", tools=TOOLS) fig.patches( data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, line_color="white", line_width=0.5 ) hover = fig.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("index", "$index") ]) script, div = components(fig, CDN) html = "%s\n%s" % (script, div) return html
Example #15
Source File: comparison_plot.py From estimagic with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _add_hover_tool(plot, point_glyph, df): top_cols = ["model", "name", "value"] optional_cols = ["model_class", "conf_int_lower", "conf_int_upper"] for col in optional_cols: if len(df[col].unique()) > 1: top_cols.append(col) tooltips = [(col, "@" + col) for col in top_cols] hover = HoverTool(renderers=[point_glyph], tooltips=tooltips) plot.tools.append(hover)
Example #16
Source File: layout.py From pairstrade-fyp-2019 with MIT License | 4 votes |
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
Example #17
Source File: bokeh_jobs_viz.py From rvt_model_services with MIT License | 4 votes |
def update_graph(jobs_db, graph_path): rows = [] for job in jobs_db.all(): rows.append([job.get("<project_code>"), job.get("<command>"), job.get(">start_time"), job.get("timeout")]) df = pd.DataFrame(rows, columns=["project", "command", "start", "timeout"]) df = df.sort_values(by="project", ascending=False) df["start"] = pd.to_datetime(df["start"], format="%H:%M:%S") df["start_txt"] = df.start.astype("str").str.extract(r"(\d+:\d+)", expand=True) + " h" df["timeout_txt"] = df['timeout'].copy().astype('str') + " seconds" df["timeout"] = df['timeout'].astype('timedelta64[s]') df["end"] = pd.to_datetime(df["start"], format="%H:%M:%S") + df["timeout"] colors = viridis(len(df["project"])) output_file(graph_path, title="rvt_model_services_jobs", mode="inline") cds = ColumnDataSource(data=dict(start=df["start"].values, end=df["end"].values, name=df["project"], timeout=df["timeout_txt"], start_txt=df["start_txt"], command=df["command"], color=colors, ) ) hover = HoverTool(tooltips=[("project", "@name"), ("command", "@command"), ("start time:", "@start_txt"), ("timeout:", "@timeout"), ]) tools_opt = [hover, "save", "pan", "wheel_zoom", "box_zoom", "reset"] graph_opt = dict(width=900, x_axis_type="datetime", tools=tools_opt, toolbar_location="right", background_fill_alpha=0, border_fill_alpha=0) jobs_viz = figure(title="rvt_model_service_jobs", y_range=list(df["project"].unique()), **graph_opt) jobs_viz.hbar(source=cds, y="name", left="start", right="end", height=1, color="color", ) style_plot(jobs_viz) save(jobs_viz)
Example #18
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 4 votes |
def interactiveG(G): from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider from bokeh.plotting import figure, output_file, show, ColumnDataSource from bokeh.io import output_notebook, show output_notebook() # We could use figure here but don't want all the axes and titles #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) output_file("PHMI_network") source=ColumnDataSource(data=dict( x=locations[0].tolist(), #x=[idx for idx in range(len(PHMIList))], #y=locations[1].tolist(), y=PHMIList, #desc=[str(i) for i in PHMIList], #PHMI_value=PHMI_dic[0][0].tolist(), )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), #("desc", "@desc"), #("PHMI", "$PHMI_value"), ] plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network") #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()} graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0)) #plot.renderers.append(graph) fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position) graph.layout_provider = fixed_layout_provider plot.renderers.append(graph) # Blue circles for nodes, and light grey lines for edges graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba') graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2) # green hover for both nodes and edges graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4') graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4) # When we hover over nodes, highlight adjecent edges too graph.inspection_policy = NodesAndLinkedEdges() plot.add_tools(HoverTool(tooltips=None)) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(plot) #06-single landmarks pattern 无人车位置点与对应landmarks栅格图 #convert location and corresponding landmarks to raster data format using numpy.histogram2d
Example #19
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def interactiveG(G): from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider from bokeh.plotting import figure, output_file, show, ColumnDataSource from bokeh.io import output_notebook, show output_notebook() # We could use figure here but don't want all the axes and titles #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) output_file("PHMI_network") source=ColumnDataSource(data=dict( x=locations[0].tolist(), #x=[idx for idx in range(len(PHMIList))], #y=locations[1].tolist(), y=PHMIList, #desc=[str(i) for i in PHMIList], #PHMI_value=PHMI_dic[0][0].tolist(), )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), #("desc", "@desc"), #("PHMI", "$PHMI_value"), ] plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network") #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()} graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0)) #plot.renderers.append(graph) fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position) graph.layout_provider = fixed_layout_provider plot.renderers.append(graph) # Blue circles for nodes, and light grey lines for edges graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba') graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2) # green hover for both nodes and edges graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4') graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4) # When we hover over nodes, highlight adjecent edges too graph.inspection_policy = NodesAndLinkedEdges() plot.add_tools(HoverTool(tooltips=None)) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(plot) #05-single landmarks pattern 无人车位置点与对应landmarks栅格图 #convert location and corresponding landmarks to raster data format using numpy.histogram2d
Example #20
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def interactiveG(G): from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider from bokeh.plotting import figure, output_file, show, ColumnDataSource from bokeh.io import output_notebook, show output_notebook() # We could use figure here but don't want all the axes and titles #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) output_file("PHMI_network") source=ColumnDataSource(data=dict( x=locations[0].tolist(), #x=[idx for idx in range(len(PHMIList))], #y=locations[1].tolist(), y=PHMIList, #desc=[str(i) for i in PHMIList], #PHMI_value=PHMI_dic[0][0].tolist(), )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), #("desc", "@desc"), #("PHMI", "$PHMI_value"), ] plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network") #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()} graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0)) #plot.renderers.append(graph) fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position) graph.layout_provider = fixed_layout_provider plot.renderers.append(graph) # Blue circles for nodes, and light grey lines for edges graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba') graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2) # green hover for both nodes and edges graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4') graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4) # When we hover over nodes, highlight adjecent edges too graph.inspection_policy = NodesAndLinkedEdges() plot.add_tools(HoverTool(tooltips=None)) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(plot) #05-single landmarks pattern 无人车位置点与对应landmarks栅格图 #convert location and corresponding landmarks to raster data format using numpy.histogram2d
Example #21
Source File: visualisation.py From knmt with GNU General Public License v3.0 | 4 votes |
def make_alignment_figure(src, tgt, alignment, title="Attention Model", toolbar_location='right', plot_width=800, plot_height=800): alignment = alignment[:, ::-1] # tgt = list(reversed(tgt)) src = ["%i %s" % (num, x) for num, x in enumerate(src)] tgt = ["%s %i" % (x, num) for num, x in reversed(list(enumerate(tgt)))] xname = [] yname = [] color = [] alpha = [] count = [] for i, n1 in enumerate(src): for j, n2 in enumerate(tgt): xname.append(n1) yname.append(n2) alpha.append(alignment[i, j]) color.append('black') count.append(alignment[i, j]) # for x, y, a in zip(xname, yname, alpha): # print(x, y, a) source = ColumnDataSource( data=dict( xname=xname, yname=yname, colors=color, alphas=alpha, count=count, ) ) # create a new figure p = figure(title=title, x_axis_location="above", tools="hover", toolbar_location=toolbar_location, x_range=src, y_range=tgt, plot_width=plot_width, plot_height=plot_height) p.rect('xname', 'yname', 0.9, 0.9, source=source, color='colors', alpha='alphas', line_color=None) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "10pt" p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = np.pi / 3 hover = p.select(dict(type=HoverTool)) hover.tooltips = [ ('tgt/src', '@yname, @xname'), ('attn', '@count'), ] return p
Example #22
Source File: bokeh_qc_graphs.py From rvt_model_services with MIT License | 4 votes |
def graph(_csv, _project_code, graph_topics): figures = [] graph_x_range = None for topic in graph_topics.keys(): # data source csv_topic = _csv.copy().filter(regex=topic) csv_topic["timeStamp"] = _csv.timeStamp.copy() csv_topic.set_index('timeStamp', inplace=True) csv_topic.index = pd.to_datetime(csv_topic.index) csv_topic.sort_index(inplace=True) df_columns_count = csv_topic.shape[1] df_rows_count = csv_topic.shape[0] colors = viridis(df_columns_count) topic_title = f"{_project_code} - RVT - {graph_topics[topic]}" # print(topic_title) # print(csv_topic.head()) line_opt = dict(line_width=3, alpha=0.8) hover = HoverTool(tooltips=[("name", "@name"), ("time", "@time"), ("count", "@count"), ] ) tools_opt = [hover, "save", "pan", "wheel_zoom", "reset"] graph_opt = dict(width=900, x_axis_type="datetime", toolbar_location="left", tools=tools_opt, toolbar_sticky=False, background_fill_alpha=0, border_fill_alpha=0) if graph_x_range: topic_figure = figure(title=topic_title, x_range=graph_x_range, **graph_opt) else: topic_figure = figure(title=topic_title, **graph_opt) graph_x_range = topic_figure.x_range # glyphs # print(len(cds.column_names)) for i, col_name in enumerate(csv_topic.columns): if topic in col_name: # print(col_name) csv_topic["color"] = colors[i] name_list = [col_name[2:] for i in range(df_rows_count)] cds = ColumnDataSource(data=dict(x=csv_topic.index.values, y=csv_topic[col_name].values, name=name_list, count=csv_topic[col_name].values, time=csv_topic.index.strftime("%Y-%m-%d %H:%M:%S"), ) ) topic_figure.line("x", "y", color=colors[i], name="name", source=cds, legend=col_name[2:], **line_opt ) figures.append(style_plot(topic_figure)) return figures
Example #23
Source File: bokeh_qc_graphs.py From rvt_model_services with MIT License | 4 votes |
def graph(_csv, _project_code, graph_topics): figures = [] graph_x_range = None for topic in graph_topics.keys(): # data source csv_topic = _csv.copy().filter(regex=topic) csv_topic["timeStamp"] = _csv.timeStamp.copy() csv_topic.set_index('timeStamp', inplace=True) csv_topic.index = pd.to_datetime(csv_topic.index) csv_topic.sort_index(inplace=True) df_columns_count = csv_topic.shape[1] df_rows_count = csv_topic.shape[0] colors = viridis(df_columns_count) topic_title = f"{_project_code} - RVT - {graph_topics[topic]}" # print(topic_title) # print(csv_topic.head()) line_opt = dict(line_width=3, alpha=0.8) hover = HoverTool(tooltips=[("name", "@name"), ("time", "@time"), ("count", "@count"), ] ) tools_opt = [hover, "save", "pan", "wheel_zoom", "reset"] graph_opt = dict(width=900, x_axis_type="datetime", toolbar_location="left", tools=tools_opt, toolbar_sticky=False, background_fill_alpha=0, border_fill_alpha=0) if graph_x_range: topic_figure = figure(title=topic_title, x_range=graph_x_range, **graph_opt) else: topic_figure = figure(title=topic_title, **graph_opt) graph_x_range = topic_figure.x_range # glyphs # print(len(cds.column_names)) for i, col_name in enumerate(csv_topic.columns): if topic in col_name: # print(col_name) csv_topic["color"] = colors[i] name_list = [col_name[2:] for i in range(df_rows_count)] cds = ColumnDataSource(data=dict(x=csv_topic.index.values, y=csv_topic[col_name].values, name=name_list, count=csv_topic[col_name].values, time=csv_topic.index.strftime("%Y-%m-%d %H:%M:%S"), ) ) topic_figure.line("x", "y", color=colors[i], name="name", source=cds, legend=col_name[2:], **line_opt ) figures.append(style_plot(topic_figure)) return figures
Example #24
Source File: viz2.py From scipy2015-blaze-bokeh with MIT License | 4 votes |
def timeseries(): # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] df['moving_average'] = pd.rolling_mean(df['anomaly'], 12) df = df.fillna(0) # List all the tools that you want in your plot separated by comas, all in one string. TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" # New figure t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS) # Data processing # The hover tools doesn't render datetime appropriately. We'll need a string. # We just want dates, remove time f = lambda x: str(x)[:7] df["datetime_s"]=df[["datetime"]].applymap(f) source = ColumnDataSource(df) # Create plot t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source) t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva") # Style xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"])) t.xaxis[0].formatter = xformatter t.xaxis.major_label_orientation = math.pi/4 t.yaxis.axis_label = 'Anomaly(ºC)' t.legend.orientation = "bottom_right" t.grid.grid_line_alpha=0.2 t.toolbar_location=None # Style hover tool hover = t.select(dict(type=HoverTool)) hover.tooltips = """ <div> <span style="font-size: 15px;">Anomaly</span> <span style="font-size: 17px; color: red;">@anomaly</span> </div> <div> <span style="font-size: 15px;">Month</span> <span style="font-size: 10px; color: grey;">@datetime_s</span> </div> """ hover.renderers = t.select("mva") # Show plot #show(t) return t # Add title
Example #25
Source File: visualize_utils.py From embedding with MIT License | 4 votes |
def visualize_self_attention_scores(tokens, scores, filename="/notebooks/embedding/self-attention.png", use_notebook=False): mean_prob = np.mean(scores) weighted_edges = [] for idx_1, token_prob_dist_1 in enumerate(scores): for idx_2, el in enumerate(token_prob_dist_1): if idx_1 == idx_2 or el < mean_prob: weighted_edges.append((tokens[idx_1], tokens[idx_2], 0)) else: weighted_edges.append((tokens[idx_1], tokens[idx_2], el)) max_prob = np.max([el[2] for el in weighted_edges]) weighted_edges = [(el[0], el[1], (el[2] - mean_prob) / (max_prob - mean_prob)) for el in weighted_edges] G = nx.Graph() G.add_nodes_from([el for el in tokens]) G.add_weighted_edges_from(weighted_edges) plot = Plot(plot_width=500, plot_height=500, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool()) graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.data_source.data['colors'] = Spectral8[:len(tokens)] graph_renderer.node_renderer.glyph = Circle(size=15, line_color=None, fill_color="colors") graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="colors") graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="grey") graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a, b)['weight'] * 3 for a, b in G.edges()] graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_width={'field': 'line_width'}) graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="grey", line_width=5) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="grey", line_width=5) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = EdgesAndLinkedNodes() plot.renderers.append(graph_renderer) x, y = zip(*graph_renderer.layout_provider.graph_layout.values()) data = {'x': list(x), 'y': list(y), 'connectionNames': tokens} source = ColumnDataSource(data) labels = LabelSet(x='x', y='y', text='connectionNames', source=source, text_align='center') plot.renderers.append(labels) plot.add_tools(SaveTool()) if use_notebook: output_notebook() show(plot) else: export_png(plot, filename) print("save @ " + filename)
Example #26
Source File: monitoring_app.py From estimagic with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _plot_time_series(data, y_keys, x_name, title, y_names=None): """Plot time series linking the *y_keys* to a common *x_name* variable. Args: data (ColumnDataSource): data that contain the y_keys and x_name y_keys (list): list of the entries in the data that are to be plotted. x_name (str): name of the entry in the data that will be on the x axis. title (str): title of the plot. y_names (list): if given these replace the y keys for the names of the lines. Returns: plot (bokeh Figure) """ if y_names is None: y_names = y_keys plot = create_standard_figure(title=title) colors = get_color_palette(nr_colors=len(y_keys)) for color, y_key, y_name in zip(colors, y_keys, y_names): line_glyph = plot.line( source=data, x=x_name, y=y_key, line_width=2, legend_label=y_name, color=color, muted_color=color, muted_alpha=0.2, ) tooltips = [(x_name, "@" + x_name)] tooltips += [("param_name", y_name), ("param_value", "@" + y_key)] hover = HoverTool(renderers=[line_glyph], tooltips=tooltips) plot.tools.append(hover) if len(y_key) == 1: plot.legend.visible = False else: plot.legend.click_policy = "mute" plot.legend.location = "top_left" return plot
Example #27
Source File: main.py From EARS with MIT License | 4 votes |
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
Example #28
Source File: main.py From EARS with MIT License | 4 votes |
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