def create_stock_figure(stock_source): mapper = linear_cmap(field_name='pchange', palette=['red', 'green'], low=0, high=0, low_color='green', high_color='red') TOOLTIPS = [("open", "@open"), ("high", "high"), ("low", "@low"), ("close", "@close"), ("pchange", "@pchange"), ("date", "@date")] TOOLS = [ TapTool(), PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool(), BoxSelectTool(), HoverTool(tooltips=TOOLTIPS) ] fig = figure(plot_height=500, plot_width=1000, x_axis_label='时间', y_axis_label='价格', tools=TOOLS, toolbar_location="above", x_range=(stock_source.data['index'].min(), stock_source.data['index'].max()), y_range=(stock_source.data['low'].min(), stock_source.data['high'].max())) fig.line(x='index', y='uprice', color='blue', line_width=2, source=stock_source, name='无穷成本均线') fig.segment(x0='index', y0='low', x1='index', y1='high', line_width=1.5, color='black', source=stock_source) fig.vbar(x='index', bottom='open', top='close', width=1, color=mapper, source=stock_source) fig.xaxis.major_label_overrides = { i: mdate for i, mdate in enumerate(stock_source.data["date"]) } return fig
def graphNetwork(adjm, data): G = nx.from_numpy_matrix(adjm) data['degree'] = list(dict(G.degree).values()) subgraphs = getSubgraphs(G) subgraphs = data.join(subgraphs.set_index('nodes')) graph_plot = Plot(plot_width=800, plot_height=800, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) graph_plot.title.text = "Graph.\nTotal Nodes: %i\nTotal Edges: %i\t Total subgraphs:%i" % ( G.number_of_nodes(), G.number_of_edges(), len(subgraphs.subgraph.unique())) node_hover_tool = HoverTool(tooltips=[( "hashtag", "@hashtag"), ("freq", "@frequency"), ('degree', '@degree'), ('subgraph', '@subgraph')]) graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(), WheelZoomTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=18, fill_color='#277bb6') graph_renderer.node_renderer.hover_glyph = Circle(size=18, fill_color='#E84A5F') graph_renderer.node_renderer.glyph.properties_with_values() graph_renderer.edge_renderer.glyph = MultiLine(line_color="gray", line_alpha=0.7, line_width=0.3) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='#e09e8f', line_width=3) graph_renderer.node_renderer.data_source.data[ 'hashtag'] = subgraphs.ht.values graph_renderer.node_renderer.data_source.data[ 'frequency'] = subgraphs.frq.values graph_renderer.node_renderer.data_source.data[ 'degree'] = subgraphs.degree.values graph_renderer.node_renderer.data_source.data[ 'subgraph'] = subgraphs.subgraph.values graph_renderer.inspection_policy = NodesAndLinkedEdges() graph_renderer.selection_policy = NodesAndLinkedEdges() graph_plot.toolbar.active_inspect = [node_hover_tool] graph_plot.renderers.append(graph_renderer) #output_file(path+topic+"_graph_N"+str(nodeThresh)+'E'+str(edgeThresh)+".html") show(graph_plot) subgraphs = subgraphs.sort_values(by='subgraph') return subgraphs
def bokeh(G, node_color=None, node_label=None, node_size=100, node_size_scale=[25, 200], alpha=0.8, font_size=18, cmap='Set1', width=40, height=30, pos=None, filename=None, title=None, methodtype='default', verbose=3): import networkx as nx from bokeh.io import show, output_file from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, BoxZoomTool, ResetTool from bokeh.models.graphs import from_networkx from bokeh.palettes import Spectral4 SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red" edge_attrs = {} for start_node, end_node, _ in G.edges(data=True): edge_color = SAME_CLUB_COLOR if G.nodes[start_node]["club"] == G.nodes[ end_node]["club"] else DIFFERENT_CLUB_COLOR edge_attrs[(start_node, end_node)] = edge_color nx.set_edge_attributes(G, edge_attrs, "edge_color") # Show with Bokeh plot = Plot(plot_width=400, plot_height=400, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = "Graph Interaction Demonstration" node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")]) plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1) plot.renderers.append(graph_renderer) output_file("interactive_graphs.html") show(plot)
def plot_categorical_column(contexts, layer, acts_tag, color_col, legend=False): """ Given a layer and a categorical column in the contexts dataframe, plots all activations at the specified layer, colorized to visualize the specified column. TODO: document requirements of contexts dataframe. """ p = empty_plot() if legend: # add legend p.height += 200 p.add_layout( Legend(orientation='horizontal', label_text_font_size='6pt', label_width=10), 'above') source = ColumnDataSource({ 'x': contexts[f'{layer} {acts_tag} x'], 'y': contexts[f'{layer} {acts_tag} y'], 'color': vis_util.categorical_list_to_color_list(contexts[color_col]), 'legend label': contexts[color_col], 'token': contexts['token'], 'abbreviated context': contexts['abbreviated context'], 'abbreviated context html': contexts['abbreviated context html'], 'context html': contexts['context html'] }) if legend: p.circle('x', 'y', color='color', legend_group='legend label', source=source) else: p.circle('x', 'y', color='color', source=source) p.tools = [ PanTool(), WheelZoomTool(), BoxZoomTool(), ResetTool(), custom_hover_tool() ] return p
def initialize_figure(height, width, title, X, margin, decision): """ Arguments --------- height : int Figure height width : int Figure width title : str or None Figure title X : numpy.ndarray Data to be plotted. It will be used to set `x_range` and `y_range` Shape of X = (n_data, 2) margin : float Padding size. The range of figures is `x_range` = (x_min - margin, x_max + margin) `y_range` = (y_min - margin, y_max + margin) decision : Boolean or None If not None or True, hover tool shows decision value of each point Returns ------- p : bokeh.plotting.Figure Initialized figure. Hovertool looks up objects of which name is `scatter` """ tooltips = [("data index", "$index point"), ("label", "@label"), ("(x, y)", "($x, $y)"), ('Support Vector', '@sv')] if (decision is not None) or (decision == True): tooltips.append(('decision value', '@decision')) tools = [ HoverTool(names=["scatter"]), PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool(), SaveTool() ] x_range, y_range = check_range(X, margin) p = figure(height=height, width=width, title=title, tooltips=tooltips, tools=tools, x_range=x_range, y_range=y_range) return p
def make_plot_freq(updated_df_freq, y_val_freq, y_label, bio_title): gs_bins = list(range(1, 202)) gs_labels = list(range(1, 201)) #df for frequency df_bins = updated_df_freq df_bins = df_bins.groupby(y_val_freq).sum() df_bins['specimenBin'] = pd.cut(df_bins.specimenCount, gs_bins, right=True, labels=gs_labels, retbins=False, include_lowest=True) df_bins = df_bins.groupby('specimenBin').count() df_bins.rename(columns={'specimenCount': 'yaxisCount'}, inplace=True) #create the frequency plots hov_freq = HoverTool(tooltips=[ (y_label + " Count", "@yaxisCount"), ("Specimens", "@specimenBin"), ], mode='mouse') p_freq = figure(title='Frequency Distribution of Specimens By ' + y_label + ': ' + bio_title, width=fig_width, height=fig_height, x_axis_label="# Specimens (n)", y_axis_label='# of ' + y_label + ' with more than n specimens', tools=[ hov_freq, PanTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(), ResetTool() ]) #xrange removed p_freq.line('specimenBin', 'yaxisCount', line_width=2, line_color="cadetblue", source=df_bins) p_freq.circle('specimenBin', 'yaxisCount', fill_color=secondary_color, size=5, source=df_bins) p_freq.xaxis.major_label_orientation = x_angle p_freq.xgrid.grid_line_color = None p_freq.ygrid.grid_line_color = '#BFBFBF' p_freq.y_range.start = 0 p_freq.yaxis.minor_tick_line_color = None return p_freq
def plot(df, xcol, ycol, tags, groupby, colors, outprefix): output_file(f'{outprefix}.html') tooltips = [(f"({xcol},{ycol})", f"(@{xcol}, @{ycol})")] for tag in tags: tooltips.append((f"{tag}", f"@{tag}")) hover = HoverTool(tooltips=tooltips) p = figure(title="", tools=[ hover, BoxZoomTool(), ResetTool(), WheelZoomTool(), PanTool(), SaveTool(), ZoomInTool(), ZoomOutTool() ], toolbar_location="below", toolbar_sticky=False, plot_width=800, plot_height=600, x_axis_label=xcol, y_axis_label=ycol) if groupby: for ngroup, group in enumerate(df[groupby].unique()): if type(colors) == dict: color = colors[group] else: color = colors[ngroup] source = ColumnDataSource(df.loc[df[groupby] == group, :]) p.circle(x=xcol, y=ycol, size=10, alpha=1, color=color, source=source, legend=group) p.legend.location = "top_left" p.legend.click_policy = "hide" else: source = ColumnDataSource(df) p.circle(x=xcol, y=ycol, size=10, alpha=0.8, color=colors, source=source) save(p)
def large_plot(n): from bokeh.models import ( Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, SaveTool, ResetTool ) from bokeh.models.layouts import Column from bokeh.models.glyphs import Line col = Column() objects = set([col]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis() plot.add_layout(xaxis, "below") yaxis = LinearAxis() plot.add_layout(yaxis, "left") xgrid = Grid(dimension=0) plot.add_layout(xgrid, "center") ygrid = Grid(dimension=1) plot.add_layout(ygrid, "center") tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() save = SaveTool() reset = ResetTool() tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset] plot.add_tools(*tools) col.children.append(plot) objects |= set([ xdr, ydr, xaxis, yaxis, xgrid, ygrid, renderer, renderer.view, glyph, source, source.selected, source.selection_policy, plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title, box_zoom.overlay, box_select.overlay, ] + tickers + tools) return col, objects
def subnetwork_generator(top_n_nodes): import pickle import pandas as pd import networkx as nx from bokeh.io import show, output_file from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, BoxZoomTool, ResetTool from bokeh.models.graphs import from_networkx from bokeh.palettes import Spectral4 ## loading the total edgelist with open(r"./flaskexample/total_edgelist.pickle", "rb") as input_file: total_edgelist = pickle.load(input_file) ## Creating the subnetwork edgelist subnet_edgelist = [] for nodeID in top_n_nodes: for i, edge in enumerate(total_edgelist): if edge[0] == nodeID or edge[1] == nodeID: subnet_edgelist.append(edge) ## Initializing the graph G = nx.Graph() ## Adding the nodes and edges for edge in subnet_edgelist: G.add_edge(edge[0], edge[1]) df_index_title = pd.read_csv('./flaskexample/df_index_title.csv') df_subnet = df_index_title[df_index_title['Index'].isin(list(G.nodes))] print(df_subnet) ## Getting title dictionary based on filtered dataframe over the subnetwork dict_title = {} keys = list(G.nodes) for i in keys: dict_title[i] = 'Missing' for j in range(df_subnet.shape[0]): if str(df_subnet.iloc[j, 0]) == i: dict_title[i] = df_subnet.iloc[j, 1] nx.set_node_attributes(G, dict_title, 'title') # Show with Bokeh plot = Plot(plot_width=400, plot_height=400, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) #plot.title.text = "Subnetwork of recommended articles" node_hover_tool = HoverTool(tooltips=[("Title", "@title")]) plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=8, fill_color=Spectral4[0]) #graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1) plot.renderers.append(graph_renderer) return (plot)
def test_box_zoom_with_center_origin(self, single_plot_page): plot = _make_plot(BoxZoomTool(origin="center")) page = single_plot_page(plot) page.drag_canvas_at_position(100, 100, 50, 50) page.click_custom_action() results = page.results assert (results['xrstart'] + results['xrend'])/2.0 == pytest.approx(0.25) assert (results['yrstart'] + results['yrend'])/2.0 == pytest.approx(0.75) assert page.has_no_console_errors()
def test_box_zoom_can_match_aspect(self, single_plot_page): plot = _make_plot(BoxZoomTool(match_aspect=True)) plot.x_range.end = 2 page = single_plot_page(plot) page.drag_canvas_at_position(150, 150, 70, 53) page.click_custom_action() results = page.results assert (results['xrend'] - results['xrstart']) / (results['yrend'] - results['yrstart']) == pytest.approx(2.0) assert page.has_no_console_errors()
def epicyclic_gear(module, sun_teeth, planet_teeth): xdr = Range1d(start=-150, end=150) ydr = Range1d(start=-150, end=150) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=800) plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), UndoTool(), RedoTool(), ResetTool()) annulus_teeth = sun_teeth + 2 * planet_teeth glyph = Gear(x=0, y=0, module=module, teeth=annulus_teeth, angle=0, fill_color=fill_color[0], line_color=line_color, internal=True) plot.add_glyph(glyph) glyph = Gear(x=0, y=0, module=module, teeth=sun_teeth, angle=0, fill_color=fill_color[2], line_color=line_color) plot.add_glyph(glyph) sun_radius = pitch_radius(module, sun_teeth) planet_radius = pitch_radius(module, planet_teeth) radius = sun_radius + planet_radius angle = half_tooth(planet_teeth) for i, j in [(+1, 0), (0, +1), (-1, 0), (0, -1)]: glyph = Gear(x=radius * i, y=radius * j, module=module, teeth=planet_teeth, angle=angle, fill_color=fill_color[1], line_color=line_color) plot.add_glyph(glyph) return plot
def alignment_stats(self, input_path_file, output_path_file_csv, output_path_file_html): df = pd.read_json(input_path_file, orient='index') df.to_csv(output_path_file_csv + '.csv', index=True, sep='\t') samples = [] alignment_length = [] alignment_freq = [] for index, row in df.iterrows(): for key, value in row['stats_per_reference'].items(): samples.extend([index + '(' + key + ')'] * int(self.nr_items_align(value))) for k, v in value.items(): if k == 'alignment_length_and_freqs': for keys, values in v.items(): alignment_length.extend([float(keys)]) alignment_freq.extend([values]) data1 = {} data1['samples'] = samples data1['aligned read length'] = alignment_length data1['frequency'] = alignment_freq bar1 = Bar(data1, values='frequency', label='aligned read length', stack='samples', agg='sum', title="Alignment read length and frequency", legend='top_left', width=1200, bar_width=1.0, palette=[ 'Blue', 'Aqua', 'SeaGreen', 'SpringGreen', 'Brown', 'Peru', 'Purple', 'Violet' ], tools=[ HoverTool(tooltips=[("Read length", "@x"), ("Frequency", "@y")]), PanTool(), BoxSelectTool(), BoxZoomTool(), WheelZoomTool(), ResizeTool(), ResetTool() ]) output_file(output_path_file_html + '.html') show(bar1)
def metrix_plot(xname, yname, xax=False, yax=False, xdr=None, ydr=None, source=None): mbl = 40 if yax else 0 mbb = 40 if xax else 0 plot = Plot(x_range=xdr, y_range=ydr, plot_width=200 + mbl, plot_height=200 + mbb, min_border_left=1 + mbl, min_border_right=1, min_border_top=1, min_border_bottom=1 + mbb) circle = Circle(x=xname, y=yname, fill_color="color", size=4, line_color="color") r = plot.add_glyph(source, circle) xdr.renderers.append(r) ydr.renderers.append(r) xticker = BasicTicker() if xax: xaxis = LinearAxis() xaxis.axis_label = xname plot.add_layout(xaxis, 'below') xticker = xaxis.ticker plot.add_layout(Grid(dimension=0, ticker=xticker)) yticker = BasicTicker() if yax: yaxis = LinearAxis() yaxis.axis_label = yname yaxis.major_label_orientation = 'vertical' plot.add_layout(yaxis, 'left') yticker = yaxis.ticker plot.add_layout(Grid(dimension=1, ticker=yticker)) plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), SaveTool(), ResetTool()) return plot
def large_plot(n): from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, ResizeTool, SaveTool, ResetTool) from bokeh.models.layouts import VBox from bokeh.models.glyphs import Line vbox = VBox() objects = set([vbox]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() resize = ResizeTool() save = SaveTool() reset = ResetTool() tools = [ pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, resize, save, reset ] plot.add_tools(*tools) vbox.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.toolbar, plot.tool_events, plot.title, box_zoom.overlay, box_select.overlay ] + tickers + tools) return vbox, objects
def make_plot(source, title): plot = figure(plot_width=800, plot_height = 800, x_axis_type = 'datetime', toolbar_location='below', tools = [PanTool(), WheelZoomTool(), BoxZoomTool(), ResetTool()]) plot.xaxis.axis_label = 'Time' plot.yaxis.axis_label = 'Price ($)' plot.axis.axis_label_text_font_style = 'bold' plot.x_range = DataRange1d(range_padding = 0.0) plot.grid.grid_line_alpha = 0.3 plot.title.text = title plot.line(x= 'date', y='nadac_per_unit', source=source) plot.add_tools(HoverTool(tooltips=[('Date', '@date{%F}'), ('Price', '@nadac_per_unit')], formatters = {'date': 'datetime'})) return plot
def _projected_prediction(model): """ Create projected prediction plot Parameters ---------- model : RegressionModel Returns ------- bokeh plot """ hover = HoverTool(tooltips=[ ("#SampleID", "@index"), ]) pred = model.predict() pcvar = model.percent_explained() pred['color'] = 'predicted' # make predictions red raw = model.balances raw['color'] = 'raw' # make raw values blue p = figure(plot_width=400, plot_height=400, tools=[hover, BoxZoomTool(), ResetTool()]) raw_source = ColumnDataSource(raw) pred_source = ColumnDataSource(pred) p.circle(raw.columns[0], raw.columns[1], size=7, source=raw_source, fill_color='blue', legend='raw') p.circle(pred.columns[0], pred.columns[1], size=7, source=pred_source, fill_color='red', legend='predicted') p.title.text = 'Projected Prediction' p.title_location = 'above' p.title.align = 'center' p.title.text_font_size = '18pt' p.xaxis.axis_label = '{} ({:.2%})'.format(pcvar.index[0], pcvar.iloc[0]) p.yaxis.axis_label = '{} ({:.2%})'.format(pcvar.index[1], pcvar.iloc[1]) return p
def plot001(request, **kwargs): ''' Displays a plot Based on sample code : https://bokeh.pydata.org/en/latest/docs/user_guide/categorical.html ''' title = u'Plot001' fruits = [ 'Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries' ] counts = [5, 3, 4, 2, 4, 6] source = ColumnDataSource( data=dict(fruits=fruits, counts=counts, color=Spectral6)) tools = [PanTool(), BoxZoomTool(), SaveTool(), ResetTool()] plot = figure(x_range=fruits, y_range=(0, 9), plot_height=2000, plot_width=2000, title="Fruit Counts", toolbar_location="above", tools=tools, active_drag=None, active_scroll=None, active_tap=None) plot.vbar(x='fruits', top='counts', width=0.9, color='color', legend="fruits", source=source) plot.xgrid.grid_line_color = None plot.legend.orientation = "horizontal" plot.legend.location = "top_center" script_bokeh, div_bokeh = components(plot) return render( request, 'bokeh_mobile_tests/plot001.html', { 'site_title': site_title, 'title': title, 'script_bokeh': script_bokeh, 'div_bokeh': div_bokeh, })
def plotGraph(graph, title=None, graphSavePath=None, networkPath=None): for k, adjacencies in zip(list(graph.nodes.keys()), graph.adjacency()): graph.nodes[k]["degree"] = len(adjacencies[1]) if networkPath is not None: for city in graph.nodes(): graph.nodes[city]["code"] = graph.networkPath.stationList.getCode( city) plot_height = 700 plot = Plot(plot_width=900, plot_height=plot_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = title node_hover_tool = HoverTool( tooltips=[("Miasto", "@index"), ("Kod miasta", "@code"), ("Stopien wierzcholka", "@degree")]) plot.add_tools(WheelZoomTool(), PanTool(), SaveTool(), node_hover_tool, BoxZoomTool(), ResetTool()) # , TapTool()) graph_renderer = from_networkx(graph, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=12, fill_color="yellow") graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="blue") graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="red") graph_renderer.edge_renderer.glyph = MultiLine(line_color="green", line_alpha=0.3, line_width=1) graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="blue", line_width=1.2) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="red", line_width=1.2) plot.renderers.append(graph_renderer) columnCities = ColumnDataSource(data=dict(city=list(graph.nodes.keys()))) columnsNetwork = [ TableColumn(field="city", title="Miasto"), ] table = DataTable(source=columnCities, columns=columnsNetwork, width=155, height=plot_height) layout = row(plot, table) if graphSavePath is not None: output_file(graphSavePath, title) show(layout)
def time_series(x_key, y_key, groups, labels, config): """Plot time series with error bands per group.""" # pylint:disable=too-many-function-args kwargs = dict(y_axis_type="log") if config["log_scale"] else {} pic = figure(title="Plot", **kwargs) pic.xaxis.axis_label = x_key pic.yaxis.axis_label = y_key pic.tools = [ PanTool(), BoxZoomTool(), WheelZoomTool(dimensions="height"), WheelZoomTool(dimensions="width"), SaveTool(), ResetTool(), HelpTool(), ] pic.add_tools() if config["individual"]: pic.add_tools( HoverTool(tooltips=[("y", "@y"), ("x", "@x{a}"), ("id", "@id")])) else: pic.add_tools(HoverTool(tooltips=[("y", "@y_mean"), ("x", "@x{a}")])) for label, group, color in zip(labels, groups, bokeh.palettes.cividis(len(labels))): data = group.extract() progresses = [d.progress for d in data if y_key in d.progress.columns] if not progresses: continue x_all, all_ys = filter_and_interpolate(x_key, y_key, progresses) if config["individual"]: plot_individual(pic, x_all, all_ys, data, label, color) else: plot_mean_dispersion( pic, x_all, all_ys, label, color, standard_error=config["standard_error"], ) pic.legend.location = "bottom_left" pic.legend.click_policy = "hide" return pic
def test_box_zoom_height_updates_only_yrange(self, single_plot_page: SinglePlotPage) -> None: plot = _make_plot(BoxZoomTool(dimensions="height")) page = single_plot_page(plot) page.drag_canvas_at_position(plot, 250, 250, 50, 50) page.eval_custom_action() results = page.results assert results['xrstart'] == 0 assert results['xrend'] == 1 assert results['yrstart'] > 0 assert results['yrend'] < 0.5 assert page.has_no_console_errors()
def test_box_zoom_height_clips_to_yrange(self, single_plot_page) -> None: plot = _make_plot(BoxZoomTool(dimensions="height")) page = single_plot_page(plot) page.drag_canvas_at_position(250, 250, 50, 500) page.click_custom_action() results = page.results assert results['xrstart'] == 0 assert results['xrend'] == 1 assert results['yrstart'] == 0 assert results['yrend'] < 0.5 assert page.has_no_console_errors()
def setup_vol_plot(): vol_plot.tools = [PanTool(), ResetTool(), SaveTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool()] vol_plot.toolbar.logo = None vol_plot.toolbar_location = 'right' vol_plot.x_range.follow = "end" vol_plot.x_range.range_padding = 0 vol_plot.xaxis.formatter = date_formatter # Angled display for better reading. vol_plot.xaxis.major_label_orientation = radians(45) vol_plot.segment(x0='center', y0='low', x1='center', y1='high', line_width=0.5, line_color='#CE9178', source=source_volume_bar) vol_plot.quad(left='time0', bottom='open', right='time1', top='close', color='color', source=source_volume_bar)
def test_box_zoom_width_updates_only_xrange(self, single_plot_page): plot = _make_plot(BoxZoomTool(dimensions="width")) page = single_plot_page(plot) page.drag_canvas_at_position(250, 250, 50, 50) page.click_custom_action() results = page.results assert results['xrstart'] > 0.5 assert results['xrend'] < 1 assert results['yrstart'] == 0 assert results['yrend'] == 1 assert page.has_no_console_errors()
def test_box_zoom_with_corner_origin(self, single_plot_page) -> None: plot = _make_plot(BoxZoomTool()) page = single_plot_page(plot) page.drag_canvas_at_position(100, 100, 200, 200) page.click_custom_action() results = page.results assert results['xrstart'] == pytest.approx(0.25) assert results['xrend'] == pytest.approx(0.75) assert results['yrstart'] == pytest.approx(0.25) assert results['yrend'] == pytest.approx(0.75) assert page.has_no_console_errors()
def test_box_zoom_with_center_origin_clips_to_range(self, single_plot_page): plot = _make_plot(BoxZoomTool(origin="center")) page = single_plot_page(plot) page.drag_canvas_at_position(200, 200, 500, 500) page.click_custom_action() results = page.results assert results['xrstart'] == 0 assert results['xrend'] == 1 assert results['yrstart'] == 0 assert results['yrend'] == 1 assert page.has_no_console_errors()
def large_plot(n): from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.models.widgets.layouts import VBox from bokeh.models.glyphs import Line vbox = VBox() objects = set([vbox]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool(plot=plot) wheel_zoom = WheelZoomTool(plot=plot) box_zoom = BoxZoomTool(plot=plot) box_select = BoxSelectTool(plot=plot) box_selection = BoxSelectionOverlay(tool=box_select) plot.renderers.append(box_selection) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot) reset = ResetTool(plot=plot) tools = [ pan, wheel_zoom, box_zoom, box_select, resize, previewsave, reset ] plot.tools.extend(tools) vbox.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.tool_events, box_selection ] + tickers + tools) return vbox, objects
def create_village_map(survey): s = survey[["village_name", "_gps_point_latitude", "_gps_point_longitude"]] g = s.groupby("village_name") mean = g.agg([np.mean]) mean = mean.reset_index() mean.columns = ['_'.join(col).strip() for col in mean.columns.values] mean.columns = ['vn', 'lat_mean', 'lon_mean'] x_range = Range1d() y_range = Range1d() map_options = GMapOptions(lat=-2.588, lng=140.5170, zoom=11) plot = GMapPlot(x_range=x_range, y_range=y_range, map_options=map_options, title="Lake Sentani") dot_source = ColumnDataSource(data=dict( lat=[float(x) for x in survey['_gps_point_latitude']], lon=[float(y) for y in survey['_gps_point_longitude']], uuid=[str(x) for x in survey['_uuid']], vName=[str(x) for x in survey['village_name']], size=[.0001 for x in survey['_uuid']], )) plot.map_options.map_type = "terrain" circle = Circle(x='lon', y='lat', radius='size', fill_color='red', fill_alpha=0.9) plot.add_glyph(dot_source, circle) text_source = ColumnDataSource( data=dict(vn=[str(x) for x in mean['vn']], lat=[float(x) for x in mean['lat_mean']], lon=[float(x) for x in mean['lon_mean']])) text = Text(x="lon", y="lat", text="vn", text_color="maroon") plot.add_glyph(text_source, text) reset = ResetTool() pan = PanTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() plot.add_tools(pan, wheel_zoom, box_zoom, reset) xaxis = LinearAxis(axis_label="lon.", major_tick_in=0) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat.", major_tick_in=0) plot.add_layout(yaxis, 'left') return plot
def coverage(request): """ View that returns the vaccination coverage page. """ form = CoverageForm(request.POST) vax = 'Dtap' if form.is_valid(): vax = str(form.cleaned_data['vaccine']) all_data = pd.DataFrame.from_records(VaxCoverage.objects.all().values()) plot_data = vaxplot.VaxPlot(df=all_data, color='black', vaccine=vax, shade_color='#7570B3', shade_alpha=0.2) if vax == 'No Vaccinations': ptitle = 'Children Age 19-35 Months Who Received No Vaccinations' else: ptitle = '%s Vaccination Coverage in Children Age 19-35 Months' % vax hover = HoverTool(tooltips=[ ("Year", "$x{int}"), ("Coverage:", "$y"), ]) plt = figure(plot_width=800, plot_height=400, tools=[hover], title=ptitle) plt.line(plot_data.x_values, plot_data.y_values, color=plot_data.color) plt.patch(plot_data.shadex_values, plot_data.shadey_values, color=plot_data.shade_color, fill_alpha=plot_data.shade_alpha, line_alpha=plot_data.shade_alpha) plt.xaxis.axis_label = "Year" plt.yaxis.axis_label = "Coverage" plt.add_tools(BoxZoomTool()) plt.add_tools(ResetTool()) script, div = components(plt) return render(request, 'vaxcharts/coverage.html', { 'script': script, 'div': div, 'form': form })
def _plot_gene_html(counting_value_list, gene_name): output_file(gene_name + '.html') plot_html = figure( title=gene_name, x_axis_label='Fraction number', y_axis_label='Normalized and scaled to max read counts', tools=[BoxZoomTool(), ResetTool(), PanTool(), WheelZoomTool()]) plot_html.yaxis.axis_label_text_font_size = "15pt" plot_html.xaxis.axis_label_text_font_size = "15pt" plot_html.title.text_font_size = '15pt' plot_html.toolbar.logo = None y_axis = range(1, 22) plot_html.line(y_axis, counting_value_list) show(plot_html)