def _make_plot(num_objects=0, drag=True, vertices=False): source = ColumnDataSource(dict(xs=[[1, 2]], ys=[[1, 1]])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyDrawTool(num_objects=num_objects, drag=drag, renderers=[renderer]) if vertices: psource = ColumnDataSource(dict(x=[], y=[])) prenderer = plot.add_glyph(psource, Circle(x='x', y='y', size=10)) tool.vertex_renderer = prenderer plot.add_tools(tool) plot.toolbar.active_multi = tool code = RECORD("xs", "source.data.xs") + RECORD("ys", "source.data.ys") plot.add_tools(CustomAction(callback=CustomJS(args=dict(source=source), code=code))) plot.toolbar_sticky = False return plot
def _make_plot(num_objects=0, drag=True, vertices=False): source = ColumnDataSource(dict(xs=[[1, 2]], ys=[[1, 1]])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyDrawTool(num_objects=num_objects, drag=drag, renderers=[renderer]) if vertices: psource = ColumnDataSource(dict(x=[], y=[])) prenderer = plot.add_glyph(psource, Circle(x='x', y='y', size=10)) tool.vertex_renderer = prenderer plot.add_tools(tool) plot.toolbar.active_multi = tool code = RECORD("xs", "source.data.xs", final=False) + RECORD("ys", "source.data.ys") plot.add_tools(CustomAction(callback=CustomJS(args=dict(source=source), code=code))) plot.toolbar_sticky = False return plot
def initialize(self, plot_id=None): try: from bokeh.models import PolyDrawTool except: param.main.warning('PolyDraw requires bokeh >= 0.12.14') return plot = self.plot stream = self.streams[0] kwargs = {} if stream.num_objects: if bokeh_version >= '1.0.0': kwargs['num_objects'] = stream.num_objects else: param.main.warning( 'Specifying num_objects to PointDraw stream ' 'only supported for bokeh versions >=1.0.0.') if stream.show_vertices: if bokeh_version >= '1.0.0': vertex_style = dict({'size': 10}, **stream.vertex_style) r1 = plot.state.scatter([], [], **vertex_style) kwargs['vertex_renderer'] = r1 else: param.main.warning( 'Enabling vertices on the PointDraw stream ' 'only supported for bokeh versions >=1.0.0.') poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), empty_value=stream.empty_value, renderers=[plot.handles['glyph_renderer']], **kwargs) plot.state.tools.append(poly_tool) self._update_cds_vdims() super(PolyDrawCallback, self).initialize(plot_id)
def initialize(self, plot_id=None): plot = self.plot stream = self.streams[0] cds = self.plot.handles['cds'] glyph = self.plot.handles['glyph'] renderers = [plot.handles['glyph_renderer']] kwargs = {} if stream.num_objects: kwargs['num_objects'] = stream.num_objects if stream.show_vertices: vertex_style = dict({'size': 10}, **stream.vertex_style) r1 = plot.state.scatter([], [], **vertex_style) kwargs['vertex_renderer'] = r1 if stream.styles: self._create_style_callback(cds, glyph) if stream.tooltip: kwargs[CUSTOM_TOOLTIP] = stream.tooltip if stream.empty_value is not None: kwargs['empty_value'] = stream.empty_value poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), renderers=renderers, **kwargs) plot.state.tools.append(poly_tool) self._update_cds_vdims(cds.data) super().initialize(plot_id)
def __init__( self, dataf, labels, x, y, size=5, alpha=0.5, width=400, height=400, color=None, legend=True, ): self.uuid = str(uuid.uuid4())[:10] self.x = x self.y = y self.plot = figure(width=width, height=height, title=f"{x} vs. {y}") self.color_column = labels if isinstance(labels, str) else color self._colors = ["red", "blue", "green", "purple", "cyan"] self.legend = legend if isinstance(labels, str): self.labels = list(dataf[labels].unique()) d = {k: col for k, col in zip(self.labels, self._colors)} dataf = dataf.assign(color=[d[lab] for lab in dataf[labels]]) self.source = ColumnDataSource(data=dataf) else: if not self.color_column: dataf = dataf.assign(color=["gray" for _ in range(dataf.shape[0])]) else: color_labels = list(dataf[self.color_column].unique()) d = {k: col for k, col in zip(color_labels, self._colors)} dataf = dataf.assign(color=[d[lab] for lab in dataf[self.color_column]]) self.source = ColumnDataSource(data=dataf) self.labels = labels if len(self.labels) > 5: raise ValueError("We currently only allow for 5 classes max.") self.plot.circle( x=x, y=y, color="color", source=self.source, size=size, alpha=alpha ) # Create all the tools for drawing self.poly_patches = {} self.poly_draw = {} for k, col in zip(self.labels, self._colors): self.poly_patches[k] = self.plot.patches( [], [], fill_color=col, fill_alpha=0.4, line_alpha=0.0 ) icon_path = pathlib.Path(resource_filename("hulearn", f"images/{col}.png")) self.poly_draw[k] = PolyDrawTool( renderers=[self.poly_patches[k]], custom_icon=icon_path ) c = self.plot.circle([], [], size=5, color="black") edit_tool = PolyEditTool( renderers=list(self.poly_patches.values()), vertex_renderer=c ) self.plot.add_tools(*self.poly_draw.values(), edit_tool) self.plot.toolbar.active_tap = self.poly_draw[self.labels[0]]
def initialize(self): try: from bokeh.models import PolyDrawTool except: param.main.warning('PolyDraw requires bokeh >= 0.12.14') return plot = self.plot poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), empty_value=self.streams[0].empty_value, renderers=[plot.handles['glyph_renderer']]) plot.state.tools.append(poly_tool) super(PolyDrawCallback, self).initialize()
def modify_doc(doc): source = ColumnDataSource(dict(xs=[[1, 2]], ys=[[1, 1]])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyDrawTool(renderers=[renderer]) plot.add_tools(tool) plot.toolbar.active_multi = tool div = Div(text='False') def cb(attr, old, new): if cds_data_almost_equal(new, expected): div.text = 'True' source.on_change('data', cb) code = RECORD("matches", "div.text") plot.add_tools(CustomAction(callback=CustomJS(args=dict(div=div), code=code))) doc.add_root(column(plot, div))
def initialize(self, plot_id=None): try: from bokeh.models import PolyDrawTool except: param.main.warning('PolyDraw requires bokeh >= 0.12.14') return plot = self.plot poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), empty_value=self.streams[0].empty_value, renderers=[plot.handles['glyph_renderer']]) plot.state.tools.append(poly_tool) data = dict(plot.handles['source'].data) for stream in self.streams: stream.update(data=data) super(CDSCallback, self).initialize(plot_id)
def initialize(self): try: from bokeh.models import PolyDrawTool except: param.main.warning('PolyDraw requires bokeh >= 0.12.14') return plot = self.plot poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), empty_value=self.streams[0].empty_value, renderers=[plot.handles['glyph_renderer']]) plot.state.tools.append(poly_tool) element = plot.current_frame x, y = element.dimensions('key', label=True) data = dict(plot.handles['source'].data) for stream in self.streams: stream.update(data=data)
def modify_doc(doc): source = ColumnDataSource(dict(xs=[[1, 2]], ys=[[1, 1]])) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyDrawTool(renderers=[renderer]) plot.add_tools(tool) plot.toolbar.active_multi = tool div = Div(text='False') def cb(attr, old, new): if cds_data_almost_equal(new, expected): div.text = 'True' source.on_change('data', cb) code = RECORD("matches", "div.text") plot.tags.append( CustomJS(name="custom-action", args=dict(div=div), code=code)) doc.add_root(column(plot, div))
def initialize(self, plot_id=None): plot = self.plot stream = self.streams[0] kwargs = {} if stream.num_objects: kwargs['num_objects'] = stream.num_objects if stream.show_vertices: vertex_style = dict({'size': 10}, **stream.vertex_style) r1 = plot.state.scatter([], [], **vertex_style) kwargs['vertex_renderer'] = r1 if stream.styles: self._create_style_callback(plot.handles['cds'], plot.handles['glyph'], 'xs') poly_tool = PolyDrawTool(drag=all(s.drag for s in self.streams), empty_value=stream.empty_value, renderers=[plot.handles['glyph_renderer']], **kwargs) plot.state.tools.append(poly_tool) self._update_cds_vdims() super(PolyDrawCallback, self).initialize(plot_id)
def create_poly_draw_tool(plot: figure): p1 = plot.patches([], [], fill_alpha=0.4) return PolyDrawTool(renderers = [p1])
from bokeh.models import PolyDrawTool, PolyEditTool from bokeh.plotting import figure, output_file, show output_file("tools_poly_edit.html") p = figure(x_range=(0, 10), y_range=(0, 10), width=400, height=400, title='Poly Edit Tool') p1 = p.patches([], [], fill_alpha=0.4) p2 = p.patches([[1, 2, 3]], [[3, 5, 2]], fill_color='green', fill_alpha=0.4) c1 = p.circle([], [], size=10, color='red') draw_tool = PolyDrawTool(renderers=[p1, p2]) edit_tool = PolyEditTool(renderers=[p1, p2], vertex_renderer=c1) p.add_tools(draw_tool, edit_tool) p.toolbar.active_drag = edit_tool show(p)
def plot_stock_price(stock, symbol, lengthOfTime): p = figure(plot_width=P_WIDTH, plot_height=P_HEIGHT, tools=TOOLS, title=symbol + ' (' + lengthOfTime + ')', toolbar_location='above') # green or red inc = stock.data['Close'] >= stock.data['Open'] dec = stock.data['Open'] > stock.data['Close'] view_inc = CDSView(source=stock, filters=[BooleanFilter(inc)]) view_dec = CDSView(source=stock, filters=[BooleanFilter(dec)]) # relabel the x-axis to avoid gaps on days of no trading p.xaxis.major_label_overrides = { i + int(stock.data['index'][0]): date.strftime('%b %d') for i, date in enumerate(pd.to_datetime(stock.data["date"])) } p.xaxis.bounds = (stock.data['index'][0], stock.data['index'][-1]) # Wicks p.segment(x0='index', x1='index', y0='low', y1='high', color=GREY, source=stock, view=view_inc) p.segment(x0='index', x1='index', y0='low', y1='high', color=GREY, source=stock, view=view_dec) # Candlesticks p.vbar(x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=GREEN, line_color=GREEN, source=stock, view=view_inc, name="price") p.vbar(x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=RED, line_color=RED, source=stock, view=view_dec, name="price") # Simple Moving Average p.line(df['index'], df['sma20'], color='yellow', alpha=0.7) # Volume bars p.vbar(x='index', width=VBAR_WIDTH / 2, top='volHeight', bottom=0, fill_color=GREEN, line_color=GREEN, source=stock, view=view_inc, name="price") p.vbar(x='index', width=VBAR_WIDTH / 2, top='volHeight', bottom=0, fill_color=RED, line_color=RED, source=stock, view=view_dec, name="price") # graph formatting p.yaxis.formatter = NumeralTickFormatter(format='0,0[.]000') p.x_range.range_padding = 0.05 p.xaxis.ticker.desired_num_ticks = 40 p.xaxis.major_label_orientation = 3.14 / 4 p.xgrid.grid_line_alpha = 0.1 p.ygrid.grid_line_alpha = 0.1 # hover and draw tool price_hover = p.select(dict(type=HoverTool)) line = p.multi_line([[0, 0]], [[0, 0]], line_width=1, alpha=0.8, color=(255, 255, 255)) draw_tool_line = PolyDrawTool(renderers=[line]) p.add_tools(draw_tool_line) # Tooltips price_hover.names = ["price"] price_hover.tooltips = [("Date", "@date{%d-%m-%Y}"), ("Open", "@Open{0,0.00}"), ("Close", "@Close{0,0.00}"), ("Volume", "@volume{0.00 a}")] price_hover.formatters = {"@date": 'datetime'} return p
from bokeh.plotting import figure, output_file, show from bokeh.models import PolyDrawTool output_file("tools_poly_draw.html") p = figure(x_range=(0, 10), y_range=(0, 10), width=400, height=400, title='Poly Draw Tool') p1 = p.patches([[2, 5, 8]], [[2, 8, 2]], line_width=0, alpha=0.4) l1 = p.multi_line([[1, 9]], [[5, 5]], line_width=5, alpha=0.4, color='red') draw_tool_p1 = PolyDrawTool(renderers=[p1]) draw_tool_l1 = PolyDrawTool(renderers=[l1]) p.add_tools(draw_tool_p1, draw_tool_l1) p.toolbar.active_drag = draw_tool_p1 show(p)
def create_image_figure( image_source: ColumnDataSource, roi_source: ColumnDataSource, vector_source: ColumnDataSource, ) -> Figure: try: image = image_source.data['image'][0] width = image.shape[1] height = image.shape[0] except IndexError: width = 800 height = 800 plot = figure( plot_width=min(width, 800), plot_height=min(height, 800), x_range=[0, width], y_range=[0, height], title='Selected Image', name='image_figure', ) plot.image( image='image', x=0, y=0, dw='dw', dh='dh', source=image_source, palette='Spectral11', name='image_plot', ) hover = HoverTool(tooltips=[('x', '$x'), ('y', '$y'), ('value', '@image')]) r1 = plot.rect( x='x', y='y', width='width', height='height', source=roi_source, fill_alpha=0.5, fill_color='#DAF7A6', name='rois', ) lines = plot.multi_line( xs='xs', ys='ys', source=vector_source, line_color='red', line_width=2, name='vectors', ) circles = plot.circle( x=[], y=[], size=10, color='yellow', ) plot.tools = [ hover, BoxEditTool(renderers=[r1]), PolyDrawTool(renderers=[lines]), PolyEditTool(renderers=[lines], vertex_renderer=circles), ] plot.toolbar.active_inspect = [] return plot