def plot_daily_income_per_month(income_summary, page_obj, freq='daily'): title = page_obj.object_list[0] colors = ["#c9d9d3", "#718dbf", "#e84d60"] stacks = list(income_summary.columns.drop('Total')) if freq == 'monthly': income_summary.index = [ hf.first_day_of_month(x) for x in income_summary.index ] income_summary.index = income_summary.index.rename('date') source = ColumnDataSource(income_summary) plot = figure(title=title, plot_width=500, plot_height=400, x_axis_type="datetime") renderers = plot.varea_stack(stacks, x='date', source=source, color=colors[:len(stacks)], legend=[x + ' ' for x in stacks]) plot.legend.location = 'top_left' plot.left[0].formatter.use_scientific = False plot.add_tools(BoxZoomTool()) plot.add_tools(ResetTool()) hover = HoverTool(tooltips=[('Date', '@date')]) plot.add_tools(hover) script, div = components(plot) return script, div
def render_karate_graph(): G = nx.karate_club_graph() 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.spectral_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) return plot
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() self.lasso_select = LassoSelectTool( renderers=self.circles, # default = all available renderers select_every_mousemove=False, # to enhance performance ) self.lasso_select.overlay.line_alpha=0.9 self.lasso_select.overlay.line_color="black" self.lasso_select.overlay.fill_alpha=0.2 self.lasso_select.overlay.fill_color="grey" hover = self._get_hover_tool() self.tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*self.tools)
def makedoc(doc): source = ColumnDataSource(dataframe) image_holder = ColumnDataSource({ 'image': [], 'x': [], 'y': [], 'dx': [], 'dy': [] }) tools = [ ResetTool(), PanTool(), WheelZoomTool(), TapTool(), BoxSelectTool(), PolySelectTool(), UndoTool(), RedoTool() ] pca = figure(title='PCA', x_range=[minx - 0.05 * rangex, maxx + 0.05 * rangex], y_range=[miny - 0.05 * rangey, maxy + 0.05 * rangey], sizing_mode='scale_both', tools=tools) glyphs = pca.circle(source=source, x='x', y='y') sel = figure(title='Selected image', x_range=[0, 1], y_range=[0, 1], sizing_mode='scale_both') image_canvas = sel.image_rgba('image', 'x', 'y', 'dx', 'dy', source=image_holder) def load_selected(attr, old, new): print('new index: ', new.indices) if len(new.indices) == 1: # could be empty selection update_image_canvas_single(new.indices[0], data=dataframe, source=image_holder) elif len(new.indices) > 1: update_image_canvas_multi(new.indices, data=dataframe, source=image_holder) glyphs.data_source.on_change('selected', load_selected) fig = row([pca, sel], sizing_mode='stretch_both') doc.title = 'Bokeh microscopium app' doc.add_root(fig)
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() # TODO: add only to one plot, maybe with n_plot self.lasso_select = LassoSelectTool( renderers=self.circles, # default all available renderers select_every_mousemove=False, # enhance performance ) tooltips = ''' <style> .bk-tooltip>div:not(:nth-child(-n+5)) {{ display:none; }} /* .bk-tooltip-custom + .bk-tooltip-custom {{ display: none; sometimes everything is hidden with this }} */ .bk-tooltip>div {{ background-color: #dff0d8; padding: 5px; }} </style> <b>INDEX: </b> @INDEX <br> <b>{x}: </b> @{x} <br> <b>{x}_FLAG_W: </b> @{x}_FLAG_W <br> <b>{y}: </b> @{y} <br> <b>{y}_FLAG_W: </b> @{y}_FLAG_W <br> '''.format(x=self.x, y=self.y) hover = HoverTool( # TODO: try to make this toggleable renderers=self.circles, toggleable=True, mode='mouse', tooltips=tooltips, ) tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*tools)
def plot_pulses2(self, km=False): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from bokeh.resources import CDN from bokeh.embed import components from bokeh.mpl import to_bokeh from bokeh.models.tools import WheelZoomTool, ResetTool, PanTool, HoverTool, SaveTool lines = self.get_lines() N = len(lines) npoints = self.total_units / self.km2unit if km else self.total_units fig = plt.figure(figsize=(12, 2 + N * 0.5)) ax = fig.add_subplot(111) labels = ['IPP'] for i, line in enumerate(lines): labels.append(line.get_name(channel=True)) l = ax.plot((0, npoints), (N - i - 1, N - i - 1)) points = [(tup[0], tup[1] - tup[0]) for tup in line.pulses_as_points(km=km) if tup != (0, 0)] ax.broken_barh(points, (N - i - 1, 0.5), edgecolor=l[0].get_color(), facecolor='none') n = 0 f = ((self.ntx + 50) / 100) * 5 if ( (self.ntx + 50) / 100) * 10 > 0 else 2 for x in np.arange(0, npoints, self.ipp if km else self.ipp * self.km2unit): if n % f == 0: ax.text(x, N, '%s' % n, size=10) n += 1 labels.reverse() ax.set_yticks(range(len(labels))) ax.set_yticklabels(labels) ax.set_xlabel = 'Units' plot = to_bokeh(fig, use_pandas=False) plot.tools = [ PanTool(dimensions=['width']), WheelZoomTool(dimensions=['width']), ResetTool(), SaveTool() ] plot.toolbar_location = "above" return components(plot, CDN)
def addplot(self, curve, *args): TOOLTIPS = [ ("(curve)", "($name)"), ("(value)", "($x)")] logIndex=len(self.plotlist) r = lambda: random.randint(0,255) colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r()) if self.unitDict[curve] in ('ohmm', 'OHMM'): self.figDict["fig{0}".format(logIndex)]=figure(x_axis_type="log", x_axis_location='above') else: self.figDict["fig{0}".format(logIndex)] = figure(tooltips=TOOLTIPS, x_axis_location='above') # Define 1st LHS y-axis self.figDict["fig{0}".format(logIndex)].yaxis.axis_label = str(self.curvename[0])+' (' + str(self.unitDict[self.curvename[0]])+ ')' self.figDict["fig{0}".format(logIndex)].y_range = Range1d(start=max(self.df[self.curvename[0]]), end=min(self.df[self.curvename[0]]), bounds=(None,None)) # Define x-axis self.figDict["fig{0}".format(logIndex)].xaxis.axis_label = str(curve) + ' ('+ str(self.unitDict[curve])+')' self.figDict["fig{0}".format(logIndex)].x_range = Range1d(start=min(self.df[curve]), end=max(self.df[curve])) #fig.xaxis.ticker=SingleIntervalTicker(interval=30) self.figDict["fig{0}".format(logIndex)].xaxis.axis_label_text_color = colr # Define x-axis curve self.figDict["fig{0}".format(logIndex)].line( y = self.df[self.curvename[0]], x = self.df[curve], name = str(curve), color = colr ) for curves in args: colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r()) #add more x-axis self.figDict["fig{0}".format(logIndex)].extra_x_ranges [str(curves)] = Range1d(start=min(self.df[curves]), end=max(self.df[curves])) self.figDict["fig{0}".format(logIndex)].add_layout(LinearAxis( x_range_name=curves, axis_label=str(curves) + ' ('+ str(self.unitDict[curves])+')', axis_label_text_color = colr), 'above') # Define other x-axis curve self.figDict["fig{0}".format(logIndex)].line( y = self.df[self.curvename[0]], x = self.df[curves], name = curves, x_range_name = str(curves), color = colr ) self.plotlist.append(self.figDict["fig{0}".format(logIndex)]) self.figDict["fig{0}".format(logIndex)].tools=[WheelZoomTool(),PanTool(),ResetTool()] self.figDict["fig{0}".format(logIndex)].add_tools(HoverTool(tooltips=TOOLTIPS)) return self.figDict["fig{0}".format(logIndex)]
def newplot(self, data, log, unit, *args): curve= data[log] TOOLTIPS = [ ("(curve)", "($name)"), ("(value)", "($x)")] logIndex=len(self.plotlist) r = lambda: random.randint(0,255) colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r()) self.figDict["fig{0}".format(logIndex)] = figure(tooltips=TOOLTIPS, x_axis_location='above') # Define 1st LHS y-axis self.figDict["fig{0}".format(logIndex)].yaxis.axis_label = str(self.curvename[0])+' (' + str(self.unitDict[self.curvename[0]])+ ')' self.figDict["fig{0}".format(logIndex)].y_range = Range1d(start=max(curve.index), end=min(curve.index), bounds=(None,None)) # Define x-axis self.figDict["fig{0}".format(logIndex)].xaxis.axis_label = str(log) + ' ('+ str(unit)+')' self.figDict["fig{0}".format(logIndex)].x_range = Range1d(start=min(curve), end=max(curve)) #fig.xaxis.ticker=SingleIntervalTicker(interval=30) self.figDict["fig{0}".format(logIndex)].xaxis.axis_label_text_color = colr # Define x-axis curve self.figDict["fig{0}".format(logIndex)].line( y = curve.index, x = curve, name = str(log), color = colr ) for curved in args: curves=data[curved] colr='#{:02x}{:02x}{:02x}'.format(r(), r(), r()) #add more x-axis self.figDict["fig{0}".format(logIndex)].extra_x_ranges [str(curved)] = Range1d(start=min(curves), end=max(curves)) self.figDict["fig{0}".format(logIndex)].add_layout(LinearAxis( x_range_name=curved, axis_label=str(curved) + ' ('+ str(unit)+')', axis_label_text_color = colr), 'above') # Define other x-axis curve self.figDict["fig{0}".format(logIndex)].line( y = curves.index, x = curves, name = curved, x_range_name = str(curved), color = colr ) self.plotlist.append(self.figDict["fig{0}".format(logIndex)]) self.figDict["fig{0}".format(logIndex)].tools=[WheelZoomTool(),PanTool(),ResetTool()] self.figDict["fig{0}".format(logIndex)].add_tools(HoverTool(tooltips=TOOLTIPS)) return self.figDict["fig{0}".format(logIndex)]
def plot_perf( data: pd.DataFrame, mod: DirectReinforcementModel, tail: int = config["chartTail"], modelName: str = f"{config['modelName']} v{config['modelVersion']}", ) -> str: # returns HTML str data = data.tail(tail) data = DataVisualiser.add_positions_to_data(mod, data) data = DataVisualiser.add_performance_to_data(mod, data) p1 = figure( x_axis_type="datetime", title="Cumulative Returns by Strategy", plot_width=800, plot_height=500, ) p1.grid.grid_line_alpha = 0.3 p1.xaxis.axis_label = "Date" p1.yaxis.axis_label = "Cumulative Returns" p1.toolbar.logo = None p1.tools = [ PanTool(), # SaveTool(), WheelZoomTool(), ResetTool(), CrosshairTool(), ] p1.line( # pylint: disable=too-many-function-args datet(data.closeTimeIso), data.modelReturnsCumSum, color="#33A02C", legend_label=modelName, ) p1.line( # pylint: disable=too-many-function-args datet(data.closeTimeIso), data.buyHoldReturns, color="#FB9A99", legend_label="HODL", ) return file_html(p1, CDN), data
def plot_stacked_area(df, stack_category, x_axis, colors, title='', xaxis_type=''): data = {'x_axis': x_axis} for cat in stack_category: data[cat] = list(df[cat].values) if xaxis_type == 'datetime': p = figure(x_range=x_axis, plot_height=350, title=title, toolbar_location='below', tools="pan,wheel_zoom,box_zoom,reset", tooltips="$name - @x_axis: @$name", x_axis_type='datetime') else: p = figure(x_range=x_axis, plot_height=350, title=title, toolbar_location='below', tools="pan,wheel_zoom,box_zoom,reset", tooltips="$name @x_axis: @$name") renderers = p.vbar_stack(stack_category, x="x_axis", width=0.9, color=colors, source=data, legend=[bvalue(x) for x in stack_category]) p.left[0].formatter.use_scientific = False p.add_tools(BoxZoomTool()) p.add_tools(ResetTool()) script, div = components(p) return script, div
def render_from_fb_combined(): print('rendering from facebook_combined.txt') df = pd.read_csv('facebook_combined.txt', sep=" ", header=None) G = nx.from_pandas_edgelist(df.head(1000), 0, 1) print(nx.info(G)) plot = Plot(background_fill_color="white", sizing_mode="stretch_both", x_range=Range1d(-0.5, 0.5), y_range=Range1d(-0.5, 0.5)) 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_alpha=0.8, line_width=1) plot.add_tools(WheelZoomTool()) plot.add_tools(ResetTool()) plot.add_tools(PanTool()) plot.add_tools(HoverTool( tooltips=[("user", "datracka"), ("url", "https://twitter.com/datracka")])) plot.add_tools(PointDrawTool( renderers=[], empty_value='black')) plot.axis.axis_line_width = 0 plot.grid.grid_line_width = 0 plot.xaxis.major_tick_line_color = None # turn off x-axis major ticks plot.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks plot.xaxis.major_label_text_color = None # Remove label x axis plot.yaxis.major_label_text_color = None # Remove label x axis plot.border_fill_color = None plot.outline_line_color = None plot.renderers.append(graph_renderer) return plot
def __create_tools(cls, **hoverkwargs): return [ TapTool(), BoxSelectTool(dimensions='width'), BoxSelectTool(dimensions='height'), BoxSelectTool(), WheelZoomTool(), BoxZoomTool(), ResetTool(), SaveTool(), HoverTool(tooltips=[('workflow', '@Workflow'), ('activity', '@Activity'), ('result', '@Result'), ('duration', '@DurationStr'), ('started', '@StartedOnTimestampStr'), ('ended', '@EndedOnTimeStampStr')], formatters={ 'started': 'printf', 'ended': 'printf' }, show_arrow=True, **hoverkwargs) ]
def create_bk_fig(x=None, xlab=None, x_min=None, x_max=None, ylab=None, fh=None, fw=None, title=None, pw=None, ph=None, x_axis_type="linear", y_axis_type="linear", x_name=None, y_name=None, **kwargs): """ Generates a bokeh figure Parameters ---------- x :obj:`DataArray` Contains x-axis data xlab : :obj:`str` X-axis label x_min : :obj:`float` Min x value x_max : :obj:`float` Max x value ylab : :obj:`str` Y-axis label fh: :obj:`int` True height of figure without legends, axes titles etc fw: :obj:`int` True width of figure without legends, axes etc title: :obj:`str` Title of plot pw: :obj:`int` Plot width including legends, axes etc ph: :obj:`int` Plot height including legends, axes etc x_axis_type: :obj:`str` Type of x-axis can be linear, log, or datetime y_axis_type: :obj:`str` Can be linear, log or datetime x_name: :obj:`str` Name of the column used for the x-axis. Mostly used to form tooltips y_name: :obj:`str` Name of the column used for the y-axis. Also used for tooltips add_grid: :obj:`bool` Whether or not to add grid add_title: :obj:`bool` Whether or not to add title to plot add_xaxis: :obj:`bool` Whether or not to add x-axis and tick marks add_yaxis: :obj:`bool` Add y-axis or not fix_plotsize: :obj:`bool` Enforce certain dimensions on plot. This is useful for ensuring a plot is not obscure by axes and other things. If activated, plot's dimensions will not be responsive. It utilises fw and fh. Returns ------- p : :obj:`Plot` A bokeh Plot object """ add_grid = kwargs.pop("add_grid", False) add_title = kwargs.pop("add_title", True) add_xaxis = kwargs.pop("add_xaxis", False) add_yaxis = kwargs.pop("add_yaxis", False) fix_plotsize = kwargs.pop("fix_plotsize", True) # addition plot specs pl_specs = kwargs.pop("pl_specs", {}) # additional axis specs ax_specs = kwargs.pop("ax_specs", {}) # ticker specs ti_specs = kwargs.pop("ti_specs", {}) plot_specs = dict(background="white", border_fill_alpha=0.1, border_fill_color="white", min_border=3, name="plot", outline_line_dash="solid", outline_line_width=2, outline_line_color="#017afe", outline_line_alpha=0.4, output_backend="canvas", sizing_mode="stretch_width", title_location="above", toolbar_location="above") plot_specs.update(pl_specs) axis_specs = dict(minor_tick_line_alpha=0, axis_label_text_align="center", axis_label_text_font="monospace", axis_label_text_font_size="10px", axis_label_text_font_style="normal", major_label_orientation="horizontal") axis_specs.update(ax_specs) tick_specs = dict(desired_num_ticks=5) tick_specs.update(ti_specs) # Define frame width and height # This is the actual size of the plot without the titles et al if fix_plotsize and not(fh or fw): fw = int(0.98 * pw) fh = int(0.93 * ph) # define the axes ranges x_range = DataRange1d(name="p_x_range", only_visible=True) y_range = DataRange1d(name="p_y_range", only_visible=True) if x_min is not None and x_max is not None and x_name.lower() in ["channel", "frequency"]: x_range = Range1d(name="p_x_range", start=x_min, end=x_max) y_range.only_visible = False # define items to add on the plot p_htool = HoverTool(tooltips=[(x_name, "$x"), (y_name, "$y")], name="p_htool", point_policy="snap_to_data") if x_name.lower() == "time": p_htool.tooltips[0] = (x_name, "$x{%d-%m-%Y %H:%M}") p_htool.formatters = {"$x": "datetime"} p_toolbar = Toolbar(name="p_toolbar", tools=[p_htool, BoxSelectTool(), BoxZoomTool(), # EditTool(), # BoxEditTool(), # RangeTool(), LassoSelectTool(), PanTool(), ResetTool(), SaveTool(), UndoTool(), WheelZoomTool()]) p_ticker = BasicTicker(name="p_ticker", **tick_specs) # select the axis scales for x and y if x_axis_type == "linear": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = LinearAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = DatetimeAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "log": x_scale = LogScale(name="p_x_scale") p_x_axis = LogAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) if y_axis_type == "linear": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = LinearAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = DatetimeAxis(axis_label=xlab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif y_axis_type == "log": y_scale = LogScale(name="p_y_scale") # define the axes and tickers p_y_axis = LogAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) # Create the plot object p = Plot(plot_width=pw, plot_height=ph, frame_height=fh, frame_width=fw, toolbar=p_toolbar, x_range=x_range, x_scale=x_scale, y_range=y_range, y_scale=y_scale, **plot_specs) if add_title: p_title = Title(align="center", name="p_title", text=title, text_font_size="24px", text_font="monospace", text_font_style="bold",) p.add_layout(p_title, "above") if add_xaxis: p.add_layout(p_x_axis, "below") if add_yaxis: p.add_layout(p_y_axis, "left") if add_grid: p_x_grid = Grid(dimension=0, ticker=p_ticker) p_y_grid = Grid(dimension=1, ticker=p_ticker) p.add_layout(p_x_grid) p.add_layout(p_y_grid) return p
def create_HRDPS_graph(df): source = ColumnDataSource(df) # create plot 1 p1 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') p1.title.text = '48H Temperature' p1.xaxis.axis_label = 'Date/Time' p1.yaxis.axis_label = 'Temperature \N{DEGREE SIGN}C' # add lines glyph_1 = p1.line(x='DATETIME', y='TMP', source=source, color='OrangeRed', line_width=1.5) glyph_1a = p1.scatter(x='DATETIME', y='TMP', source=source, line_color="darkRed", fill_color="OrangeRed", size=4) # tools hover1 = HoverTool(renderers=[glyph_1], tooltips=[('\N{DEGREE SIGN}C', '@TMP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p1.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p1.toolbar.logo = None p1.toolbar.active_drag = None p1.toolbar.active_scroll = None p1.toolbar.active_tap = None p1.add_tools(hover1) # legend 1 legend = Legend(items=[("Temp", [glyph_1, glyph_1a])], location="center", orientation="horizontal") p1.add_layout(legend, 'below') # create tab from plot tab1 = Panel(child=p1, title="Temperature") # create plot 2 p2 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') p2.title.text = '48H Precipitation' p2.xaxis.axis_label = 'Date/Time' p2.yaxis.axis_label = 'Amount (mm/cm)' # Add lines glyph_1 = p2.line(x='DATETIME', y='RQP', source=source, color='blue', line_width=1.5) glyph_1a = p2.scatter(x='DATETIME', y='RQP', source=source, line_color="darkblue", fill_color="blue", size=4) glyph_2 = p2.line(x='DATETIME', y='SQP', source=source, color='lavender', line_width=1.5) glyph_2a = p2.scatter(x='DATETIME', y='SQP', source=source, line_color="lightsteelblue", fill_color="lavender", size=4) p2.varea(x='DATETIME', y1='SQP', source=source, color='GhostWhite', alpha=0.5) band = Band(base='DATETIME', upper='RQP', source=source, level='overlay', fill_alpha=0.3, fill_color='SkyBlue') p2.add_layout(band) # tools hover2a = HoverTool(renderers=[glyph_1], tooltips=[('mm Rain', '@RQP'), ('mm Freezing Rain', '@FQP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') hover2b = HoverTool(renderers=[glyph_2], tooltips=[('cm Snow', '@SQP'), ('mm Ice/Hail', '@IQP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p2.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p2.toolbar.logo = None p2.toolbar.active_drag = None p2.toolbar.active_scroll = None p2.toolbar.active_tap = None p2.add_tools(hover2a, hover2b) # legend 2 legend = Legend(items=[("Rain", [glyph_1, glyph_1a]), ("Snow", [glyph_2, glyph_2a])], location="center", orientation="horizontal") p2.add_layout(legend, 'below') # Create tab from plot tab2 = Panel(child=p2, title="Precipitation") # create plot 3 p3 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') p3.title.text = '48H Wind/Cloud' p3.xaxis.axis_label = 'Date/Time' p3.yaxis.axis_label = 'Speed (km/h) / % Coverage' # Add lines glyph_1 = p3.line(x='DATETIME', y='WS', source=source, color='green', line_width=1.5) glyph_1a = p3.scatter(x='DATETIME', y='WS', source=source, line_color="darkgreen", fill_color="green", size=4) glyph_2 = p3.line(x='DATETIME', y='CLOUD', source=source, color='grey', line_width=1.5) glyph_2a = p3.scatter(x='DATETIME', y='CLOUD', source=source, line_color="darkgrey", fill_color="grey", size=4) band = Band(base='DATETIME', upper='CLOUD', source=source, level='underlay', fill_alpha=0.3, fill_color='lightgrey') p3.add_layout(band) # tools hover3a = HoverTool(renderers=[glyph_1], tooltips=[('Wind Speed', '@WS'), ('Wind Direction', '@WD'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') hover3b = HoverTool(renderers=[glyph_2], tooltips=[('% Coverage', '@CLOUD'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p3.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p3.toolbar.logo = None p3.toolbar.active_drag = None p3.toolbar.active_scroll = None p3.toolbar.active_tap = None p3.add_tools(hover3a, hover3b) # legend 3 legend = Legend(items=[("Wind", [glyph_1, glyph_1a]), ("Cloud", [glyph_2, glyph_2a])], location="center", orientation="horizontal") p3.add_layout(legend, 'below') # Create tab from plot tab3 = Panel(child=p3, title="Wind/Cloud") # merge to final plot plot = Tabs(tabs=[tab1, tab2, tab3]) # return graph html = file_html(plot, CDN) return html
def create_NAM_graph(df): source = ColumnDataSource(df) # Create plot 1 y_overlimit = 0.05 p1 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') if len(df) > 65: p1.title.text = '10 Day Temperature' else: p1.title.text = '3.5 Day Temperature' p1.xaxis.axis_label = 'Date/Time' p1.yaxis.axis_label = 'Temperature \N{DEGREE SIGN}C' # add lines glyph_1 = p1.line(x='DATETIME', y='TMP', source=source, color='OrangeRed', line_width=1.5) glyph_1a = p1.scatter(x='DATETIME', y='TMP', source=source, line_color="darkRed", fill_color="OrangeRed", size=4) p1.y_range = Range1d(df['TMP'].min() * (1 - y_overlimit), df['TMP'].max() * (1 + y_overlimit)) # SECOND AXIS y_column2_range = "HGT_0C_DB" + "_range" p1.extra_y_ranges = { y_column2_range: Range1d(start=df['HGT_0C_DB'].min() * (1 - y_overlimit), end=df['HGT_0C_DB'].max() * (1 + y_overlimit)) } p1.add_layout( LinearAxis(y_range_name=y_column2_range, axis_label='Elevation (m)'), "right") # add lines glyph_2 = p1.line(x='DATETIME', y="HGT_0C_DB", source=source, line_width=1.5, y_range_name=y_column2_range, color="gold") glyph_2a = p1.scatter(x='DATETIME', y='HGT_0C_DB', source=source, y_range_name=y_column2_range, line_color="goldenrod", fill_color="gold", size=4) # tools hover1a = HoverTool(renderers=[glyph_1], tooltips=[('\N{DEGREE SIGN}C', '@TMP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') hover1b = HoverTool(renderers=[glyph_2], tooltips=[('m', '@HGT_0C_DB'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p1.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p1.toolbar.logo = None p1.toolbar.active_drag = None p1.toolbar.active_scroll = None p1.toolbar.active_tap = None p1.add_tools(hover1a, hover1b) # legend 1 legend = Legend(items=[("Temp", [glyph_1, glyph_1a]), ("Frz Lvl", [glyph_2, glyph_2a])], location="center", orientation="horizontal") p1.add_layout(legend, 'below') # create tab from plot tab1 = Panel(child=p1, title="Temperature") # create plot 2 p2 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') if len(df) > 65: p2.title.text = '10 Day Precipitation' else: p2.title.text = '3.5 Day Precipitation' p2.xaxis.axis_label = 'Date/Time' p2.yaxis.axis_label = 'Amount (mm/cm)' # add lines glyph_1 = p2.line(x='DATETIME', y='RQP', source=source, color='blue', line_width=1.5) glyph_1a = p2.scatter(x='DATETIME', y='RQP', source=source, line_color="darkblue", fill_color="blue", size=4) glyph_2 = p2.line(x='DATETIME', y='SQP', source=source, color='lavender', line_width=1.5) glyph_2a = p2.scatter(x='DATETIME', y='SQP', source=source, line_color="lightsteelblue", fill_color="lavender", size=4) p2.varea(x='DATETIME', y1='SQP', source=source, color='GhostWhite', alpha=0.5) band = Band(base='DATETIME', upper='RQP', source=source, level='overlay', fill_alpha=0.3, fill_color='SkyBlue') p2.add_layout(band) # tools hover2a = HoverTool(renderers=[glyph_1], tooltips=[('mm Rain', '@RQP'), ('mm Freezing Rain', '@FQP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') hover2b = HoverTool(renderers=[glyph_2], tooltips=[('cm Snow', '@SQP'), ('mm Ice/Hail', '@IQP'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p2.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p2.toolbar.logo = None p2.toolbar.active_drag = None p2.toolbar.active_scroll = None p2.toolbar.active_tap = None p2.add_tools(hover2a, hover2b) # legend 2 legend = Legend(items=[("Rain", [glyph_1, glyph_1a]), ("Snow", [glyph_2, glyph_2a])], location="center", orientation="horizontal") p2.add_layout(legend, 'below') # create tab from plot tab2 = Panel(child=p2, title="Precipitation") # plot 3 p3 = figure(x_axis_type='datetime', plot_width=600, plot_height=400, toolbar_location='above', sizing_mode='scale_width') if len(df) > 65: p1.title.text = '10 Day Wind/Cloud' else: p1.title.text = '3.5 Day Wind/Cloud' p3.xaxis.axis_label = 'Date/Time' p3.yaxis.axis_label = 'Speed (km/h) / % Coverage' # add lines glyph_1 = p3.line(x='DATETIME', y='WS', source=source, color='green', line_width=1.5) glyph_1a = p3.scatter(x='DATETIME', y='WS', source=source, line_color="darkgreen", fill_color="green", size=4) glyph_2 = p3.line(x='DATETIME', y='CLOUD', source=source, color='grey', line_width=1.5) glyph_2a = p3.scatter(x='DATETIME', y='CLOUD', source=source, line_color="darkgrey", fill_color="grey", size=4) band = Band(base='DATETIME', upper='CLOUD', source=source, level='underlay', fill_alpha=0.3, fill_color='lightgrey') p3.add_layout(band) # tools hover3a = HoverTool(renderers=[glyph_1], tooltips=[('Wind Speed', '@WS'), ('Wind Direction', '@WD'), ('Gusts', '@WG'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') hover3b = HoverTool(renderers=[glyph_2], tooltips=[('% Coverage', '@CLOUD'), ('Time', '@DATETIME{%F %T}')], formatters={'@DATETIME': 'datetime'}, mode='vline') p3.toolbar.logo = None p3.tools = [ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] p3.toolbar.active_drag = None p3.toolbar.active_scroll = None p3.toolbar.active_tap = None p3.add_tools(hover3a, hover3b) # legend 3 legend = Legend(items=[("Wind", [glyph_1, glyph_1a]), ("Cloud", [glyph_2, glyph_2a])], location="center", orientation="horizontal") p3.add_layout(legend, 'below') # tab from plot tab3 = Panel(child=p3, title="Wind/Cloud") # merge tabs into one plot plot = Tabs(tabs=[tab1, tab2, tab3]) # return plot html = file_html(plot, CDN) return html
from bokeh.models.sources import ColumnDataSource from bokeh.models import Range1d, Legend, NumeralTickFormatter, DatetimeTickFormatter, Title from bokeh.models.tools import PanTool, BoxZoomTool, WheelZoomTool, ResetTool, HoverTool from bokeh.layouts import row from bokeh.palettes import Dark2 import datetime import psycopg2 import pandas as pd import numpy as np # Interactive tools to use hover = HoverTool(tooltips=[('Stock Name', '@stock_name'), ('Time', '@timestamp'), ('Price', '@y')]) tools = [PanTool(), BoxZoomTool(), ResetTool(), WheelZoomTool(), hover] name_mapper = dict(NFLX='Netflix', GE='General Electric', NVDA='NVIDIA', INTC='Intel Corporation', AAPL='Apple', AMZN='Amazon') p = figure(title="STOCKSTREAMER v0.0", tools=tools, plot_width=1000, y_range=Range1d(-50, 1200), x_range=Range1d(0, 1), plot_height=680, toolbar_location='below', toolbar_sticky=False)
def plot(): # Read data as if uploaded file is now used, Data set 1 data1 = read_csv('app/static/uploads/Data1.csv', sep=',', skipinitialspace=1) xdata1 = data1.values[:,1] # Extract Data ydata1 = data1.values[:,2] colour1 = ['black']*len(xdata1) # Read data as if uploaded file is now used, Data set 2 data2 = read_csv('app/static/uploads/Data2.csv', sep=',', skipinitialspace=1) xdata2 = data2.values[:,1] ydata2 = data2.values[:,2] colour2 = ['green']*len(xdata2) # Read data as if uploaded file is now used, Data set 3 data3 = read_csv('app/static/uploads/Data3.csv', sep=',', skipinitialspace=1) xdata3 = data3.values[:,1] ydata3 = data3.values[:,2] colour3 = ['red']*len(xdata3) # Prepare Data3 # xdata3 = linspace(0, 100, 10) # ydata3 = sin(10*xdata3) # Data_pandas = DataFrame({'Time': xdata3, # 'Value': ydata3}) # Data_pandas.to_csv('app/static/uploads/Data3.csv') # Assign read data to ColumnDataSource objects sourceData1 = ColumnDataSource(data=dict(x=xdata1, y=ydata1, color=colour1)) sourceData2 = ColumnDataSource(data=dict(x=xdata2, y=ydata2, color=colour2)) sourceData3 = ColumnDataSource(data=dict(x=xdata3, y=ydata3, color=colour3)) my_plot = figure(tools=[BoxSelectTool(dimensions=['width'], select_every_mousemove=True), PanTool(), ResetTool(), WheelZoomTool(), BoxZoomTool()], title='Time series data', x_range=(xdata1.min(), xdata1.max()), y_range=(ydata1.min(), ydata1.max()), width=1200) # Create figure object; DEBUG: select_every_mousemove=False my_plot.extra_y_ranges = {# 'Data1': Range1d(start=ydata1.min(), end=ydata1.max()), 'Data2': Range1d(start=ydata2.min(), end=ydata2.max()), 'Data3': Range1d(start=ydata3.min(), end=ydata3.max())} my_plot.circle(x='x', y='y', color='color', source=sourceData1, size=8, alpha=0.8, legend='Data 1') # Add circle elements (glyphs) to the figure my_plot.circle(x='x', y='y', color='color', source=sourceData2, size=5, alpha=0.8, y_range_name='Data2', legend='Data 2') my_plot.circle(x='x', y='y', color='color', source=sourceData3, size=8, alpha=0.5, y_range_name='Data3', legend='Data 3') my_plot.line(x='x', y='y', color='red', source= sourceData3, alpha=0.5, y_range_name='Data3', legend='Data 3') sourceFit = ColumnDataSource(data=dict(xfit=[], yfit=[])) my_plot.circle(x='xfit', y='yfit', source=sourceFit, color='orange', alpha=0.3) # my_plot.add_layout(LinearAxis(y_range_name='Data1', axis_line_color=colour1[0]), 'left') my_plot.add_layout(LinearAxis(y_range_name='Data2', axis_line_color=colour2[0], axis_line_width=3), 'left') my_plot.add_layout(LinearAxis(y_range_name='Data3', axis_line_color=colour3[0], axis_line_width=3), 'left') # sourceAnnotate = ColumnDataSource(data=dict(text=['Foo', 'Bah'], x=[50, 50], y=[0.5, 0], x_offset=[0,0], y_offset=[0,0], text_font_size=['15pt', '15pt'], # text_color=['orange', 'orange'])) # my_plot.text(source=sourceAnnotate, text='text', x='x', y='y', x_offset='x_offset', y_offset='y_offset', text_font_size='text_font_size', text_color='text_color') sourceData1.callback = CustomJS(args=dict(sourceFit=sourceFit), code=("""FirstOrderEyeball(cb_obj, sourceFit)""")) # sourceData.callback = CustomJS(args=dict(sourceFit=sourceFit, sourceAnnotate=sourceAnnotate), code=("""FirstOrderEyeball(cb_obj, sourceFit, sourceAnnotate)""")) script, div = components(my_plot) # Break figure up into component HTML to be added to template return render_template("int_scatter.html", myScript=script, myDiv=div)
def create_figures(source, source_columns, fig_len=fig_len, fig_height=fig_height, data_colors=data_colors, hover_data=hover_data, alpha=0.6, figure_collector=figure_collector, fig_title=fig_title, sub_title=sub_title): # title = create_text(fig_title, text_color='#2b2d2f', text_font_size='40px', fig_height=60) # sub_title = create_text(sub_title, text_color='grey', text_font_size='20px', fig_height=40) # figure_collector.append(title) # figure_collector.append(sub_title) num_figures = len(source_columns) num = 0 while num < num_figures: # create figure fig = figure(plot_width=fig_len, plot_height=fig_height, x_axis_type='datetime', name='data_series', output_backend="webgl") fig.sizing_mode = 'scale_width' # add tools tools = [ PanTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(), ResetTool() ] fig.add_tools(*tools) # create the scatter plot scatter = Circle(x='publishedAt', y=source_columns[num], line_color=data_colors[num], fill_color=data_colors[num], size=6, fill_alpha=alpha, line_alpha=alpha) scatter_render = fig.add_glyph(source_or_glyph=source, glyph=scatter) # hover only over scatter plot hover = HoverTool(renderers=[scatter_render], tooltips=hover_data, formatters={'@publishedAt': 'datetime'}) fig.add_tools(hover) # open video url on tap scatter points taptool = TapTool(renderers=[scatter_render]) taptool.callback = OpenURL(url=url) fig.add_tools(taptool) # create line plot without hover or top # line = Line(x='publishedAt', y=source_columns[num], line_color=data_colors[num], line_width=2, line_alpha=1) # line_render = fig.add_glyph(source_or_glyph=source, glyph=line) # add series title title = Text(x=data['publishedAt'].min(), y=0.2, text=[figure_titles[num]], text_color=data_colors[num], text_font_size='35px') fig.add_glyph(title) # decrease clutter fig.outline_line_color = None fig.xgrid.grid_line_color = None fig.ygrid.grid_line_color = None fig.yaxis.visible = False fig.xaxis.visible = False # format x-axis ticks fig.xaxis.major_tick_line_color = "grey" fig.xaxis.major_label_text_font_size = "15pt" fig.xaxis.major_label_text_color = "grey" # collect figures in a list figure_collector.append(fig) num += 1 return figure_collector
def plot_corr(self, X, names=None, title='Feature Correlations', width=None, height=None): """Correlation matrix plot Args: X: names: (Default value = None) title: (Default value = 'Feature Correlations') width: (Default value = None) height: (Default value = None) Returns: """ n, d = X.shape xcorr = np.corrcoef(X.T) XX, YY = np.meshgrid(np.arange(1, d + 1), np.arange(1, d + 1)) colors = [] alphas = [] for corr in xcorr.ravel(): if corr > 0: colors.append(self.binary_colors[0]) alphas.append(corr) elif corr < 0: colors.append(self.binary_colors[1]) alphas.append(-corr) else: colors.append('lightgrey') alphas.append(self.alpha) dsource = ColumnDataSource(data=dict(xname=XX.ravel(), yname=YY.ravel(), colors=colors, alphas=alphas, corrs=xcorr.ravel())) hover_tooltips = dict({ 'xname': '@xname', 'yname': '@yname', 'corr': '@corrs' }) f = self._get_figure_instance(title=title, x_range=names, y_range=names, xlabel='', ylabel='', width=width, height=height) f.tools = [PanTool(), ResetTool()] f.add_tools(HoverTool(tooltips=hover_tooltips)) f.grid.grid_line_color = None f.axis.axis_line_color = None f.axis.major_tick_line_color = None f.axis.major_label_text_font_size = "6pt" f.axis.major_label_standoff = 0 f.xaxis.major_label_orientation = -np.pi / 2 f.rect('xname', 'yname', 0.9, 0.9, source=dsource, color='colors', alpha='alphas', line_color=None, hover_line_color='black', hover_color='colors') return f
def __init__(self, dataset, parameters): self.dataset = dataset # Set up the controls self.specials = Selector( name="Specials", kind="specials", css_classes=["specials"], entries={ "Color-magnitude diagram": "cmd", "Period vs. radius": "pr", "Period vs. transit duration": "pdt", }, default="Color-magnitude diagram", ) self.data = Selector( name="Datasets", kind="datasets", css_classes=["data"], entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"}, default="Confirmed Planets", ) self.xaxis = Selector( name="Build-Your-Own", kind="parameters", css_classes=["build-your-own"], entries=parameters, default="ra", title="X Axis", ) self.yaxis = Selector( kind="parameters", css_classes=["build-your-own"], entries=parameters, default="dec", title="Y Axis", ) self.size = Selector( name="Sides", kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Size", none_allowed=True, ) self.color = Selector( kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Color", none_allowed=True, ) # Set up the plot self.source = ColumnDataSource( data=dict(x=[], y=[], size=[], color=[]) ) self.plot = figure( plot_height=600, plot_width=700, title="", tooltips=[("TIC ID", "@ticid")], sizing_mode="scale_both", ) self.plot.circle( x="x", y="y", source=self.source, size="size", color=linear_cmap( field_name="color", palette=Viridis256, low=0, high=1 ), line_color=None, ) self.plot.add_tools( BoxSelectTool(), BoxZoomTool(), LassoSelectTool(), PanTool(), PolySelectTool(), TapTool(), WheelZoomTool(), WheelPanTool(), ZoomInTool(), ZoomOutTool(), HoverTool(), CrosshairTool(), ResetTool(), ) # Register the callback for control in [ self.specials, self.data, self.xaxis, self.yaxis, self.size, self.color, ]: control.widget.on_change("value", self.callback) # Load and display the data self.callback(None, None, None)
from bokeh.models.tools import BoxZoomTool, PanTool, ResetTool from bokeh.plotting import figure, output_file, show # prepare some data x = [1, 2, 3, 4, 5] y = [4, 5, 5, 7, 2] # set output to static HTML file output_file("first_steps.html") # create a plot p = figure( title="Modifying tools example", tools=[BoxZoomTool(), ResetTool()], sizing_mode="stretch_width", max_width=500, plot_height=250, ) # add an additional pan tool # only vertical panning is allowed p.add_tools(PanTool(dimensions="width")) # add a renderer p.circle(x, y, size=10) # show the results show(p)
MULT_HEIGHT = 1.5 MARKERS = [ "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "P", "*", "h", "H", "+", "x", "X", "D", "d" ] COLORS = Category20[ 19] #["red", "yellow", "blue", "green", "rosybrown","darkorange", "fuchsia", "grey", ] TOOLS = [ PanTool(), BoxZoomTool(), WheelZoomTool(), UndoTool(), RedoTool(), ResetTool(), SaveTool(), HoverTool(tooltips=[("Price", "$y"), ("Time", "$x")]) ] NAME_RESULT_SHOW_VARS = "resultat_show_variables_pi_plus_{}_pi_minus_{}.html" #------------------------------------------------------------------------------ # definitions of functions #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # definitions of functions #------------------------------------------------------------------------------ # _____________________________________________________________________________
def setup_plot( self, x_axis_type="linear", y_axis_type="linear", x_flip=False, y_flip=False, ): # Set up the plot self.plot = figure( plot_height=620, min_width=600, title="", x_axis_type=x_axis_type, y_axis_type=y_axis_type, tools="", sizing_mode="stretch_both", ) # Enable Bokeh tools self.plot.add_tools(PanTool(), TapTool(), ResetTool()) # Axes orientation and labels self.plot.x_range.flipped = x_flip self.plot.y_range.flipped = y_flip self.plot.xaxis.axis_label = self.xaxis.value self.plot.yaxis.axis_label = self.yaxis.value # Plot the data self.plot.circle( x="x", y="y", source=self.source, size="size", color=linear_cmap(field_name="color", palette=Viridis256, low=0, high=1), line_color=None, ) # -- HACKZ -- # Update the plot element in the HTML layout if hasattr(self.parent, "layout"): self.parent.layout.children[0].children[-1] = self.plot # Make the cursor a grabber when panning code_pan_start = """ Bokeh.grabbing = true var elm = document.getElementsByClassName('bk-canvas-events')[0] elm.style.cursor = 'grabbing' """ code_pan_end = """ if(Bokeh.grabbing) { Bokeh.grabbing = false var elm = document.getElementsByClassName('bk-canvas-events')[0] elm.style.cursor = 'grab' } """ self.plot.js_on_event("panstart", CustomJS(code=code_pan_start)) self.plot.js_on_event("panend", CustomJS(code=code_pan_end)) # Add a hover tool w/ a pointer cursor code_hover = """ if((Bokeh.grabbing == 'undefined') || !Bokeh.grabbing) { var elm = document.getElementsByClassName('bk-canvas-events')[0] if (cb_data.index.indices.length > 0) { elm.style.cursor = 'pointer' Bokeh.pointing = true } else { if((Bokeh.pointing == 'undefined') || !Bokeh.pointing) elm.style.cursor = 'grab' else Bokeh.pointing = false } } """ self.plot.add_tools( HoverTool( callback=CustomJS(code=code_hover), tooltips=[("TIC ID", "@ticid")], ))
div = activity.loc[cat.groups["Dividends"]] bins = dates_of_interest(cadence=option, start=start, end=end) yr_bins = [] div_bins = [] for yr, value in bins.items(): mask = (div["date"] >= value["start"]) & (div["date"] <= value["end"]) div_bins.append(div.loc[mask]["netAmount"].agg(np.sum)) yr_bins.append(yr) # Categories: https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html from bokeh.models.tools import BoxZoomTool, ResetTool from bokeh.plotting import figure p = figure(x_range=yr_bins, tools=[BoxZoomTool(), ResetTool()], plot_width=800) p.vbar(x=yr_bins, top=div_bins, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 st.bokeh_chart(p, use_container_width=True) """ # Trade Volume """ "trades cadence:", option trades = activity.loc[cat.groups["Trades"]] # https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sql.html trades.groupby("action").size()
# ============================================================================= multi_plot = Plot(plot_width=800, plot_height=400, background_fill_color='silver') multi_glyph = MultiLine(xs='waves', ys='ys', line_width=2, line_color='label') multi_plot.add_glyph(spectra_visible_multi, multi_glyph) xaxis, yaxis = LinearAxis(), LinearAxis() multi_plot.add_layout(xaxis, 'below') multi_plot.xaxis.axis_label = 'Wavelength (nm)' multi_plot.add_layout(yaxis, 'left') multi_plot.yaxis.axis_label = 'Intensity (CPS)' multi_plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) multi_plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) multi_plot.add_tools(BoxZoomTool()) multi_plot.add_tools(WheelZoomTool()) multi_plot.add_tools(ResetTool()) multi_plot.add_tools(SaveTool()) multi_plot.add_layout(span) # ============================================================================= # ~~ Clustering figures # ~ labeled_materials_image: map image of predicted material labels # ~ elbow inertia vs n_materials plot # ~ varBar bar plot of pca explained variances # ============================================================================= labeled_materials_image, label_mapper = basicMap(labeled_materials, 400, 'image') # elbow = figure(x_axis_label='Number of Materials', y_axis_label='Learning Inertia', # plot_width=400, plot_height=200, toolbar_location=None) # elbow.line('num_clusters', 'inertia', source=elbow_plot) varBar = figure(plot_width=400, plot_height=200, toolbar_location=None) varBar.vbar(x='x', top='top', source=pca_variance, width=0.9)
def create_daily_res_plot(res_forecast, load_forecast): """ Graph the res injection forecast. Arguments: res_forecast (list): list of renewable energy injection forecast load_forecast (list): list of load forecast """ # Datetime range time_of_day = [] # Create x-axis # beginning of day today = datetime.datetime.today() beginning_of_day = datetime.datetime(year=today.year, month=today.month, day=today.day) for i in range(len(res_forecast)): time_of_day.append(beginning_of_day + datetime.timedelta(minutes=i * 30)) # Compute 75 percentile percentile = np.percentile(res_forecast, 75) # Initialize dictionaries normal_dict = {'x': [], 'y': [], 'percentage': []} peak_dict = {'x': [], 'y': [], 'percentage': []} for i in range(len(res_forecast)): if res_forecast[i] >= percentile: peak_dict['x'].append(time_of_day[i]) peak_dict['y'].append(res_forecast[i]) peak_dict['percentage'].append( percentage_of(res_forecast[i], load_forecast[i])) else: normal_dict['x'].append(time_of_day[i]) normal_dict['y'].append(res_forecast[i]) normal_dict['percentage'].append( percentage_of(res_forecast[i], load_forecast[i])) # Hover tool to properly display time of day and value on hover hover = HoverTool( tooltips=[("Time of day", "@x{%H:%M}"), ("Forecast Value", "@y MWh"), ("Percentage of Daily Load", "@percentage{1.11} %")], formatters={'@x': 'datetime'}, ) # Create the figure plot = figure( x_axis_label="Time of Day", y_axis_label="Megawatts Per Hour", x_axis_type='datetime', sizing_mode="stretch_width", tools=[ hover, BoxZoomTool(), ResetTool(), LassoSelectTool(), WheelZoomTool(), PanTool(), SaveTool() ], ) plot.xaxis.formatter = DatetimeTickFormatter( minutes=["%H:%M"], hours=["%H:%M"], ) # Set x-range and y-range plot.y_range = Range1d(min(res_forecast) - 200, max(res_forecast) + 100) plot.x_range = Range1d(time_of_day[0] - datetime.timedelta(minutes=5), time_of_day[-1] + datetime.timedelta(minutes=5)) # Set a grid plot.grid.minor_grid_line_color = '#eeeeee' # Set the font and style of labels plot.axis.axis_label_text_font = "raleway" plot.axis.axis_label_text_font_style = "normal" # Set the font of ticks on the axis plot.axis.major_label_text_font = "raleway" # Set the desired ticks plot.xaxis.ticker = DatetimeTicker(desired_num_ticks=24) plot.yaxis.ticker = AdaptiveTicker(desired_num_ticks=20) # Add a line plot plot.line(time_of_day, res_forecast, line_alpha=0.2, color="#264b01", line_width=1.5) # Add two circle plots one for the normal values and one for those that # are at or above the 75-percentile plot.circle('x', 'y', source=normal_dict, size=8, color="#264b01") plot.circle('x', 'y', source=peak_dict, size=15, color="#264b01") return components(plot)
ts_cnt = np.arange(3) cross = [CrosshairTool() for n in ts_cnt] hover = [ HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p1'), ('raw', '@raw_lp_decim_p1')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p2'), ('raw', '@raw_lp_decim_p2')]) ] xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt] xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [[ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all) play_all_sox_button = Button(label='Play sox', button_type='success', width=60) play_all_sox_button.on_click(play_all_sox) audio_first_checkbox = CheckboxGroup(labels=['audio first'], active=[0]) audio_first_checkbox.on_click(audio_first_selected) fsel.on_change('value', file_selected)
# ;----------; # {{{1 tooltips_top = [ ('open', '@open{0.2f}'), ('high', '@high{0.2f}'), ('low', '@low{0.2f}'), ('close', '@close{0.2f}'), ('ma-slow', '@ma_slow{0.2f}'), ('ma-fast', '@ma_fast{0.2f}'), ('time', '@time{%F %T}') ] box_zoom = BoxZoomTool() pan_tool = PanTool(dimensions='width') wheel_zoom = WheelZoomTool() reset_tool = ResetTool() crosshair = CrosshairTool() save = SaveTool() hover_tool = HoverTool( tooltips=tooltips_top, formatters={'@time': 'datetime'} ) box_selection = BoxSelectTool() tools_top = [ box_zoom, pan_tool, wheel_zoom, reset_tool, crosshair, save,
def make_region_plot(src, src_gene, src_tss, src_rna, fixed_yaxis=None): ''' Construct pileup plot based on src ''' # output_file(html_output) # flatten list of lists in count column of src, find max value of absolute expression frag_count_range = max( map(abs, [x for count in src.data['count'] for x in count])) if len(src_rna.data['y_plus']) > 0: rna_count_range = max(max(src_rna.data['y_plus']), max(abs(src_rna.data['y_minus']))) else: rna_count_range = 0 count_range = max(frag_count_range, rna_count_range) if fixed_yaxis: ymin = -1 * (fixed_yaxis) ymax = fixed_yaxis else: ymin = -(count_range + 1) ymax = count_range + 1 # draw blank figure of correct size with tools p = figure(y_range=(ymin, ymax), plot_width=900, plot_height=700, tools=[ BoxSelectTool(), BoxZoomTool(), PanTool(), WheelZoomTool(), SaveTool(), ResetTool() ], toolbar_location='above') legends = [] # format axis and colors p.xaxis.axis_label = 'position' p.xaxis.major_label_orientation = pi / 4 p.xaxis[0].formatter.use_scientific = False # p.xaxis[0].ticker=FixedTicker(ticks=range(start, end, 100)) p.yaxis.axis_label = 'log normalized activity' patches = p.patches(source=src, xs='position', ys='count', fill_color='color', line_color=None, alpha=0.50) legends.append( LegendItem(label='promoter activity (plus strand)', renderers=[patches], index=0)) legends.append( LegendItem(label='promoter activity (minus strand)', renderers=[patches], index=1)) # draw RNA lines if len(src_rna.data['x_minus']) > 0: plus_line = p.line(x='x_plus', y='y_plus', line_color='#528ecb', line_width=2, source=src_rna) legends.append( LegendItem(label='RNA-seq (plus strand)', renderers=[plus_line], index=0)) minus_line = p.line(x='x_minus', y='y_minus', line_color='#ef8137', line_width=2, source=src_rna) legends.append( LegendItem(label='RNA-seq (minus strand)', renderers=[minus_line], index=1)) # add second y-axis for TSS strength max_tss = max(map(abs, src_tss.data['y0'])) p.extra_y_ranges = { 'tss': Range1d(start=-(max_tss * 4), end=(max_tss * 4)) } p.add_layout(LinearAxis(y_range_name='tss', axis_label='TSS expression'), 'right') # draw vertical rectangle p.quad(top='top', bottom='bottom', left='left', right='right', color='color', source=src_tss, y_range_name='tss') # draw horizontal line for arrow p.segment(x0='x0', y0='y0', x1='x1', y1='y1', color='color', source=src_tss, line_width=4, y_range_name='tss') # center of triangle is endpoint of segment tri = p.triangle(x='x1', y='y1', size=9, angle='angle', angle_units='deg', color='color', source=src_tss, y_range_name='tss') legends.append(LegendItem(label='inactive TSS', renderers=[tri], index=9)) legends.append(LegendItem(label='active TSS', renderers=[tri], index=0)) # plot genes p.rect(x='gene_center', y='gene_center_y', width='gene_width', color='gene_color', height=10, height_units='screen', source=src_gene) p.triangle(x='tri_x', y=0, size=20, angle='angle', angle_units='deg', fill_color='gene_color', line_color=None, source=src_gene) p.text(x='gene_center', y='gene_center_y', text='gene_name', text_color='black', text_align='center', text_baseline='middle', text_font_size='10pt', source=src_gene) p.add_layout(Legend(items=legends), 'below') return p
source = ColumnDataSource( data=dict( months = userData['months'], apps_ = userData['applications'], names_ = userData['names'] ) ) hover = HoverTool(tooltips=[ ("Name", "@names_"), ("Months unemployed", "$x{int}"), ("Submissions", "$y{int}") ] ) TOOLS = [BoxSelectTool(), WheelZoomTool(), ResetTool(), hover] p = figure(plot_width=800, plot_height=900, title="NAV risk assessment", tools=TOOLS) p.xaxis.axis_label = 'Unemployed duration (months)' p.yaxis.axis_label = 'Number of applications submitted' colormap = {0:'green',1:'red'} colors = [colormap[x] for x in userData['labels']] p.circle('months', 'apps_', color=colors, fill_alpha=0.2, size=10,source=source) p.circle(X,Y,color='blue',size=10) output_file("NAVrisk.html", title="NAVrisk.py example") show(p) # Create HTML elements to export