def __init__(self, scheduler, width=600, **kwargs): with log_errors(): self.last = 0 self.scheduler = scheduler self.source = ColumnDataSource({'nprocessing': [1, 2], 'nprocessing-half': [0.5, 1], 'nprocessing-color': ['red', 'blue'], 'nbytes': [1, 2], 'nbytes-half': [0.5, 1], 'worker': ['a', 'b'], 'y': [1, 2], 'nbytes-color': ['blue', 'blue'], 'bokeh_address': ['', '']}) processing = figure(title='Tasks Processing', tools='resize', id='bk-nprocessing-plot', width=int(width / 2), **kwargs) processing.rect(source=self.source, x='nprocessing-half', y='y', width='nprocessing', height=1, color='nprocessing-color') processing.x_range.start = 0 nbytes = figure(title='Bytes stored', tools='resize', id='bk-nbytes-worker-plot', width=int(width / 2), **kwargs) nbytes.rect(source=self.source, x='nbytes-half', y='y', width='nbytes', height=1, color='nbytes-color') nbytes.xaxis[0].formatter = NumeralTickFormatter(format='0.0 b') nbytes.xaxis.major_label_orientation = -math.pi / 12 nbytes.x_range.start = 0 for fig in [processing, nbytes]: fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False tap = TapTool(callback=OpenURL(url='http://@bokeh_address/')) fig.add_tools(tap) fig.toolbar.logo = None fig.toolbar_location = None fig.yaxis.visible = False hover = HoverTool() hover.tooltips = "@worker : @nprocessing tasks. Click for worker page" hover.point_policy = 'follow_mouse' processing.add_tools(hover) hover = HoverTool() hover.tooltips = "@worker : @nbytes bytes. Click for worker page" hover.point_policy = 'follow_mouse' nbytes.add_tools(hover) self.processing_figure = processing self.nbytes_figure = nbytes processing.y_range = nbytes.y_range self.root = row(nbytes, processing, sizing_mode='scale_width')
def areaplot(p, source, data_cols, colormap, hovertool, xlabelname, x_axis_type, stacked, **kwargs): """Adds areaplot to figure p for each data_col.""" # Add element to start and end of each x and y column for vertical lines at # end of areaplots: for key in source.keys(): if key == "x": source[key] = [source[key][0]] + list( source[key]) + [source[key][-1]] else: source[key] = np.array([0] + list(source[key]) + [0]) N_source = len(source[key]) # Stack data if <stacked>=True: if stacked: baseline = np.zeros(N_source) for col in data_cols: source[col] = baseline + source[col] baseline = source[col] if "alpha" not in kwargs: kwargs["alpha"] = 1 elif "alpha" not in kwargs: kwargs["alpha"] = 0.5 # Add line (and optional scatter glyphs) to figure: for j, name, color in list(zip(range(len(data_cols)), data_cols, colormap))[::-1]: p.patch(x="x", y=str(name), legend=" " + str(name), source=source, color=color, **kwargs) glyph = p.line( x="x", y=str(name), legend=" " + str(name), source=source, color=color, alpha=0, ) if hovertool and int(len(data_cols) / 2) == j: my_hover = HoverTool(mode="vline", renderers=[glyph]) if x_axis_type == "datetime": my_hover.tooltips = [(xlabelname, "@x{%F}") ] + [(str(name), "@{%s}" % str(name)) for name in data_cols[::-1]] my_hover.formatters = {"x": "datetime"} else: my_hover.tooltips = [ (xlabelname, "@x"), (str(name), "@{%s}" % str(name)), ] p.add_tools(my_hover) return p
def pointplot(p, source, data_cols, colormap, hovertool, xlabelname, x_axis_type, **kwargs): """Adds pointplot to figure p for each data_col.""" N_cols = len(data_cols) # Define marker for pointplot: if "marker" in kwargs: markers = [kwargs["marker"]] * N_cols del kwargs["marker"] else: marker = [ "circle", "square", "triangle", "asterisk", "circle_x", "square_x", "inverted_triangle", "x", "circle_cross", "square_cross", "diamond", "cross", ] markers = marker * int(N_cols / 20 + 1) markers = markers[:N_cols] # Add scatter/point glyphs to figure: for name, color, marker in zip(data_cols, colormap, markers): glyph = p.scatter(x="x", y=str(name), legend=" " + str(name), source=source, color=color, marker=marker, **kwargs) if hovertool: my_hover = HoverTool(mode="vline", renderers=[glyph]) if x_axis_type == "datetime": my_hover.tooltips = [ (xlabelname, "@x{%F}"), (str(name), "@{%s}" % str(name)), ] my_hover.formatters = {"x": "datetime"} else: my_hover.tooltips = [ (xlabelname, "@x"), (str(name), "@{%s}" % str(name)), ] p.add_tools(my_hover) return p
def hover(tips): ''' Function to create a hoover inspector tool ''' tool = HoverTool() tool.tooltips = tips return tool
def tagsDistributionScatterPlot(NbTags, dates, plotname='Tags Distribution Plot'): output_file(plotname + ".html") counts = {} glyphs = {} desc = {} hover = HoverTool() plot = figure(plot_width=800, plot_height=800, x_axis_type="datetime", x_axis_label='Date', y_axis_label='Number of tags', tools=[hover]) for name in NbTags.keys(): desc[name] = [] for date in dates[name]: desc[name].append(date_tools.datetimeToString(date, "%Y-%m-%d")) counts[name] = plot.circle( dates[name], NbTags[name], legend="Number of events with y tags", source=ColumnDataSource(data=dict(desc=desc[name]))) glyphs[name] = counts[name].glyph glyphs[name].size = int(name) * 2 hover.tooltips = [("date", "@desc")] if int(name) != 0: glyphs[name].fill_alpha = 1 / int(name) show(plot)
def data_usage_plot(df): def create_data_source(df): return ColumnDataSource(data=dict(filesystem=df['filesystem'],total_size=df['total_size'],used=df['used'],available=df['available'],use_percent=df['use_percent'],mounted=['mounted'],submittime=[x.strftime("%Y-%m-%d") for x in df['submittime']])) hover = HoverTool(names=['points']) TOOLS = [BoxZoomTool(),PanTool(),ResetTool(),WheelZoomTool(),hover] Colors = ['red','navy','olive','firebrick','lightskyblue','yellowgreen','lightcoral','yellow', 'green','blue','gold'] # Change percents to format bokeh can use fp_list = [] for row in df['use_percent']: fp_list.append(float(row.replace('%',''))) df['f_percent'] = fp_list # Begin Plotting x_max = datetime.now() p = figure(height=500, width=1000, x_axis_type="datetime", x_range=((x_max-timedelta(14)),x_max), y_axis_label='Percent Full', tools=TOOLS, title='Data Usage by Filesystem') # Points with hover info p.scatter(x=df['submittime'], y=df['f_percent'], name='points', source=create_data_source(df), color='black', size=6) df = df.groupby(by = ['filesystem']) # Connecting lines count = 0 for filesystem, group in df: count += 1 p.line(x=group['submittime'] ,y=group['f_percent'], color=Colors[count], legend=str(filesystem), line_width=3) # Formating p.legend.orientation = "top_left" hover.point_policy = "follow_mouse" hover.tooltips = [("Filesystem", "@filesystem"),("Size","@total_size"),("Available","@available"),("Percent Used","@use_percent"),("Time","@submittime")] return p
def showViz(data, zip_code): """ data=pandas data frame for resturant zip_code=zip code where resturants are located """ data = data.fillna('') column_name='perZip'+'.'+str(zip_code) #print(column_name) cuisine=data['cuisine'].tolist() counts=list(data[column_name].values) # Needed for using bokeh source = ColumnDataSource(data=dict(cuisine=cuisine, count=counts)) p = figure(x_range=cuisine,plot_height=1000, plot_width=1000,toolbar_location=None, title="Resturant counts by cusine") renderers = p.vbar(x='cuisine', top='count', width=0.9, source=source, line_color='white', fill_color=factor_cmap('cuisine', palette=inferno(len(cuisine)), factors=cuisine)) p.xgrid.grid_line_color = None # p.xaxis.major_label_orientation = math.pi/4 p.xaxis.major_label_text_font_size = "8pt" p.xaxis.major_label_orientation = "vertical" # Implement interactivity my_hover = HoverTool() my_hover.tooltips = [('Cuisine','@cuisine'),('Number of Locations','@count')] p.add_tools(my_hover) return p
def vBarGraphic2(df, categoricalVariable, filterCategorical, filterCategoricalValue): dfCategory = df[df[filterCategorical] == filterCategoricalValue] typByCategoryDF = dfCategory.groupby( categoricalVariable)[categoricalVariable].value_counts().to_frame() typByCategoryDF['values'] = typByCategoryDF.index typByCategoryDF['values'] = [ i[0] for i in typByCategoryDF['values'].tolist() ] source = ColumnDataSource(typByCategoryDF) hover = HoverTool() hover.tooltips = """ <div> <h3>@values</h3> <div><strong>Value: </strong> @Type </div> </div> """ hover_tool = HoverTool(tooltips=[('Category', '@values'), ('Count', '@Type')]) p = figure(x_range=source.data['values'].tolist(), plot_height=300, title="Type of app", x_axis_label='Apps', y_axis_label='Number of apps') p.vbar(x='values', width=0.5, bottom=0, top='Type', source=source) p.add_tools(hover) return p
def vBarGraphic(df, categoricalVariable, filterCategorical, filterCategoricalValue, numericalVariable, numberToShow): df.dropna(subset=[numericalVariable], inplace=True) finalDf = df[df[filterCategorical] == filterCategoricalValue].sort_values( by=numericalVariable, ascending=False).head(numberToShow) source = ColumnDataSource(finalDf) hover = HoverTool() hover_tool = HoverTool(tooltips=[('Name', '@App'), ('Rating', '@Rating')]) hover.tooltips = """ <div> <h3>@App</h3> <div><strong>Value: </strong> @Rating </div> </div> """ p = figure(x_range=source.data['App'].tolist(), plot_height=300, title="Best 3 review apps", x_axis_label='Apps', y_axis_label='Reviews') p.vbar(x=categoricalVariable, width=0.5, bottom=0, top=numericalVariable, color="firebrick", source=source) p.add_tools(hover) return p
def nbytes_plot(**kwargs): data = {"name": [], "left": [], "right": [], "center": [], "color": [], "percent": [], "MB": [], "text": []} source = ColumnDataSource(data) fig = figure(title="Memory Use", tools="", toolbar_location=None, id="bk-nbytes-plot", **kwargs) fig.quad(source=source, top=1, bottom=0, left="left", right="right", color="color", alpha=1) fig.grid.grid_line_color = None fig.grid.grid_line_color = None fig.axis.visible = None fig.outline_line_color = None hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Percent:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">MB:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span> </div> """ hover.point_policy = "follow_mouse" return source, fig
def make_plot(src, p): journal = ["AA", "ASR", "JMAS"] palette = [cc.rainbow[i * 15] for i in range(17)] p.vbar(x='x', top='counts', width=0.9, source=src, fill_color=factor_cmap('x', palette=palette, factors=journal, start=1, end=2)) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None hover = HoverTool() hover.tooltips = [("count", "@counts")] hover.mode = 'vline' p.add_tools(hover) # Styling p = style(p) return p
def __init__(self, dataset): self._dataset = dataset hover_tool = HoverTool() hover_tool.tooltips = [("price", "@price")] self._fig = figure(title=dataset.title, tools=[hover_tool], name="plot") color_mapper = LinearColorMapper(palette=palette) self._fig.circle( "x", "y", source=dataset.source, fill_color={ "field": "price", "transform": color_mapper }, ) self._x_select = Select(title="X Axis:", value=dataset.x_feature, options=dataset.feature_names) self._y_select = Select(title="Y Axis:", value=dataset.y_feature, options=dataset.feature_names) self._x_select.on_change("value", self.update_data) self._y_select.on_change("value", self.update_data) self._inputs = column(self._x_select, self._y_select, sizing_mode="stretch_width", name="inputs")
def tagsDistributionScatterPlot(NbTags, dates, plotname='Tags Distribution Plot'): output_file(plotname + ".html") counts = {} glyphs = {} desc = {} hover = HoverTool() plot = figure(plot_width=800, plot_height=800, x_axis_type="datetime", x_axis_label='Date', y_axis_label='Number of tags', tools=[hover]) for name in NbTags.keys(): desc[name] = [] for date in dates[name]: desc[name].append(date_tools.datetimeToString(date, "%Y-%m-%d")) counts[name] = plot.circle(dates[name], NbTags[name], legend="Number of events with y tags", source=ColumnDataSource( data=dict( desc=desc[name] ) )) glyphs[name] = counts[name].glyph glyphs[name].size = int(name) * 2 hover.tooltips = [("date", "@desc")] if int(name) != 0: glyphs[name].fill_alpha = 1/int(name) show(plot)
def createMatrix(width, height, column_list_original, index_list_original, mapper, color_bar, source_normal): #Color mapper #Hover information hover = HoverTool() hover.tooltips = [ ("(Author1, Author2)", "(@AuthorX, @AuthorY)"), ("Similarity rate", "@sim"), ("Index", "@index") ] #Basic interaction tools TOOLS = "save,pan,box_zoom,reset,wheel_zoom" #Graph grid and properties figure_matrix = figure(plot_width = width, plot_height=height, x_range=column_list_original, y_range=index_list_original, #feeding columns and range toolbar_location="right", tools=TOOLS, x_axis_location="above") r = figure_matrix.rect(x='AuthorX', y='AuthorY', width=1, height=1, source=source_normal,#feeding x,y for each square line_color=None, fill_color=transform('sim', mapper)) figure_matrix.tools.append(hover) figure_matrix.add_layout(color_bar, 'right') figure_matrix.axis.axis_line_color = None figure_matrix.axis.major_tick_line_color = None figure_matrix.axis.major_label_text_font_size = "7pt" figure_matrix.axis.major_label_standoff = 0 figure_matrix.xaxis.major_label_orientation = np.pi/2 return figure_matrix
def plot_multiple_distributions( df: pd.DataFrame, title: str, column_bar_name: list, column_category_name: str, plot_width: int = 330, plot_height: int = 330, colours: list = ['#00BFA5', "#8c9eff", "#536dfe"], bins: int = 10): """ Creates figure with distribution as bar chart :param df: dataframe with data :param title: title for the graph :param column_bar_name: indicates the column needed to to create distribution figure :param is_categorical: indicates if plot uses categorical or numerical variables :param plot_width: figure's width (default = 330) :param plot_height: figure's height (default = 330) :param colour: fill colour for bar chart :param bins: number of bins :return: figure with bar chart distribution """ hover = HoverTool() p = figure(title=title, plot_width=plot_width, plot_height=plot_height, tools=["save", hover]) for ind, category_ in enumerate(sorted(df[column_category_name].unique())): temp_df = df[df[column_category_name] == category_] arr_hist, edges = np.histogram(temp_df[column_bar_name], bins=bins, range=[0, 1]) hist_df = pd.DataFrame({ 'dis': arr_hist, 'left': edges[:-1], 'right': edges[1:] }) source = ColumnDataSource(hist_df) p.quad(bottom=0, top='dis', left='left', right='right', fill_color=colours[ind], source=source, fill_alpha=0.6**ind, line_width=0, legend=column_category_name + ": " + str(category_)) p.title.text_font = p.xaxis.axis_label_text_font = p.yaxis.axis_label_text_font = "Helvetica Neue" p.xgrid.visible = p.ygrid.visible = False tooltips = [("dis", "@" + "dis" + '{0%}')] hover = p.select(dict(type=HoverTool)) hover.tooltips = tooltips return p
def __init__(self, scheduler, **kwargs): with log_errors(): self.scheduler = scheduler self.source = ColumnDataSource({ 'occupancy': [0, 0], 'worker': ['a', 'b'], 'x': [0.0, 0.1], 'y': [1, 2], 'ms': [1, 2] }) fig = figure(title='Occupancy', tools='resize', id='bk-occupancy-plot', x_axis_type='datetime', **kwargs) fig.rect(source=self.source, x='x', width='ms', y='y', height=1, color='blue') fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False # fig.xaxis[0].formatter = NumeralTickFormatter(format='0.0s') fig.x_range.start = 0 hover = HoverTool() hover.tooltips = "@worker : @occupancy s" hover.point_policy = 'follow_mouse' fig.add_tools(hover) self.root = fig
def create_line_chart(df, title, width=800, height=300): """ Create a line and circle chart with name of x axis, y axis and hover tool. """ # convert date object to string and factorize the month as x_axis lable df.date = df.date.apply(lambda x: datetime.datetime.strftime(x, '%Y-%m')) xdr = FactorRange(factors=df.date) source = ColumnDataSource(df) plot = figure(title=title, x_range=xdr, plot_width=800, plot_height=300) plot.line(x="date", y="salary", source=source, line_width=2) #plot.circle(x="date", y="salary", source=source, fill_color="white", size=8) plot.vbar(x="date", top="salary", source=source, width=0.5) plot.toolbar.logo = None plot.xaxis.axis_label = "月份" plot.yaxis.axis_label = "工资" hover = HoverTool() hover.tooltips = [ ('日期', '@date'), ('工资', '@salary{0.00}'), ] plot.add_tools(hover) return plot
def createBokehChart(self): keyFields = self.getKeyFields() valueFields = self.getValueFields() color = self.options.get("color") xlabel = keyFields[0] ylabel = valueFields[0] wpdf = self.getWorkingPandasDataFrame().copy() colors = self.colorPalette( None if color is None else len(wpdf[color].unique())) p = figure(y_axis_label=ylabel, x_axis_label=xlabel) for i, c in enumerate(list( wpdf[color].unique())) if color else enumerate([None]): wpdf2 = wpdf[wpdf[color] == c] if c else wpdf p.circle(list(wpdf2[xlabel]), list(wpdf2[ylabel]), color=colors[i], legend=str(c) if c and self.showLegend() else None, fill_alpha=0.5, size=8) p.xaxis.axis_label = xlabel p.yaxis.axis_label = ylabel p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@y')] p.add_tools(hover) return p
def bokeh_PCA( geolocate, PCX, title="Eigenvector", ): from bokeh.plotting import figure, save, output_file from bokeh.models import ColumnDataSource from bokeh.models import HoverTool from bokeh.palettes import Viridis256, RdYlBu import seaborn as sns import bokeh.models my_hover = HoverTool() my_hover.tooltips = [("Wind Farm", '@{Wind Farm}'), ("Location", "@Location"), ("Construction Year", "@{Year entered}"), ("PC{0}".format(PCX), "@PC{0}".format(PCX))] tab = figure(title=title) # ADDING BASEMAP #p.multi_line('x',"y",source=base_chi,color="black",line_width=2) #base.plot() p_df = geolocate.drop('Coordinates', axis=1).copy() psource = ColumnDataSource(p_df) # Delux palette = sns.diverging_palette(10, 150, n=31) palette = palette.as_hex() #mapper=bokeh.models.mappers.ContinuousColorMapper(palette=Viridis256) mapper = bokeh.models.mappers.LinearColorMapper(palette=Viridis256[::-1], low=-1, high=1) colors = {'field': 'PC{0}'.format(PCX), 'transform': mapper} # Quick test on radius rads = {'field': 'PC{0}'.format(PCX), 'transform': mapper} #p.circle('Latitude','Longitude',source=psource , fill_color= "red",size=12,radius=radii) # radii = locate["PC1"]*.5 # p.circle(x=p_df['Latitude'],y=p_df['Longitude'] , fill_color= palette[0:p_df.shape[0]],size=12,radius=radii) tab.circle(y='Latitude', x='Longitude', source=psource, fill_color=colors, size=1, radius="PC{0}_r".format(PCX), fill_alpha=.3) #tab.circle(y='Latitude',x='Longitude',source=psource , fill_color=colors,size=1,radius="PC{0}_r".format(PCX)) tab.add_tools(my_hover) outfp = "/mnt/y/Code/Analysis/graph/powerdeck/pointmap_1.html" save(tab, outfp) return tab
def lineChart(df, xlabel, vFields, color=None, clustered=None, title=None): ylabel = ','.join(v for v in vFields) x = list(df[xlabel].values) if df[xlabel].dtype == object: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, x_range=x, **self.get_common_figure_options()) else: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, **self.get_common_figure_options()) if clustered is not None: colors = self.colorPalette(len( df[clustered].unique())) if color is None else color df[clustered] = df[clustered].astype(str) for j, c in enumerate(list( df[clustered].unique())) if clustered else enumerate( [None]): df2 = df[df[clustered] == c] if c else df df2 = df2.drop(clustered, axis=1) if c else df2 for i, v in enumerate(vFields): y = list(df2[v].values) l = v if self.isSubplot() else c p.line( x, y, line_width=2, color=colors[i] if self.isSubplot() else colors[j], legend=l if self.showLegend() else None) else: colors = self.colorPalette( len(vFields)) if color is None else color for i, v in enumerate(vFields): y = list(df[v].values) p.line(x, y, line_width=2, color=colors[i], legend=v if self.showLegend() else None) p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@y{0.00}'), ('x', '$x'), ('y', '$y')] p.add_tools(hover) return p
def csd_base_figure(add_legend=True, add_custom_hover=True): """ function to make a CSD plot dummy""" fig = figure(width=800, height=600, sizing_mode='scale_both', tools=['pan', 'box_zoom', 'reset', 'save', 'crosshair'], toolbar_location='right', x_axis_type="log", y_axis_type="linear", x_axis_label='time[s]', y_axis_label='abundance') # fig.y_range = Range1d(1E-3, 1) fig.title.text = 'CSD Evolution' # diagram name fig.title.align = 'left' # setting layout fig.title.text_font_size = "14pt" fig.xaxis.axis_label_text_font_size = "16pt" fig.yaxis.axis_label_text_font_size = "16pt" fig.yaxis.major_label_text_font_size = "14pt" fig.xaxis.major_label_text_font_size = "14pt" fig.xaxis[0].formatter = PrintfTickFormatter(format="%4.1e") custom_hover = HoverTool() custom_hover.tooltips = """ <style> .bk-tooltip>div:not(:first-child) {display:none;} </style> <b>time [s] </b> @x <br> <b>Relative abundance: </b> @y """ if add_custom_hover: fig.add_tools(custom_hover) if add_legend: legend = Legend(items=[]) fig.add_layout(legend) # fig.legend.title = 'charge states' fig.legend.location = "top_left" # setup plot legend fig.legend.click_policy = "mute" return fig
def histogram(df, vField, color=None, clustered=None): colors = self.colorPalette(len( df.index)) if color is None else color p = figure(y_axis_label='Frequency', x_axis_label=vField) for j, c in enumerate(list( df[clustered].unique())) if clustered else enumerate( [None]): df2 = df[df[clustered] == c] if c else df hist, edges = np.histogram(list(df2[vField]), density=True, bins=binsize) p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=colors[j], line_color="#cccccc", fill_alpha=0.8 if clustered else 1, legend=str(c) if clustered else None) p.y_range.start = 0 p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [('Frequency', '@top{0.00}'), ('Interval', '@left - @right')] p.add_tools(hover) return p
def nbytes_plot(**kwargs): data = {'name': [], 'left': [], 'right': [], 'center': [], 'color': [], 'percent': [], 'MB': [], 'text': []} source = ColumnDataSource(data) fig = figure(title='Memory Use', tools='', toolbar_location=None, **kwargs) fig.quad(source=source, top=1, bottom=0, left='left', right='right', color='color', alpha=0.8) fig.text(source=source, x='center', y=0.5, text='text', text_baseline='middle', text_align='center') fig.grid.grid_line_color = None fig.grid.grid_line_color = None fig.axis.visible = None fig.outline_line_color = None hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Percent:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">MB:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def plot_lines(df, fig, x, y, group): legends = [] groups = df.groupby(by=[group]) numlines = len(groups) colors=Spectral11[0:numlines] for i, (key, grp) in enumerate(groups): grp = grp.sort_values(by=x,axis=0) name = str(key) source = ColumnDataSource(data=grp) line = fig.line(x, y, source=source, line_width=4, line_color=colors[i]) point = fig.circle(x, y, source=source, name=name, size=8, fill_color=colors[i]) legends.append((name, [line])) hover = HoverTool(names=[name]) hover.tooltips = [(c, '@' + c) for c in grp.columns] hover.tooltips.append(('index', '$index')) fig.add_tools(hover) # place a legend outside the plot area # http://bokeh.pydata.org/en/dev/docs/user_guide/styling.html#outside-the-plot-area legend = Legend(legends=legends, location=(0, -30), name="foppo") fig.add_layout(legend, 'right') return fig
def __init__(self, scheduler, name, height=150, **kwargs): self.scheduler = scheduler self.action_ys = dict() self.last = 0 self.name = name self.source = ColumnDataSource({'time': [], 'action': [], 'hover': [], 'y': [], 'color': []}) x_range = DataRange1d(follow='end', follow_interval=200000) fig = figure(title=name, x_axis_type='datetime', height=height, tools='', x_range=x_range, **kwargs) fig.circle(source=self.source, x='time', y='y', color='color', size=50, alpha=0.5, legend='action') fig.yaxis.axis_label = "Action" fig.legend.location = 'top_left' hover = HoverTool() hover.tooltips = "@action<br>@hover" hover.point_policy = 'follow_mouse' fig.add_tools( hover, ResetTool(reset_size=False), PanTool(dimensions="width"), WheelZoomTool(dimensions="width") ) self.root = fig
def __init__(self, scheduler, **kwargs): with log_errors(): self.scheduler = scheduler self.source = ColumnDataSource({'occupancy': [0, 0], 'worker': ['a', 'b'], 'x': [0.0, 0.1], 'y': [1, 2], 'ms': [1, 2], 'color': ['red', 'blue'], 'bokeh_address': ['', '']}) fig = figure(title='Occupancy', tools='', id='bk-occupancy-plot', x_axis_type='datetime', **kwargs) rect = fig.rect(source=self.source, x='x', width='ms', y='y', height=1, color='color') rect.nonselection_glyph = None fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False # fig.xaxis[0].formatter = NumeralTickFormatter(format='0.0s') fig.x_range.start = 0 tap = TapTool(callback=OpenURL(url='http://@bokeh_address/')) hover = HoverTool() hover.tooltips = "@worker : @occupancy s." hover.point_policy = 'follow_mouse' fig.add_tools(hover, tap) self.root = fig
def __init__(self, scheduler, **kwargs): self.scheduler = scheduler self.steal = scheduler.extensions['stealing'] self.last = 0 self.source = ColumnDataSource({'time': [time() - 20, time()], 'level': [0, 15], 'color': ['white', 'white'], 'duration': [0, 0], 'radius': [1, 1], 'cost_factor': [0, 10], 'count': [1, 1]}) x_range = DataRange1d(follow='end', follow_interval=20000, range_padding=0) fig = figure(title="Stealing Events", x_axis_type='datetime', y_axis_type='log', height=250, tools='', x_range=x_range, **kwargs) fig.circle(source=self.source, x='time', y='cost_factor', color='color', size='radius', alpha=0.5) fig.yaxis.axis_label = "Cost Multiplier" hover = HoverTool() hover.tooltips = "Level: @level, Duration: @duration, Count: @count, Cost factor: @cost_factor" hover.point_policy = 'follow_mouse' fig.add_tools( hover, ResetTool(reset_size=False), PanTool(dimensions="width"), WheelZoomTool(dimensions="width") ) self.root = fig
def lineChart(df, xlabel, vFields, color=None, clustered=None, title=None): ylabel = ','.join(v for v in vFields) x = list(df[xlabel].values) if df[xlabel].dtype == object: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, x_range=x, **self.get_common_figure_options()) else: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, **self.get_common_figure_options()) if clustered is not None: colors = self.colorPalette(len(df[clustered].unique())) if color is None else color df[clustered] = df[clustered].astype(str) for j,c in enumerate(list(df[clustered].unique())) if clustered else enumerate([None]): df2 = df[df[clustered] == c] if c else df df2 = df2.drop(clustered, axis=1) if c else df2 for i,v in enumerate(vFields): y = list(df2[v].values) l = v if self.isSubplot() else c p.line(x, y, line_width=2, color=colors[i] if self.isSubplot() else colors[j], legend=l if self.showLegend() else None) else: colors = self.colorPalette(len(vFields)) if color is None else color for i,v in enumerate(vFields): y = list(df[v].values) p.line(x, y, line_width=2, color=colors[i], legend=v if self.showLegend() else None) p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@y{0.00}'), ('x', '$x'), ('y', '$y')] p.add_tools(hover) return p
def __init__(self, **kwargs): data = self.processing_update({'processing': {}, 'ncores': {}}) self.source = ColumnDataSource(data) x_range = Range1d(-1, 1) fig = figure(title='Processing and Pending', tools='', x_range=x_range, id='bk-processing-stacks-plot', **kwargs) fig.quad(source=self.source, left=0, right='right', color=Spectral9[0], top='top', bottom='bottom') fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Host:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Processing:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@processing</span> </div> """ hover.point_policy = 'follow_mouse' self.root = fig
def NewRegistered(): dfnr = pd.read_csv('BokehApp/Data/NewRegHouses_CLEANED.csv', delimiter='\t', index_col='Year_RNH') xnr = '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018' pnr = figure(x_range=xnr, plot_height=350, plot_width=550, title='Number of new properties registered', tools='pan, wheel_zoom, box_zoom, reset') sourcenr = ColumnDataSource(data= dict(x=xnr, y=dfnr['Ireland'], y1=dfnr['Dublin'])) pnr.line(x='x', y='y', line_width=2.5, line_color='#440154', source=sourcenr, legend=value('Ireland')) pnr.line(x='x', y='y1', line_width=2.5, line_color='#FDE724', source=sourcenr, legend=value('Dublin')) pnr.circle(x='x', y='y', size=5, color='#B2DD2C', source=sourcenr, legend=value('Ireland')) pnr.circle(x='x', y='y1', size=5, color='#35B778', source=sourcenr, legend=value('Dublin')) hoverpnr = HoverTool() hoverpnr.tooltips=[('Ireland', '@y'), ('Dublin', '@y1')] pnr.add_tools(hoverpnr) pnr.legend.location='top_right' #pnr.y_range.range_padding = 0.02 #pnr.xgrid.grid_line_color = None tick_labels_pnr = {'10000':'10K','20000':'20K','30000':'30K','40000':'40K','50000':'50K', '60000':'60K'} pnr.yaxis.major_label_overrides = tick_labels_pnr #pnr.legend.background_fill_alpha=None pnr.legend.border_line_alpha=0 pnr.legend.label_text_font_size = "11px" pnr.legend.click_policy="hide" pnr.title.text_font_size = '15px' #pti.axis.major_label_text_font_style = 'bold' pnr.xaxis.major_label_text_font_style = 'bold' pnr.toolbar.autohide = True pnr.outline_line_color=None pnr.grid.grid_line_alpha = 0.6 pnr.grid.grid_line_dash = 'dotted' pnr.grid.grid_line_dash_offset = 5 pnr.grid.grid_line_width = 2 return pnr
def plot_coords(df, filename): lat = 'Latitude|"Degrees"|-180.0|180.0|10' long = 'Longitude|"Degrees"|-180.0|180.0|10' speed = 'Speed|"mph"|0.0|150.0|10' df.loc[df[lat] == 0, lat] = np.nan df.loc[df[long] == 0, long] = np.nan coord_source = ColumnDataSource(df) coord_source.add(df['Interval|"ms"|0|0|1'], name='Time') coord = figure(sizing_mode='scale_both', width=700, height=600, title='GPS Data_{}'.format(filename)) # TODO figure out why this is broken # mapper = linear_cmap(field_name='Speed"|"mph"|0.0|150.0|10', palette=Spectral6, low=min(speed), high=max(speed)) coord.circle(x=lat, y=long, source=coord_source, size=3, color='darkcyan') # TODO figure out how to make the points be connected # coord.line(x=lat, y=long, source=coord_source, line_width=2, color='red') # Tools hover = HoverTool() hover.tooltips = [('Lat', '$x{0.000000}'), ('Long', '$y{0.000000}'), ('Time', '@Time')] hover.point_policy = 'follow_mouse' coord.add_tools(hover) return coord
def __init__(self, scheduler, **kwargs): with log_errors(): self.scheduler = scheduler self.source = ColumnDataSource({'occupancy': [0, 0], 'worker': ['a', 'b'], 'x': [0.0, 0.1], 'y': [1, 2], 'ms': [1, 2]}) fig = figure(title='Occupancy', tools='resize', id='bk-occupancy-plot', x_axis_type='datetime', **kwargs) fig.rect(source=self.source, x='x', width='ms', y='y', height=1, color='blue') fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False # fig.xaxis[0].formatter = NumeralTickFormatter(format='0.0s') fig.x_range.start = 0 hover = HoverTool() hover.tooltips = "@worker : @occupancy s" hover.point_policy = 'follow_mouse' fig.add_tools(hover) self.root = fig
def cs_base_figure(): """ function to make a CS plot dummy""" fig = figure(width=800, height=600, sizing_mode='scale_both', tools=['pan', 'box_zoom', 'reset', 'save', 'crosshair'], toolbar_location='right', x_axis_type="linear", y_axis_type="log", x_axis_label='charge state', y_axis_label='reaction cross sections, cm²') fig.title.text = 'Processes cross sections, cm²' # diagram name fig.title.align = 'left' # setting layout fig.title.text_font_size = "14pt" fig.xaxis.axis_label_text_font_size = "16pt" fig.yaxis.axis_label_text_font_size = "16pt" fig.yaxis.major_label_text_font_size = "14pt" fig.xaxis.major_label_text_font_size = "14pt" fig.yaxis[0].formatter = PrintfTickFormatter(format="%4.1e") custom_hover = HoverTool() custom_hover.tooltips = """ <style> .bk-tooltip>div:not(:first-child) {display:none;} </style> <b>charge state: </b> @x <br> <b>process rate: </b> @y """ fig.add_tools(custom_hover) legend = Legend(items=[]) fig.add_layout(legend) fig.legend.location = "top_right" # setup plot legend fig.legend.click_policy = "mute" return fig
def __init__(self, **kwargs): data = self.processing_update({'processing': {}, 'ncores': {}}) self.source = ColumnDataSource(data) x_range = Range1d(-1, 1) fig = figure( title='Processing and Pending', tools='resize', x_range=x_range, id='bk-processing-stacks-plot', **kwargs) fig.quad(source=self.source, left=0, right='right', color=Spectral9[0], top='top', bottom='bottom') fig.xaxis.minor_tick_line_alpha = 0 fig.yaxis.visible = False fig.ygrid.visible = False hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Host:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Processing:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@processing</span> </div> """ hover.point_policy = 'follow_mouse' self.root = fig
def main_map(self): #code for main page map for i in range(len(self.titles)): self.data_dict[self.titles[i]]=self.color_dict[i] for k in self.topics: if k in self.data_dict: self.color_main.append(self.data_dict[k]) map_options = GMapOptions(lat=23.3468, lng=78.5827, map_type='roadmap', zoom=5) my_hover = HoverTool() plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options) plot.title.text = "Tweet Data Analysis" plot.api_key = "AIzaSyAcvz_u0fGAyBE13pAnntsA1fn7Tu54RTU" source = ColumnDataSource(data=dict(lat=self.coord_x,lon=self.coord_y,colors=self.color_main[:len(self.coord_x)],tp=self.topics,tw=self.tweets)) my_hover.tooltips = [('Topic','@tp'),('Tweet','@{tw}')] circle = Circle(x="lon", y="lat", size=8, fill_color="colors", fill_alpha=0.7, line_color=None) plot.add_glyph(source, circle) plot.add_tools(my_hover) plot.add_tools( WheelZoomTool(), PanTool(), ResetTool()) output_file("F:\Final Year Project\Visualization\Website\static\main_page\map.html") save(obj=plot, filename="F:\Final Year Project\Visualization\Website\static\main_page\map.html")
def nbytes_plot(**kwargs): data = {'name': [], 'left': [], 'right': [], 'center': [], 'color': [], 'percent': [], 'MB': [], 'text': []} source = ColumnDataSource(data) fig = figure(title='Memory Use', tools='', toolbar_location=None, **kwargs) fig.quad(source=source, top=1, bottom=0, left='left', right='right', color='color', alpha=1) fig.grid.grid_line_color = None fig.grid.grid_line_color = None fig.axis.visible = None fig.outline_line_color = None hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Percent:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">MB:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def houseStockPlot(): df = pd.read_csv('BokehApp/Data/houseStock1.csv') df = df[['Year', 'Dublin_Vacant', 'Irl_Vacant', 'Dublin_Total','Irl_Total']] df.columns = ['Year', 'Dublin vacant', 'Ireland vacant', 'Dublin', 'Ireland'] ll = list(df.columns[1:]) source = ColumnDataSource(data=dict(x=df.Year.values,y=df['Ireland'], y1=df['Dublin'], y2=df['Ireland vacant'], y3=df['Dublin vacant'])) a2 = figure(plot_width=550, plot_height=350, title='Irish House Stock', tools = 'pan, wheel_zoom, box_zoom, reset') #, tooltips=ToolTips) hover = HoverTool() hover.tooltips=[('Ireland', '@y'), ('Dublin','@y1'), ('Ireland vancant', '@y2'), ('Dublin vacant','@y3')] a2.add_tools(hover) colors = viridis(4) a2.varea_stack(['y3','y2','y1','y'], x='x', source=source, color=colors[::-1], legend=ll, muted_alpha=0.2) a2.legend.location='top_left' a2.legend.click_policy="mute" a2.yaxis[0].formatter = NumeralTickFormatter(format="0 M") tick_labels = {'500000':'0.5M','1000000':'1M','1500000':'1,5M','2000000':'2M','2500000':'2,5M'} a2.yaxis.major_label_overrides = tick_labels a2.xaxis.ticker = df.Year.values a2.title.text_font_size = '15px' a2.legend.background_fill_alpha=None a2.legend.border_line_alpha=0 a2.legend.label_text_font_size = "11px" a2.xaxis.major_label_text_font_style = 'bold' a2.grid.grid_line_color=None a2.toolbar.autohide = True a2.outline_line_color=None return a2
def task_stream_plot(height=400, width=800, follow_interval=5000, **kwargs): data = { 'start': [], 'duration': [], 'key': [], 'name': [], 'color': [], 'worker': [], 'y': [], 'worker_thread': [], 'alpha': [] } source = ColumnDataSource(data) if follow_interval: x_range = DataRange1d(follow='end', follow_interval=follow_interval, range_padding=0) else: x_range = None fig = figure(width=width, height=height, x_axis_type='datetime', tools=['xwheel_zoom', 'xpan', 'reset', 'resize', 'box_zoom'], responsive=True, x_range=x_range, **kwargs) fig.rect(x='start', y='y', width='duration', height=0.9, fill_color='color', line_color='gray', alpha='alpha', source=source) if x_range: fig.circle(x=[1, 2], y=[1, 2], alpha=0.0) fig.xaxis.axis_label = 'Time' fig.yaxis.axis_label = 'Worker Core' fig.min_border_right = 10 fig.ygrid.grid_line_alpha = 0.4 fig.xgrid.grid_line_alpha = 0.0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Key:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Duration:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def createBokehChart(self): keyFields = self.getKeyFields() valueFields = self.getValueFields() color = self.options.get("color") xlabel = keyFields[0] ylabel = valueFields[0] wpdf = self.getWorkingPandasDataFrame().copy() colors = self.colorPalette(None if color is None else len(wpdf[color].unique())) p = figure(y_axis_label=ylabel, x_axis_label=xlabel) for i,c in enumerate(list(wpdf[color].unique())) if color else enumerate([None]): wpdf2 = wpdf[wpdf[color] == c] if c else wpdf p.circle(list(wpdf2[xlabel]), list(wpdf2[ylabel]), color=colors[i], legend=str(c) if c and self.showLegend() else None, fill_alpha=0.5, size=8) p.xaxis.axis_label = xlabel p.yaxis.axis_label = ylabel p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@y')] p.add_tools(hover) return p
def task_stream_plot(sizing_mode="scale_width", **kwargs): data = { "start": [], "duration": [], "key": [], "name": [], "color": [], "worker": [], "y": [], "worker_thread": [], "alpha": [], } source = ColumnDataSource(data) x_range = DataRange1d(range_padding=0) fig = figure( x_axis_type="datetime", title="Task stream", tools="xwheel_zoom,xpan,reset,box_zoom", toolbar_location="above", sizing_mode=sizing_mode, x_range=x_range, id="bk-task-stream-plot", **kwargs ) fig.rect( x="start", y="y", width="duration", height=0.8, fill_color="color", line_color="color", line_alpha=0.6, alpha="alpha", line_width=3, source=source, ) fig.xaxis.axis_label = "Time" fig.yaxis.axis_label = "Worker Core" fig.ygrid.grid_line_alpha = 0.4 fig.xgrid.grid_line_color = None fig.min_border_right = 35 fig.yaxis[0].ticker.num_minor_ticks = 0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 12px; font-weight: bold;">@name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span> <span style="font-size: 10px;">ms</span> </div> """ hover.point_policy = "follow_mouse" return source, fig
def progress_plot(height=300, width=800, **kwargs): from ..diagnostics.progress_stream import progress_quads data = progress_quads({'all': {}, 'in_memory': {}, 'erred': {}, 'released': {}}) source = ColumnDataSource(data) fig = figure(width=width, height=height, tools=['resize'], responsive=True, **kwargs) fig.quad(source=source, top='top', bottom='bottom', left=0, right=1, color='#aaaaaa', alpha=0.2) fig.quad(source=source, top='top', bottom='bottom', left=0, right='released_right', color='#0000FF', alpha=0.4) fig.quad(source=source, top='top', bottom='bottom', left='released_right', right='in_memory_right', color='#0000FF', alpha=0.8) fig.quad(source=source, top='top', bottom='bottom', left='erred_left', right=1, color='#000000', alpha=0.3) fig.text(source=source, text='fraction', y='center', x=-0.01, text_align='right', text_baseline='middle') fig.text(source=source, text='name', y='center', x=1.01, text_align='left', text_baseline='middle') fig.scatter(x=[-0.2, 1.4], y=[0, 5], alpha=0) fig.xgrid.grid_line_color = None fig.ygrid.grid_line_color = None fig.axis.visible = None fig.min_border_left = 0 fig.min_border_right = 10 fig.min_border_top = 0 fig.min_border_bottom = 0 fig.outline_line_color = None hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">All:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@all</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">In Memory:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@in_memory</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Erred:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@erred</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def worker_table_plot(**kwargs): """ Column data source and plot for host table """ with log_errors(): # names = ['host', 'cpu', 'memory_percent', 'memory', 'cores', 'processes', # 'processing', 'latency', 'last-seen', 'disk-read', 'disk-write', # 'network-send', 'network-recv'] names = ['processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen', 'memory_percent', 'host'] source = ColumnDataSource({k: [] for k in names}) columns = {name: TableColumn(field=name, title=name.replace('_percent', ' %')) for name in names} cnames = ['host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent'] formatters = {'cpu': NumberFormatter(format='0.0 %'), 'memory_percent': NumberFormatter(format='0.0 %'), 'memory': NumberFormatter(format='0 b'), 'latency': NumberFormatter(format='0.00000'), 'last-seen': NumberFormatter(format='0.000'), 'disk-read': NumberFormatter(format='0 b'), 'disk-write': NumberFormatter(format='0 b'), 'net-send': NumberFormatter(format='0 b'), 'net-recv': NumberFormatter(format='0 b')} table = DataTable(source=source, columns=[columns[n] for n in cnames], **kwargs) for name in cnames: if name in formatters: table.columns[cnames.index(name)].formatter = formatters[name] x_range = Range1d(0, 1) y_range = Range1d(-.1, .1) mem_plot = figure(title="Memory Usage (%)", tools='box_select', height=90, width=600, x_range=x_range, y_range=y_range, toolbar_location=None) mem_plot.circle(source=source, x='memory_percent', y=0, size=10, alpha=0.5) mem_plot.yaxis.visible = False mem_plot.xaxis.minor_tick_line_width = 0 mem_plot.ygrid.visible = False mem_plot.xaxis.minor_tick_line_alpha = 0 hover = HoverTool() mem_plot.add_tools(hover) hover = mem_plot.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span> </div> """ hover.point_policy = 'follow_mouse' return source, [mem_plot, table]
def progress_plot(**kwargs): from ..diagnostics.progress_stream import progress_quads data = progress_quads({'all': {}, 'in_memory': {}, 'erred': {}, 'released': {}}) x_range = Range1d(-0.5, 1.5) y_range = Range1d(5.1, -0.1) source = ColumnDataSource(data) fig = figure(tools='', toolbar_location=None, y_range=y_range, x_range=x_range, **kwargs) fig.quad(source=source, top='top', bottom='bottom', left=0, right=1, color='#aaaaaa', alpha=0.2) fig.quad(source=source, top='top', bottom='bottom', left=0, right='released_right', color=Spectral9[0], alpha=0.4) fig.quad(source=source, top='top', bottom='bottom', left='released_right', right='in_memory_right', color=Spectral9[0], alpha=0.8) fig.quad(source=source, top='top', bottom='bottom', left='erred_left', right=1, color='#000000', alpha=0.3) fig.text(source=source, text='fraction', y='center', x=-0.01, text_align='right', text_baseline='middle') fig.text(source=source, text='name', y='center', x=1.01, text_align='left', text_baseline='middle') fig.xgrid.grid_line_color = None fig.ygrid.grid_line_color = None fig.axis.visible = None fig.outline_line_color = None hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">All:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@all</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">In Memory:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@in_memory</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Erred:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@erred</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def progress_plot(**kwargs): with log_errors(): from ..diagnostics.progress_stream import progress_quads data = progress_quads({'all': {}, 'memory': {}, 'erred': {}, 'released': {}}) y_range = Range1d(-8, 0) source = ColumnDataSource(data) fig = figure(tools='', toolbar_location=None, y_range=y_range, **kwargs) fig.quad(source=source, top='top', bottom='bottom', left='left', right='right', color='#aaaaaa', alpha=0.2) fig.quad(source=source, top='top', bottom='bottom', left='left', right='released-loc', color=Spectral9[0], alpha=0.4) fig.quad(source=source, top='top', bottom='bottom', left='released-loc', right='memory-loc', color=Spectral9[0], alpha=0.8) fig.quad(source=source, top='top', bottom='bottom', left='erred-loc', right='erred-loc', color='#000000', alpha=0.3) fig.text(source=source, text='show-name', y='bottom', x='left', x_offset=5, text_font_size='10pt') fig.text(source=source, text='done', y='bottom', x='right', x_offset=-5, text_align='right', text_font_size='10pt') fig.xaxis.visible = False fig.yaxis.visible = False fig.grid.grid_line_alpha = 0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">All:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@all</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Memory:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Erred:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@erred</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def progress_plot(**kwargs): with log_errors(): from ..diagnostics.progress_stream import progress_quads data = progress_quads({"all": {}, "memory": {}, "erred": {}, "released": {}}) y_range = Range1d(-8, 0) source = ColumnDataSource(data) fig = figure(tools="", toolbar_location=None, y_range=y_range, id="bk-progress-plot", **kwargs) fig.quad(source=source, top="top", bottom="bottom", left="left", right="right", color="#aaaaaa", alpha=0.2) fig.quad(source=source, top="top", bottom="bottom", left="left", right="released-loc", color="color", alpha=0.6) fig.quad( source=source, top="top", bottom="bottom", left="released-loc", right="memory-loc", color="color", alpha=1 ) fig.quad( source=source, top="top", bottom="bottom", left="erred-loc", right="erred-loc", color="#000000", alpha=0.3 ) fig.text(source=source, text="show-name", y="bottom", x="left", x_offset=5, text_font_size="10pt") fig.text( source=source, text="done", y="bottom", x="right", x_offset=-5, text_align="right", text_font_size="10pt" ) fig.xaxis.visible = False fig.yaxis.visible = False fig.grid.grid_line_alpha = 0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">All:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@all</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Memory:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Erred:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@erred</span> </div> """ hover.point_policy = "follow_mouse" return source, fig
def histogram(df, vField, color=None, clustered=None): colors = self.colorPalette(len(df.index)) if color is None else color p = figure(y_axis_label='Frequency', x_axis_label=vField) for j,c in enumerate(list(df[clustered].unique())) if clustered else enumerate([None]): df2 = df[df[clustered] == c] if c else df hist, edges = np.histogram(list(df2[vField]), density=True, bins=binsize) p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=colors[j], line_color="#cccccc", fill_alpha=0.8 if clustered else 1, legend=str(c) if clustered else None) p.y_range.start=0 p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [('Frequency', '@top{0.00}'), ('Interval', '@left - @right')] p.add_tools(hover) return p
def task_stream_plot(height=400, width=800, follow_interval=5000, **kwargs): data = {'start': [], 'duration': [], 'key': [], 'name': [], 'color': [], 'worker': [], 'y': [], 'worker_thread': []} source = ColumnDataSource(data) if follow_interval: x_range = DataRange1d(follow='end', follow_interval=follow_interval, range_padding=0) else: x_range = None fig = figure(width=width, height=height, x_axis_type='datetime', tools=['xwheel_zoom', 'xpan', 'reset', 'resize', 'box_zoom'], responsive=True, x_range=x_range, **kwargs) fig.rect(x='start', width='duration', y='y', height=0.9, fill_color='color', line_color='gray', source=source) if x_range: fig.circle(x=[1, 2], y=[1, 2], alpha=0.0) fig.xaxis.axis_label = 'Time' fig.yaxis.axis_label = 'Worker Core' fig.min_border_right = 10 fig.ygrid.grid_line_alpha = 0.4 fig.xgrid.grid_line_alpha = 0.0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Key:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Duration:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def task_stream_plot(sizing_mode='scale_width', **kwargs): data = {'start': [], 'duration': [], 'key': [], 'name': [], 'color': [], 'worker': [], 'y': [], 'worker_thread': [], 'alpha': []} source = ColumnDataSource(data) x_range = DataRange1d(range_padding=0) fig = figure( x_axis_type='datetime', title="Task stream", tools='xwheel_zoom,xpan,reset,box_zoom', toolbar_location='above', sizing_mode=sizing_mode, x_range=x_range, **kwargs ) fig.rect( x='start', y='y', width='duration', height=0.8, fill_color='color', line_color='color', line_alpha=0.6, alpha='alpha', line_width=3, source=source ) fig.xaxis.axis_label = 'Time' fig.yaxis.axis_label = 'Worker Core' fig.ygrid.grid_line_alpha = 0.4 fig.xgrid.grid_line_color = None fig.min_border_right = 35 fig.yaxis[0].ticker.num_minor_ticks = 0 hover = HoverTool() fig.add_tools(hover) hover = fig.select(HoverTool) hover.tooltips = """ <div> <span style="font-size: 14px; font-weight: bold;">Key:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Duration:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span> </div> """ hover.point_policy = 'follow_mouse' return source, fig
def create_plot(ridb) : or_counties = { code: county for code, county in counties.items() if county["state"] == "or" } county_xs = [county["lons"] for county in or_counties.values()] county_ys = [county["lats"] for county in or_counties.values()] county_names = [county['name'] for county in or_counties.values()] lat = ridb['FacilityLatitude'] lon = ridb['FacilityLongitude'] source = ColumnDataSource(data=dict( x=county_xs, y=county_ys, name=ridb['FacilityName'] )) TOOLS="pan,wheel_zoom,box_zoom,reset,save" ridb = ridb.assign(Secret = "TRILLIUM") df_source = ColumnDataSource(data=ridb[['FacilityName','FacilityPhone','Secret']]) p = figure(title="Oregon Counties", tools=TOOLS) p.circle(lon, lat, size=8, color='navy', alpha=1, source=df_source, name='geo_points') p.patches('x', 'y', source=source, fill_color='green', fill_alpha=0.7, line_color="black", line_width=0.5) hover = HoverTool(names=['geo_points']) hover.tooltips = [(c, '@' + c) for c in ridb[['FacilityName','FacilityPhone','Secret']].columns] p.add_tools(hover) return p
def create_plot(ridb, list_to_display) : ridb_show = ridb[list_to_display] or_counties = { code: county for code, county in counties.items() if county["state"] == "or" } county_xs = [county["lons"] for county in or_counties.values()] county_ys = [county["lats"] for county in or_counties.values()] county_names = [county['name'] for county in or_counties.values()] lat = ridb['FacilityLatitude'] lon = ridb['FacilityLongitude'] source = ColumnDataSource(data=dict( x=county_xs, y=county_ys, )) TOOLS="pan,wheel_zoom,box_zoom,reset,save" df_source = ColumnDataSource(data=ridb_show) p = figure(title="Camping in Oregon!", tools=TOOLS) p.circle(lon, lat, size=8, color='navy', alpha=1, source=df_source, name='geo_points') p.patches('x', 'y', source=source, fill_color='green', fill_alpha=0.7, line_color="black", line_width=0.5) hover = HoverTool(names=['geo_points']) for c in ridb_show.columns: print(c) hover.tooltips = [(c, '@' + c) for c in ridb_show.columns] p.add_tools(hover) return p
def stackedBar(df, xlabel, vFields, color=None, clustered=False, title=None): ylabel = ','.join(v for v in vFields) ystart = 0 if clustered: factors=list(df.index) l = [ bk_value(a) for a in list(df.index) ] data = {'pd_stacked_col': list(df.columns.values)} for x in list(df.index): data[x] = list(df[x:x].values[0]) ystart = min(ystart, min(data[x])) else: factors=vFields l = [ bk_value(a) for a in vFields ] data = {'pd_stacked_col': list(df[xlabel].values)} for v in vFields: data[v] = list(df[v].values) ystart = min(ystart, min(data[v])) src = ColumnDataSource(data) colors = self.colorPalette(len(factors)) if color is None else color p = figure(x_range=data['pd_stacked_col'], y_axis_label=ylabel, x_axis_label=xlabel, title=title) p.vbar_stack(factors, x='pd_stacked_col', width=0.9, source=src, legend=l if self.showLegend() else None, color=colors) p.y_range.start = ystart p.axis.minor_tick_line_color = None p.outline_line_color = None p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(d if d is not 'pd_stacked_col' else xlabel, '@' + d + '{0.00}') for d in data] p.add_tools(hover) return p
def make_analysis_number(ages, age_errors, runids): hover = HoverTool() hover.tooltips = [('RunID', '@runids'), ('Age', '@ages')] ys = range(len(ages)) source = ColumnDataSource( data={'ages': ages, 'ys': ys, 'runids': runids}) fig = figure(plot_height=200, tools=[hover, ]) fig.circle('ages', 'ys', source=source, size=5, color="navy", alpha=0.5) fig.xaxis.visible = None err_xs = [] err_ys = [] for x, xerr, y in zip(ages, age_errors, ys): err_xs.append((x - xerr, x + xerr)) err_ys.append((y, y)) fig.multi_line(err_xs, err_ys) fig.logo = None fig.toolbar_location = None return _make_bokeh_components(fig)
def groupedBar(df, xlabel, vFields, color=None, clustered=False, title=None): ylabel = ','.join(v for v in vFields) if clustered: factors=list(df.index) x = [ (b, a) for b in list(df.columns.values) for a in list(df.index) ] l = [ (a) for b in list(df.columns.values) for a in list(df.index) ] counts = sum(zip(df.at[a,b] for b in list(df.columns.values) for a in list(df.index)), ()) else: factors=vFields x = [ (b,a) for b in list(df[xlabel].values) for a in vFields ] l = [ (a) for b in list(df[xlabel].values) for a in vFields ] counts = [ df[df[xlabel] == b][a].values[0] for b in list(df[xlabel].values) for a in vFields ] src = ColumnDataSource(data=dict(x=x, counts=counts, l=l)) colors = self.colorPalette(len(factors)) if color is None else color p = figure(x_range=FactorRange(*x), y_axis_label=ylabel, x_axis_label=xlabel, title=title) p.vbar(x='x', top='counts', width=0.925, source=src, legend='l' if self.showLegend() else None, color=factor_cmap('x', palette=colors, factors=factors, start=1, end=2)) p.y_range.start = 0 if not counts else min(0, min(counts)) p.axis.minor_tick_line_color = None p.outline_line_color = None p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xaxis.major_label_text_font_size = "0px" p.xaxis.major_label_text_color = None p.xaxis.major_tick_line_color = None p.xgrid.grid_line_color = None p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@counts{0.00}')] p.add_tools(hover) return p
df=select_runners() source.data=dict(x=df['AGE'], y=df['TIMESTAMP'],color=df['color'],alpha=df['alpha'],size=df['size'],last_name=df['LASTNAME'], first_name=df['FIRSTNAME'],time=df['TIME'],year=df['YEAR']) runners=pd.read_csv('./output/alltime.csv') runners['TIMESTAMP']=timeToTimeStamp(runners.TIME) source = ColumnDataSource(data=dict(x=[], y=[])) p = Figure(plot_width=1400, plot_height=800, y_axis_type='datetime') #s1=p.scatter('AGE', 'TIMESTAMP', source =source, size=15, alpha=0.5) p.circle(x="x", y="y", source=source, size="size",color="color",fill_alpha="alpha") hover = HoverTool() hover.tooltips = [('First Name', '@first_name'), ('Last Name', '@last_name'), ('Time', '@time'), ('Year', '@year'), ('Age', '@x')] p.add_tools(hover) controls=[min_year, max_year, last_name] for c in controls: c.on_change('value', update) inputs=HBox(VBoxForm(*controls), width=300) update(None, None, None) curdoc().add_root(HBox(inputs, p, width=1100))
def make_interactive_comparison_barchart(sources, bar, countries, years, title, default_year='2012', show_plot=True, legend_x=1, legend_x_padding=7.5, legend_y=[1.12, 1.05], legend_max_x_items=4): # define PlotObjects that are common for all years xdr = list(countries) xdr = FactorRange(factors=sorted(xdr)) ydr = Range1d(0,1.2) AXIS_FORMATS = dict( minor_tick_in=None, minor_tick_out=None, major_tick_in=None, major_label_text_font_size="10pt", major_label_text_font_style="normal", axis_label_text_font_size="10pt", axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) plot = Plot(plot_width=800, plot_height=375, x_range = xdr, y_range=ydr, title = title + default_year, outline_line_color=None, toolbar_location=None, responsive=True) xaxis = CategoricalAxis(major_label_orientation = pi/4, axis_label="", **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=0.2), axis_label="", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # create 'reference' source data # 1. this is the ColumnDataSource that has all the glyph info from # our previously made BarCharts # 2. it should clone a data-source from `sources` otherwise an moving # the slider back to '2012' will fail to trigger an update since the # new and old `reference_source` ColumnDataSource objects will be the same! reference_source = sources['_' + default_year].clone() plot.add_glyph(reference_source, \ Rect(x='x', y='y', width='width', height='height',\ fill_color='color', fill_alpha='fill_alpha')) # --- add legend --- # # This is why we kept one barchart around. It's 'Legend' renderer has all # the coloring and text info we want. So we'll have to rip it out # and manually make our own legend with glyphs bar_legend = bar.select(dict(type=Legend))[0].clone() tmp_source = [] for index, legend in enumerate(bar_legend.legends): legend_text = legend[0] glyph = legend[1][0] x = legend_x + legend_x_padding*(index % legend_max_x_items) y = legend_y[0] if (index < legend_max_x_items) else legend_y[1] tmp_source.append(pd.DataFrame(dict( x=x, y=y, legend_text=legend_text, color=glyph.data_source.to_df().color ))) tmp_source = ColumnDataSource(pd.concat(tmp_source)) plot.add_glyph(tmp_source, Text(x='x', y='y', text='legend_text', text_baseline='bottom', x_offset=10, y_offset=8)) plot.add_glyph(tmp_source, Square(x='x', y='y', size=10, line_color=None, fill_color='color')) # --- add HoverTool --- # hover = HoverTool(point_policy = "snap_to_data") # options "follow_mouse", "snap_to_data") hover.tooltips = OrderedDict([ ("Country", "@x"), ("Share", "@height{0.000}") ]) plot.add_tools(hover) # --- JS callback ---- # dictionary_of_sources = dict(zip([x for x in years], ['_%s' % x for x in years])) js_source_array = str(dictionary_of_sources).replace("'", "") # Add the slider code = """ var year = slider.get('value'), sources = %s, new_source_data = sources[year].get('data'); plot.set('title', '%s' + year); renderer_source.set('data', new_source_data); renderer_source.trigger('change'); """ % (js_source_array, title) callback = CustomJS(args=sources, code=code) callback.args["plot"] = plot callback.args["renderer_source"] = reference_source slider = Slider(start=int(years[0]), end=int(years[-1]), value=int(default_year), step=1, orientation='horizontal', title="Year", callback=callback) callback.args["slider"] = slider # --- put it all together --- # layout = vplot(plot, slider) if show_plot: show(layout) return layout
x_range=x_range, y_range=y_range, map_options=map_options, title = "NIST Fire Studies",plot_width=1100, plot_height=700 ) data = pd.read_csv('study_data.csv') source = ColumnDataSource({'lat':data['Latitude'],'lon':data['Longitude'],'studys': data['Study'],'report': data['Report'],'fill':data['Color'],'type':data['Type'],'date':data['Date']}) circle = Circle(x="lon",y="lat",size=15,fill_color="fill") plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() hover = HoverTool() tap = TapTool() hover.tooltips = [('Study Title','@studys'),('Date','@date'),('Type','@type')] url = "@report" TapTool.callback = OpenURL(url=url) plot.add_tools(pan,wheel_zoom,hover,tap) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "NIST_Fire_Studies.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "NIST Fire Study Map")) print("Wrote %s" % filename) view(filename)
def scatter_with_hover(df, x, y, fig=None, cols=None, name=None, marker='x', fig_width=500, fig_height=500, **kwargs): """ Plots an interactive scatter plot of `x` vs `y` using bokeh, with automatic tooltips showing columns from `df`. Parameters ---------- df : pandas.DataFrame DataFrame containing the data to be plotted x : str Name of the column to use for the x-axis values y : str Name of the column to use for the y-axis values fig : bokeh.plotting.Figure, optional Figure on which to plot (if not given then a new figure will be created) cols : list of str Columns to show in the hover tooltip (default is to show all) name : str Bokeh series name to give to the scattered data marker : str Name of marker to use for scatter plot **kwargs Any further arguments to be passed to fig.scatter Returns ------- bokeh.plotting.Figure Figure (the same as given, or the newly created figure) Example ------- fig = scatter_with_hover(df, 'A', 'B') show(fig) fig = scatter_with_hover(df, 'A', 'B', cols=['C', 'D', 'E'], marker='x', color='red') show(fig) Author ------ Robin Wilson <*****@*****.**> with thanks to Max Albert for original code example """ # If we haven't been given a Figure obj then create it with default # size etc. if fig is None: fig = figure(width=fig_width, height=fig_height, tools=['box_zoom', 'reset']) # We're getting data from the given dataframe source = ColumnDataSource(data=df) # We need a name so that we can restrict hover tools to just this # particular 'series' on the plot. You can specify it (in case it # needs to be something specific for other reasons), otherwise # we just use 'main' if name is None: name = 'main' # Actually do the scatter plot - the easy bit # (other keyword arguments will be passed to this function) fig.scatter(df[x], df[y], source=source, name=name, marker=marker, **kwargs) # Now we create the hover tool, and make sure it is only active with # the series we plotted in the previous line hover = HoverTool(names=[name]) if cols is None: # Display *all* columns in the tooltips hover.tooltips = [(c, '@' + c) for c in df.columns] else: # Display just the given columns in the tooltips hover.tooltips = [(c, '@' + c) for c in cols] hover.tooltips.append(('index', '$index')) # Finally add/enable the tool fig.add_tools(hover) return fig
circle = Circle( x="lon", y="lat", size=15, fill_color="fill", line_color="black" ) plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() hover = HoverTool() hover.tooltips = [ ("Geocoder", "@ID_list"), ] plot.add_tools(pan, wheel_zoom, box_select, hover) xaxis = LinearAxis( axis_label="Latitude", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000") ) plot.add_layout(xaxis, 'below') yaxis = LinearAxis( axis_label="Longitude", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")
color = loc_color, rprice = price, dis = distance, addr = address, restaurant = food, cafe = cafes, pub = pubs, size = sqft, ) ) circle = Circle(x = 'lon', y = 'lat', fill_color = 'color', size = 10, fill_alpha=0.6, line_color=None) plot.add_glyph(source, circle) # Hover hover = HoverTool() hover.point_policy = "follow_mouse" hover.tooltips = [ ("Address", "@addr"), ("Price per Room", "@rprice"), ("Distance to Campus", "@dis"), ("Food Quality", "@restaurant"), ("Number of cafes", "@cafe"), ("Number of pubs", "@pub"), ("Room size", "@size"), ] tools = [PanTool(), WheelZoomTool(), hover] plot.add_tools(*tools) output_file("gmap_plot.html") show(plot)
def build_chart(self, chart = 'r', name = None): if chart is 'r': title = 'R Chart {}'.format(name) df = self._df_R.reset_index() else: title = 'Xb Chart' df = self._df_X.reset_index() TOOLS = "pan,box_zoom,wheel_zoom,reset" hover = HoverTool(names=["x", "values"]) #p = figure(plot_width=400, plot_height=300, title=title, tools = [hover,TOOLS]) p = figure(plot_width=400, plot_height=300, title=title, tools="") # add a line renderer src = ColumnDataSource( data=dict( x = df['index'], val = df['values'], up = df['upper limit'], low = df['lower limit'], mean = df['mean'], sigma1 = df['sigma1'], sigma2 = df['sigma2'], minus_sigma1 = df['sigma-1'], minus_sigma2 = df['sigma-2'], time = df['index'].apply(str) )) x_src = ColumnDataSource( data=dict( x = df['index'][df['x'] == True], val = df['values'][df['x'] == True], time = df['index'][df['x'] == True].apply(str) )) strat_src = ColumnDataSource( data=dict( x = df['index'][df['stratification'] == True], val = df['values'][df['stratification'] == True], time = df['index'][df['stratification'] == True].apply(str) )) mix_src = ColumnDataSource( data=dict( x = df['index'][df['mixture'] == True], val = df['values'][df['mixture'] == True], time = df['index'][df['mixture'] == True].apply(str) )) hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ('timestamp', '@time'), ('value', '@val'), ]) zone_c_1 = BoxAnnotation(plot=p, bottom=df['sigma2'][0], top=df['sigma3'][0], fill_alpha=0.1, fill_color='red') zone_b_1 = BoxAnnotation(plot=p, bottom=df['sigma1'][0], top=df['sigma2'][0], fill_alpha=0.1, fill_color='yellow') zone_a_1 = BoxAnnotation(plot=p, bottom=df['mean'][0], top=df['sigma1'][0], fill_alpha=0.1, fill_color='green') zone_a_2 = BoxAnnotation(plot=p, bottom=df['sigma-1'][0], top=df['mean'][0], fill_alpha=0.1, fill_color='green') zone_b_2 = BoxAnnotation(plot=p, bottom=df['sigma-2'][0], top=df['sigma-1'][0], fill_alpha=0.1, fill_color='yellow') zone_c_2 = BoxAnnotation(plot=p, bottom=df['sigma-3'][0], top=df['sigma-2'][0], fill_alpha=0.1, fill_color='red') p.renderers.extend([zone_c_1, zone_b_1, zone_a_1, zone_a_2, zone_b_2, zone_c_2]) p.line('x', 'up', source = src, line_width=2, line_color='red') p.line('x', 'low', source = src, line_width=2, line_color='red') p.line('x', 'mean', source = src, line_width=2) # x p.line('x', 'sigma1', source = src, line_dash=[4, 4], line_color="green", line_width=2, alpha=0.5) p.line('x', 'sigma2', source = src, line_dash=[4, 4], line_color="orange", line_width=2, alpha=0.5) p.line('x', 'minus_sigma1', source = src, line_dash=[4, 4], line_color="green", line_width=2, alpha=0.5) p.line('x', 'minus_sigma2', source = src, line_dash=[4, 4], line_color="orange", line_width=2, alpha=0.5) p.x('x', 'val', source = x_src, name = "x", size=25, line_width=5, color="red") p.triangle('x', 'val', source = strat_src, size = 25, line_width=5, color="black") p.triangle('x', 'val', source = mix_src, size = 25, line_width=5, color="black") #p.line('x', 'val', source = src, name = "values", line_width=2, line_color='blue') p.circle('x', 'val', source = src, size=10, color='blue') #show(p) return p