def run(self, data_path, **plot_kwargs): if isinstance(data_path, (str, Path)): data = pd.read_csv(data_path) else: data = data_path current_date = datetime.datetime.now().strftime("%m-%d-%Y-%H-%M-%S") title = Title() if self.sell_signal(data): self.sell_signal.plot_candles(**plot_kwargs) p = self.sell_signal.plot_features() title.text = 'sell_signal %s' % current_date p.title = title return save(p, filename=self.sell_dir / ('sell-%s.HTML' % current_date)) elif self.buy_signal(data): self.buy_signal.plot_candles(**plot_kwargs) p = self.buy_signal.plot_features() title.text = 'buy_signal %s.HTML' % current_date p.title = title return save(p, filename=self.buy_dir / ('buy-%s.HTML' % current_date))
def gdp_income(result_df, scatter_countries, source_gdp): p3 = figure(plot_width=400, plot_height=400, x_range=(0, 110), x_axis_label='Rank', y_axis_label='GDP') p3.circle(source=source_gdp, x='x', y='y', size=5, color=RdYlBu7[0]) t = Title() t.text = 'Rank vs GDP' p3.title = t p3.xaxis.axis_label = 'Rank' p3.yaxis.axis_label = 'GDP' p2 = figure(plot_width=400, plot_height=400, x_range=(0, 110), x_axis_label='Rank', y_axis_label='Incoming Count') p2.circle(source=source_gdp, x='x', y='y2', size=5, color=RdYlBu7[6]) t = Title() t.text = 'Rank vs Incoming' p2.title = t p2.xaxis.axis_label = 'Rank' p2.yaxis.axis_label = 'Income' #t = Title() #t.text = 'Rank vs Incoming Count' #p2.title = t #t = Title() #t.text = str(source_gdp.data['year'][0]) #p2.title = t #source_incoming = ColumnDataSource({'x': scatter_countries[scatter_countries.year==2006]['rank'].tolist(), 'y': scatter_countries[scatter_countries.year==2006].incoming.tolist()}) # #def update_incoming(): # global scatter_countries # for yr in list(scatter_countries.year.unique()): # time.sleep(2) # new = {'x': scatter_countries[scatter_countries.year==yr]['rank'].tolist(), # 'y': scatter_countries[scatter_countries.year==yr].incoming.tolist()} # new = ColumnDataSource(new) # source_incoming.data.update(new.data) #p2 = figure(plot_width=400, plot_height=400,x_range=(0,110)) #p2.circle(source=source_incoming, x='x', y='y', size=5,color=RdYlBu7[6]) #p = figure(plot_width=400, plot_height=400) # add a circle renderer with a size, color, and alpha #p.circle(scatter_countries[scatter_countries.year==2006]['rank'].tolist(), scatter_countries[scatter_countries.year==2006]['gdp_percapita'].tolist(), size=5, color="navy") # show the results #show(p) return p3, p2
def plot_neff(self, ax, markersize): """Draw effective n for each plotter.""" max_ess = 0 for plotter in self.plotters.values(): for y, ess, color in plotter.ess(): if ess is not None: ax.circle( x=ess, y=y, fill_color=color, size=markersize, line_color="black", ) if ess > max_ess: max_ess = ess ax.x_range._property_values["start"] = 0 # pylint: disable=protected-access ax.x_range._property_values["end"] = 1.07 * max_ess # pylint: disable=protected-access _title = Title() _title.text = "ess" ax.title = _title ax.xaxis[0].ticker.desired_num_ticks = 3 return ax
def stock_plot(df, comp): curdoc().theme = 'dark_minimal' p = figure(x_axis_type='datetime', height=300, width=1000, sizing_mode='scale_width') t = Title() t.text = comp p.title = t p.grid.grid_line_alpha = 0.3 h12 = 12 * 60 * 60 * 1000 p.segment(df.index, df.High, df.index, df.Low, color="white") p.background_fill_color = "black" p.border_fill_color = 'black' p.rect(df.index[df['Status'] == 'Increase'], df.Middle[df.Status == 'Increase'], h12, df.Height[df.Status == 'Increase'], fill_color='lime', line_color='white') p.rect(df.index[df['Status'] == 'Decrease'], df.Middle[df.Status == 'Decrease'], h12, df.Height[df.Status == 'Decrease'], fill_color='red', line_color='white') web, div1 = components(p) cdn_js = CDN.js_files[0] return (web, div1, cdn_js)
def make_figure(x, y): # Plot time series (prices) p=figure(x_axis_type="datetime", width=1200, height=600) t = Title() t.text = 'Price' p.circle(x, y, size=10, color='red', legend='Price') p.line(x, y, color='blue') p.xaxis.formatter=DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = np.pi/4 p.grid.grid_line_alpha=0.4 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.title = t output_file('plot.html') script, div=components(p) return(script, div)
def update_graph(): global numRep, repoNames p = figure(plot_width=400, plot_height=400, title=text.value, x_range=usernameList, y_range=[0, biggestNumRep + 1], toolbar_location=None, tools="") if response.status_code == 404: t = Title() t.text = "USER NOT FOUND" p.title = t p.vbar(x=usernameList, width=0.8, bottom=0, top=numRepList, color="firebrick") p.yaxis.ticker = FixedTicker(ticks=list(range(0, biggestNumRep + 2))) p.yaxis.axis_label = "No. of repositories" if response.status_code != 404: repoDict = json.loads(response.text) repoNames = [] for entry in repoDict: repoNames.append(entry["name"]) radio = RadioButtonGroup(labels=repoNames, active=0) #radio.on_click(specific_repo) specific_repo(0) else: radio = RadioButtonGroup(labels=[]) newGraph = column(text, radio, row(p, pie), width=1000) graphs.children = newGraph.children
def chart(): from pandas_datareader import data import pandas as pd import datetime from bokeh.plotting import figure, show, output_file from bokeh.models.annotations import Title from bokeh.embed import components from bokeh.resources import CDN start_time = datetime.datetime(2017,1,1) end_time = datetime.datetime(2018,3,10) df = data.DataReader(name="BTC-USD", data_source="yahoo",start=start_time,end=end_time) def inc_dec(c,o): if c-o > 0: value="Increase" elif c-o < 0: value ="Decrease" else: value = "Equal" return value df['Status'] = [inc_dec(c,o) for c,o in zip(df.Close, df.Open)] df['Middle'] = (df.Open + df.Close)/2 df['Height'] = abs(df.Open - df.Close) df #rect methods p = figure(x_axis_type='datetime',width=1000, height=300, sizing_mode = "scale_width") t = Title() t.text= "Candlestick" p.title = t p.grid.grid_line_alpha=0.5 hours_12=12*60*60*1000 p.segment(df.index, df.High, df.index, df.Low, color="black") p.rect(df.index[df.Status == "Increase"], df.Middle[df.Status == "Increase"], hours_12, df.Height[df.Status == "Increase"], fill_color="#6495ED") p.rect(df.index[df.Status == "Decrease"], df.Middle[df.Status == "Decrease"], hours_12, df.Height[df.Status == "Decrease"], fill_color="#FF0000") script, div1 = components(p) cdn_js=CDN.js_files[0] cdn_css=CDN.css_files #output_file("CS.html") #show(p) return render_template("chart.html", webapp=script, div1=div1, cdn_js=cdn_js)
def setTitle(self, newTitle): """ change the title of the graph :param newTitle: """ title = Title() title.text = newTitle self.__figure.title = title
def plot_autocorr( axes, plotters, max_lag, figsize, rows, cols, line_width, combined, backend_kwargs, show, ): """Bokeh autocorrelation plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(), **backend_kwargs, } if axes is None: _, axes = _create_axes_grid( len(plotters), rows, cols, figsize=figsize, squeeze=False, sharex=True, sharey=True, backend="bokeh", backend_kwargs=backend_kwargs, ) else: axes = np.atleast_2d(axes) for (var_name, selection, x), ax in zip( plotters, (item for item in axes.flatten() if item is not None) ): x_prime = x if combined: x_prime = x.flatten() y = autocorr(x_prime) ax.segment( x0=np.arange(len(y)), y0=0, x1=np.arange(len(y)), y1=y, line_width=line_width, line_color="black", ) ax.line([0, 0], [0, max_lag], line_color="steelblue") title = Title() title.text = make_label(var_name, selection) ax.title = title if axes.size > 0: axes[0, 0].x_range._property_values["start"] = 0 # pylint: disable=protected-access axes[0, 0].x_range._property_values["end"] = max_lag # pylint: disable=protected-access axes[0, 0].y_range._property_values["start"] = -1 # pylint: disable=protected-access axes[0, 0].y_range._property_values["end"] = 1 # pylint: disable=protected-access if backend_show(show): bkp.show(gridplot(axes.tolist(), toolbar_location="above")) return axes
def _plot_atomic_elpd( ax_, xdata, ydata, model1, model2, threshold, coord_labels, xlabels, xlabels_shown, ylabels_shown, plot_kwargs, ): marker = _validate_bokeh_marker(plot_kwargs.get("marker")) sizes = np.ones(len(xdata)) * plot_kwargs.get("s") glyph = Scatter( x="xdata", y="ydata", size="sizes", line_color=plot_kwargs.get("color", "black"), marker=marker, ) source = ColumnDataSource(dict(xdata=xdata, ydata=ydata, sizes=sizes)) ax_.add_glyph(source, glyph) if threshold is not None: diff_abs = np.abs(ydata - ydata.mean()) bool_ary = diff_abs > threshold * ydata.std() if coord_labels is None: coord_labels = xdata.astype(str) outliers = np.nonzero(bool_ary)[0] for outlier in outliers: label = coord_labels[outlier] ax_.text( x=[outlier], y=[ydata[outlier]], text=label, text_color="black", ) if ylabels_shown: ax_.yaxis.axis_label = "ELPD difference" else: ax_.yaxis.minor_tick_line_color = None ax_.yaxis.major_label_text_font_size = "0pt" if xlabels_shown: if xlabels: ax_.xaxis.ticker = np.arange(0, len(coord_labels)) ax_.xaxis.major_label_overrides = { str(key): str(value) for key, value in zip(np.arange(0, len(coord_labels)), list(coord_labels)) } else: ax_.xaxis.minor_tick_line_color = None ax_.xaxis.major_label_text_font_size = "0pt" title = Title() title.text = f"{model1} - {model2}" ax_.title = title
def alpha_beta_plotter(df_conc, dot_alpha = 0.5, dot_size = 1.5): """ Function to plot the alpha vs beta parameters for bootstrapped samples for all Tubulin concentration values. Parameters ---------- df_conc : pandas DataFrame DataFrame containing the bootstrapped parameter values. dot_alpha : float Alpha value for the plot dots dot_size : float Size of the glyphs. Returns ------- alpha_beta_plot : figure bokeh figure of alpha-beta scatter plots. """ # Creating scatterplot alpha_beta = hv.Scatter( data = df_conc, kdims = ["Alpha_MLE", "Beta_MLE"], vdims = ["Concentration (uM)"], ).opts( height = 750, width = 750, legend_position = "right", color = "Concentration (uM)", title = "Alpha_MLE vs Beta_MLE", size = dot_size, alpha = dot_alpha, ).groupby( "Concentration (uM)" ).overlay( ) alpha_beta.opts(legend_position = "right") # Rendered alpha_beta_plot = hv.render(alpha_beta) # Aligning the title t = Title() t.text = "Alpha_MLE vs Beta_MLE" alpha_beta_plot.title = t alpha_beta_plot.title.align = "center" # Setting the legend labels alpha_beta_plot.legend.title = "Concentration (uM)" return alpha_beta_plot
def __init__(self, source_num): # DEFINE FIGURE # ------------------------------------------------------------------------------ self.Fig = figure(plot_width=150, plot_height=150) self.Fig.grid.grid_line_alpha = 0 self.Fig.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels self.Fig.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels self.Fig.xaxis.major_tick_line_color = None # turn off x-axis major ticks self.Fig.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks self.Fig.yaxis.major_tick_line_color = None # turn off y-axis major ticks self.Fig.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks self.Fig.border_fill_alpha = 1 # remove toolbar and Bokeh logo self.Fig.toolbar.logo = None self.Fig.toolbar_location = None # add border to visualization self.Fig.outline_line_width = 1 self.Fig.outline_line_alpha = 1 self.Fig.outline_line_color = "black" # create tooltip # add tooltip # self.Fig.add_tools(HoverTool( # tooltips=[ # ("Age Range (years)", "HRV Range in rMSSD (ms)"), # ("10-19", "36-70"), # ("20-29", "24-62"), # ("30-99", "15-46") # ], # mode='vline' # )) self.Fig.add_tools( HoverTool(tooltips=[("Age (Years)", "Normal Range"), ("10-19", "36-70"), ("20-29", "24-62"), ("30-99", "15-46")], )) # TOOLTIPS = [ # ] # self.Fig = figure(plot_width=150, plot_height=150, tooltips=TOOLTIPS) # DEFINE PLOT # ------------------------------------------------------------------------------ self.Text = self.Fig.text(x="num_x", y="num_y", text="hrv", source=source_num,\ text_font_size="30px", text_align="center", text_baseline="middle", text_color="#FF660F") # create title t = Title() t.text = 'HRV (ms)' # set title self.Fig.title = t self.Fig.title.align = "center" self.Fig.title.text_font_size = "20px"
def _plot_posterior( ax, length_plotters, rows, cols, figsize, plotters, bw, bins, kind, point_estimate, round_to, credible_interval, multimodal, ref_val, rope, ax_labelsize, kwargs, show, ): if ax is None: _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False, backend="bokeh") idx = 0 for (var_name, selection, x), ax_ in zip(plotters, np.ravel(ax)): _plot_posterior_op(idx, x.flatten(), var_name, selection, ax=ax_, bw=bw, bins=bins, kind=kind, point_estimate=point_estimate, round_to=round_to, credible_interval=credible_interval, multimodal=multimodal, ref_val=ref_val, rope=rope, ax_labelsize=ax_labelsize, **kwargs) idx += 1 _title = Title() _title.text = make_label(var_name, selection) ax_.title = _title if show: grid = gridplot([list(item) for item in ax], toolbar_location="above") bkp.show(grid) return ax
def _plot_atomic_elpd( ax_, xdata, ydata, model1, model2, threshold, coord_labels, xlabels, xlabels_shown, ylabels_shown, plot_kwargs, ): ax_.cross( np.asarray(xdata), np.asarray(ydata), line_color=plot_kwargs.get("color", "black"), size=plot_kwargs.get("s"), ) if threshold is not None: diff_abs = np.abs(ydata - ydata.mean()) bool_ary = diff_abs > threshold * ydata.std() if coord_labels is None: coord_labels = xdata.astype(str) outliers = np.argwhere(bool_ary).squeeze() for outlier in outliers: label = coord_labels[outlier] ax_.text( x=np.asarray(outlier), y=np.asarray(ydata[outlier]), text=label, text_color="black", ) if ylabels_shown: ax_.yaxis.axis_label = "ELPD difference" else: ax_.yaxis.minor_tick_line_color = None ax_.yaxis.major_label_text_font_size = "0pt" if xlabels_shown: if xlabels: ax_.xaxis.ticker = np.arange(0, len(coord_labels)) ax_.xaxis.major_label_overrides = { str(key): str(value) for key, value in zip(np.arange(0, len(coord_labels)), list(coord_labels)) } else: ax_.xaxis.minor_tick_line_color = None ax_.xaxis.major_label_text_font_size = "0pt" title = Title() title.text = "{} - {}".format(model1, model2) ax_.title = title
def stocks(): start = datetime.datetime(2020, 1, 1) end = datetime.datetime(2020, 4, 30) df = data.DataReader(name="AAL", data_source="yahoo", start=start, end=end) p = figure(x_axis_type='datetime', width=1000, height=300, sizing_mode="scale_width") t = Title() t.text = "American Airlines (AAL)" p.title = t p.grid.grid_line_alpha = 0.3 hours_16 = 16 * 60 * 60 * 1000 # converts to milliseconds def inc_dec(c, o): if c >= o: value = "Increase" else: value = "Decrease" return value df["Status"] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)] df["Middle"] = (df.Open + df.Close) / 2 df["Height"] = abs(df.Close - df.Open) # Vertical line high/low glyph p.segment(df.index, df.High, df.index, df.Low, color="black") # Rising price days p.rect( df.index[df.Status == "Increase"], df.Middle[df.Status == "Increase"], hours_16, df.Height[df.Status == "Increase"], fill_color="#CCFFFF", line_color="black" ) # Falling price days p.rect( df.index[df.Status == "Decrease"], df.Middle[df.Status == "Decrease"], hours_16, df.Height[df.Status == "Decrease"], fill_color="#FF3333", line_color="black" ) script1, div1 = components(p) cdn_js = CDN.js_files[0] return render_template("stocks.html", script1=script1, div1=div1, cdn_js=cdn_js)
def make_figure(df, tickerText): p = figure(x_axis_type="datetime", width=400, height=300) p.line(df.index, df['Close'], line_width=5) t = Title() t.text = tickerText p.grid.grid_line_alpha = 0.3 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.title = t bokeh.io.output_file('templates/plot.html') bokeh.io.save(p) script, div = components(p) return (script, div)
def plot_rhat(self, ax, markersize): """Draw r-hat for each plotter.""" for plotter in self.plotters.values(): for y, r_hat, color in plotter.r_hat(): if r_hat is not None: ax.circle(x=r_hat, y=y, fill_color=color, size=markersize, line_color="black") ax.x_range._property_values["start"] = 0.9 # pylint: disable=protected-access ax.x_range._property_values["end"] = 2.1 # pylint: disable=protected-access _title = Title() _title.text = "r_hat" ax.title = _title ax.xaxis[0].ticker.desired_num_ticks = 3 return ax
def plot(): from pandas_datareader import data import datetime from bokeh.plotting import figure, show, output_file from bokeh.models.annotations import Title from bokeh.embed import components from bokeh.resources import CDN start = datetime.datetime(2017, 2, 10) end = datetime.datetime(2017, 3, 10) df = data.DataReader(name = 'GOOG', data_source = 'morningstar', start = start, end = end) def inc_dec(o, c): return "Increase" if c > o else "Decrease" df["Status"] = [inc_dec(o, c) for o, c in zip(df.Open, df.Close)] df["Middle"] = (df.Open + df.Close) / 2 df["Height"] = abs(df.Open - df.Close) p = figure(x_axis_type = 'datetime', width = 1000, height = 300, sizing_mode = 'scale_width') p.grid.grid_line_alpha = .3 t = Title() t.text = "Candlestick Chart" p.title = t hour12 = 12 * 60 * 60 * 1000 # 12 hours in milliseconds #since decrease and increase days should be of different colors we ude two different DFs for graph p.segment(df.index, df.High, df.index, df.Low, color = "black") gdf = df[df.Status == "Increase"] p.rect(gdf.index, gdf.Middle, hour12, gdf.Height, fill_color = '#CCFFFF', line_color = 'black') gdf = df[df.Status == "Decrease"] p.rect(gdf.index, gdf.Middle, hour12, gdf.Height, fill_color = '#FF3333', line_color = 'black') #output_file("candlestick2.html") #show(p) script1, div1 = components(p) cdn_js = CDN.js_files cdn_css = CDN.css_files return render_template('plot.html', script1 = script1, div1 = div1, cdn_css = cdn_css[0], cdn_js = cdn_js[0])
def plot_points(p, datapoints_source): t = Title() t.text = "Car sharing Segmentation Widget" p.title = t p.scatter("x", "y", source=datapoints_source, legend="thr", alpha=0.5, size=12, color=mapper) p.xaxis.axis_label = X p.yaxis.axis_label = Y legend_title = Z + "_Threshold" #Legend Title p.legend.title = '> Threshold is 1 else 0 (For Numeric Columns)'
def create_figure(): #Obtenemos maximos y minimos para los ejes y_min = min(df[y_axis_menu.value]) y_max = max(df[y_axis_menu.value]) x_min = min(df[x_axis_menu.value]) x_max = max(df[x_axis_menu.value]) p = figure(plot_width=600, plot_height=400, tools=[hover], x_range=(x_min, x_max), y_range=(y_min, y_max)) p.circle(x_axis_menu.value, y_axis_menu.value, color = {'field':'region', 'transform':color_mapper}, alpha=1.0, legend='region', source = gapminder) t = Title() t.text = 'Gapminder Data for %d' % slider.value p.title = t p.xaxis.axis_label = x_axis_menu.value p.yaxis.axis_label = y_axis_menu.value return p
def __init__(self, source_num): # DEFINE FIGURE # ------------------------------------------------------------------------------ self.Fig = figure(plot_width=150, plot_height=150) self.Fig.grid.grid_line_alpha = 0 self.Fig.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels self.Fig.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels self.Fig.xaxis.major_tick_line_color = None # turn off x-axis major ticks self.Fig.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks self.Fig.yaxis.major_tick_line_color = None # turn off y-axis major ticks self.Fig.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks self.Fig.border_fill_alpha = 1 # remove toolbar and Bokeh logo self.Fig.toolbar.logo = None self.Fig.toolbar_location = None # add border to visualization self.Fig.outline_line_width = 1 self.Fig.outline_line_alpha = 1 self.Fig.outline_line_color = "black" self.Fig.add_tools(HoverTool( tooltips=[ ("Normal", ">95%"), ("Hypoxia", "<94%") ] )) # DEFINE PLOT # ------------------------------------------------------------------------------ self.Text = self.Fig.text(x="num_x", y="num_y", text="spo2", source=source_num,\ text_font_size="30px", text_align="center", text_baseline="middle", text_color="#0032EC") # create title t = Title() t.text = 'SPO2 (%)' # set title self.Fig.title = t self.Fig.title.align = "center" self.Fig.title.text_font_size = "20px"
def plot_train_rewards(folder, rewards, title='train_rewards'): output_file(folder + '\\' + title + '.html') p = figure(plot_width=1000, plot_height=600) x_axis = range(len(rewards)) y_axis = rewards p.line(x_axis, y_axis, line_width=2) p.xaxis.axis_label = 'Time' p.yaxis.axis_label = 'Stock Price' t = Title() t.text = 'Stock Price during year 2018' p.title = t show(p)
def plot_config(ptype: str, data_source: ColumnDataSource) -> Figure: mapper = LinearColorMapper(palette=constants.cust_rg_palette, low=0.8, high=1.2, low_color='#33FF33', high_color='#FF3333', nan_color='#A9A9A9') color_bar = ColorBar(color_mapper=mapper, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0), background_fill_alpha=0, background_fill_color=None, major_tick_line_alpha=0) custom_hover_format = CustomJS( args=dict(cust_tooltip_above=constants.cust_tooltip_above, cust_tooltip_below=constants.cust_tooltip_below), code=constants.custom_hover_code) national_args = dict(toolbar_location=None, plot_width=900, plot_height=600, frame_height=700, frame_width=1050) min_width, min_height, max_width, max_height = constants.base_dims state_args = {'width_policy': 'fit', 'height_policy': 'fit', 'min_height': min_height, 'min_width': min_width, 'max_height': max_height, 'max_width': max_width, 'min_border_left': 25, 'tools': 'wheel_zoom,reset'} plot_tools_config = {'x_axis_location': None, 'y_axis_location': None, 'border_fill_alpha': 0, 'background_fill_alpha': 0, 'background_fill_color': None, 'border_fill_color': None, 'outline_line_alpha': 0, 'outline_line_width': 0} t = None if ptype == 'national': p = figure(**plot_tools_config, **national_args) else: p = figure(**plot_tools_config, **state_args) t = Title() t.text = 'Default' p.title = t p.title.text_font_size = "20pt" p.title.text_color = '#003566' p.add_tools(HoverTool(tooltips=None, callback=custom_hover_format, formatters={'@2nd_order_growth': 'numeral', '@confirmed_infected': 'numeral', '@Rt': 'numeral'})) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.hover.attachment = "above" p.toolbar.logo = None p.patches('lons', 'lats', source=data_source, fill_color=transform('Rt', mapper), fill_alpha=0.7, line_color='#003566', line_width=0.5, hover_color='#003566') if ptype != 'national': p.add_layout(color_bar, 'right') t.visible = False return p
def __init__(self, source_num): # DEFINE FIGURE # ------------------------------------------------------------------------------ self.Fig = figure(plot_width=150, plot_height=150) self.Fig.grid.grid_line_alpha = 0 self.Fig.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels self.Fig.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels self.Fig.xaxis.major_tick_line_color = None # turn off x-axis major ticks self.Fig.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks self.Fig.yaxis.major_tick_line_color = None # turn off y-axis major ticks self.Fig.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks self.Fig.border_fill_alpha = 1 # remove toolbar and Bokeh logo self.Fig.toolbar.logo = None self.Fig.toolbar_location = None # add border to visualization self.Fig.outline_line_width = 1 self.Fig.outline_line_alpha = 1 self.Fig.outline_line_color = "black" self.Fig.add_tools(HoverTool( tooltips=[ ("GSR","refers to changes in sweat gland activity") ] )) # DEFINE PLOT # ------------------------------------------------------------------------------ self.Text = self.Fig.text(x="num_x", y="num_y", text="gsr", source=source_num, \ text_font_size="30px", text_align="center", text_baseline="middle", text_color="#96deb3") # create title t = Title() t.text = 'GSR (uV)' # set title self.Fig.title = t self.Fig.title.align = "center" self.Fig.title.text_font_size = "20px"
def _plot_autocorr( axes, plotters, max_lag, line_width, combined=False, show=True, ): for (var_name, selection, x), ax_ in zip(plotters, axes.flatten()): x_prime = x if combined: x_prime = x.flatten() y = autocorr(x_prime) ax_.segment( x0=np.arange(len(y)), y0=0, x1=np.arange(len(y)), y1=y, line_width=line_width, line_color="black", ) ax_.line([0, 0], [0, max_lag], line_color="steelblue") title = Title() title.text = make_label(var_name, selection) ax_.title = title if axes.size > 0: axes[0, 0].x_range._property_values["start"] = 0 # pylint: disable=protected-access axes[0, 0].x_range._property_values["end"] = max_lag # pylint: disable=protected-access axes[0, 0].y_range._property_values["start"] = -1 # pylint: disable=protected-access axes[0, 0].y_range._property_values["end"] = 1 # pylint: disable=protected-access if show: bkp.show( gridplot([list(item) for item in axes], toolbar_location="above")) return axes
def __init__(self, source_num): # DEFINE FIGURE # ------------------------------------------------------------------------------ self.Fig = figure(plot_width=150, plot_height=150) self.Fig.grid.grid_line_alpha = 0 self.Fig.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels self.Fig.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels self.Fig.xaxis.major_tick_line_color = None # turn off x-axis major ticks self.Fig.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks self.Fig.yaxis.major_tick_line_color = None # turn off y-axis major ticks self.Fig.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks self.Fig.border_fill_alpha = 1 # remove toolbar and Bokeh logo self.Fig.toolbar.logo = None self.Fig.toolbar_location = None # add border to visualization self.Fig.outline_line_width = 1 self.Fig.outline_line_alpha = 1 self.Fig.outline_line_color = "black" # DEFINE PLOT # ------------------------------------------------------------------------------ self.Text = self.Fig.text(x="num_x", y="num_y", text="rr", source=source_num, \ text_font_size="30px", text_align="center", text_baseline="middle", text_color="#20880E") # create title t = Title() t.text = 'RR (bpm)' # set title self.Fig.title = t self.Fig.title.align = "center" self.Fig.title.text_font_size = "20px"
def plot_autocorr( axes, plotters, max_lag, figsize, rows, cols, combined, textsize, backend_config, backend_kwargs, show, ): """Bokeh autocorrelation plot.""" if backend_config is None: backend_config = {} len_y = plotters[0][2].size backend_config.setdefault("bounds_x_range", (0, len_y)) backend_config = { **backend_kwarg_defaults(("bounds_y_range", "plot.bokeh.bounds_y_range"), ), **backend_config, } if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ), **backend_kwargs, } figsize, _, _, _, line_width, _ = _scale_fig_size(figsize, textsize, rows, cols) if axes is None: axes = create_axes_grid( len(plotters), rows, cols, figsize=figsize, sharex=True, sharey=True, backend_kwargs=backend_kwargs, ) else: axes = np.atleast_2d(axes) data_range_x = DataRange1d(start=0, end=max_lag, bounds=backend_config["bounds_x_range"], min_interval=5) data_range_y = DataRange1d(start=-1, end=1, bounds=backend_config["bounds_y_range"], min_interval=0.1) for (var_name, selection, x), ax in zip(plotters, (item for item in axes.flatten() if item is not None)): x_prime = x if combined: x_prime = x.flatten() y = autocorr(x_prime) ax.segment( x0=np.arange(len(y)), y0=0, x1=np.arange(len(y)), y1=y, line_width=line_width, line_color="black", ) ax.line([0, 0], [0, max_lag], line_color="steelblue") title = Title() title.text = make_label(var_name, selection) ax.title = title ax.x_range = data_range_x ax.y_range = data_range_y show_layout(axes, show) return axes
def plot_violin( ax, plotters, figsize, rows, cols, sharex, sharey, shade_kwargs, shade, rug, rug_kwargs, bw, textsize, circular, hdi_prob, quartiles, backend_kwargs, show, ): """Bokeh violin plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ), **backend_kwargs, } (figsize, *_, linewidth, _) = _scale_fig_size(figsize, textsize, rows, cols) shade_kwargs = {} if shade_kwargs is None else shade_kwargs rug_kwargs = {} if rug_kwargs is None else rug_kwargs rug_kwargs.setdefault("fill_alpha", 0.1) rug_kwargs.setdefault("line_alpha", 0.1) if ax is None: ax = create_axes_grid( len(plotters), rows, cols, sharex=sharex, sharey=sharey, figsize=figsize, backend_kwargs=backend_kwargs, ) else: ax = np.atleast_2d(ax) current_col = 0 for (var_name, selection, x), ax_ in zip(plotters, (item for item in ax.flatten() if item is not None)): val = x.flatten() if val[0].dtype.kind == "i": dens = cat_hist(val, rug, shade, ax_, **shade_kwargs) else: dens = _violinplot(val, rug, shade, bw, circular, ax_, **shade_kwargs) if rug: rug_x = -np.abs( np.random.normal(scale=max(dens) / 3.5, size=len(val))) ax_.scatter(rug_x, val, **rug_kwargs) per = np.nanpercentile(val, [25, 75, 50]) hdi_probs = hdi(val, hdi_prob, multimodal=False, skipna=True) if quartiles: ax_.line([0, 0], per[:2], line_width=linewidth * 3, line_color="black", line_cap="round") ax_.line([0, 0], hdi_probs, line_width=linewidth, line_color="black", line_cap="round") ax_.circle( 0, per[-1], line_color="white", fill_color="white", size=linewidth * 1.5, line_width=linewidth, ) _title = Title() _title.align = "center" _title.text = make_label(var_name, selection) ax_.title = _title ax_.xaxis.major_tick_line_color = None ax_.xaxis.minor_tick_line_color = None ax_.xaxis.major_label_text_font_size = "0pt" if current_col != 0: ax_.xaxis.major_label_text_font_size = "0pt" ax_.yaxis.major_label_text_font_size = "0pt" ax_.yaxis.major_tick_line_color = None ax_.yaxis.minor_tick_line_color = None ax_.yaxis.axis_line_color = None current_col += 1 if current_col == cols: current_col = 0 show_layout(ax, show) return ax
def _plot_mcse( ax, plotters, length_plotters, rows, cols, figsize, errorbar, rug, data, probs, extra_kwargs, extra_methods, mean_mcse, sd_mcse, rug_kwargs, idata, rug_kind, _markersize, _linewidth, show, ): if ax is None: _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, backend="bokeh") for (var_name, selection, x), ax_ in zip(plotters, np.ravel(ax)): if errorbar or rug: values = data[var_name].sel(**selection).values.flatten() if errorbar: quantile_values = _quantile(values, probs) ax_.dash(probs, quantile_values) ax_.multi_line( list(zip(probs, probs)), [(quant - err, quant + err) for quant, err in zip(quantile_values, x)], ) else: ax_.circle(probs, x) if extra_methods: mean_mcse_i = mean_mcse[var_name].sel( **selection).values.item() sd_mcse_i = sd_mcse[var_name].sel(**selection).values.item() hline_mean = Span( location=mean_mcse_i, dimension="width", line_color="black", line_width=extra_kwargs["linewidth"] * 2, line_alpha=extra_kwargs["alpha"], ) ax_.renderers.append(hline_mean) hline_sd = Span( location=sd_mcse_i, dimension="width", line_color="black", line_width=extra_kwargs["linewidth"], line_alpha=extra_kwargs["alpha"], ) ax_.renderers.append(hline_sd) if rug: if rug_kwargs is None: rug_kwargs = {} if not hasattr(idata, "sample_stats"): raise ValueError( "InferenceData object must contain sample_stats for rug plot" ) if not hasattr(idata.sample_stats, rug_kind): raise ValueError( "InferenceData does not contain {} data".format(rug_kind)) rug_kwargs.setdefault("space", 0.1) _rug_kwargs = {} _rug_kwargs.setdefault("size", 8) _rug_kwargs.setdefault("line_color", rug_kwargs.get("line_color", "black")) _rug_kwargs.setdefault("line_width", 1) _rug_kwargs.setdefault("line_alpha", 0.35) _rug_kwargs.setdefault("angle", np.pi / 2) mask = idata.sample_stats[rug_kind].values.flatten() values = rankdata(values)[mask] if errorbar: rug_x, rug_y = ( values / (len(mask) - 1), np.full_like( values, min( 0, min(quantile_values) - (max(quantile_values) - min(quantile_values)) * 0.05, ), ), ) hline = Span( location=min( 0, min(quantile_values) - (max(quantile_values) - min(quantile_values)) * 0.05, ), dimension="width", line_color="black", line_width=_linewidth, line_alpha=0.7, ) else: rug_x, rug_y = ( values / (len(mask) - 1), np.full_like( values, 0, ), ) hline = Span( location=0, dimension="width", line_color="black", line_width=_linewidth, line_alpha=0.7, ) ax_.renderers.append(hline) glyph = Dash(x="rug_x", y="rug_y", **_rug_kwargs) cds_rug = ColumnDataSource({ "rug_x": np.asarray(rug_x), "rug_y": np.asarray(rug_y) }) ax_.add_glyph(cds_rug, glyph) title = Title() title.text = make_label(var_name, selection) ax_.title = title ax_.xaxis.axis_label = "Quantile" ax_.yaxis.axis_label = (r"Value $\pm$ MCSE for quantiles" if errorbar else "MCSE for quantiles") if not errorbar: ax_.y_range._property_values["start"] = -0.05 # pylint: disable=protected-access ax_.y_range._property_values["end"] = 1 # pylint: disable=protected-access if show: grid = gridplot([list(item) for item in ax], toolbar_location="above") bkp.show(grid) return ax
def plot(): from pandas_datareader import data import datetime from bokeh.plotting import figure, show, output_file from bokeh.models.annotations import Title from bokeh.embed import components from bokeh.resources import CDN start = datetime.datetime(2015, 11, 1) end = datetime.datetime(2016, 3, 10) df = data.DataReader(name="GOOG", data_source="yahoo", start=start, end=end) def inc_dec(c, o): if c > o: return "Increase" elif o > c: return "Decrease" else: return "Equal" df["Status"] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)] df["Middle"] = (df.Open + df.Close) / 2 df["Height"] = abs(df.Open - df.Close) p = figure(x_axis_type="datetime", width=1000, height=300, sizing_mode='scale_width') t = Title() t.text = "Chart1" p.title = t p.grid.grid_line_alpha = 0.5 hfd = 12 * 60 * 60 * 1000 p.segment(df.index, df.High, df.index, df.Low, color="Black") p.rect(df.index[df.Status == "Increase"], df.Middle[df.Status == "Increase"], hfd, df.Height[df.Status == "Increase"], fill_color="#009900", line_color="black") p.rect(df.index[df.Status == "Decrease"], df.Middle[df.Status == "Decrease"], hfd, df.Height[df.Status == "Decrease"], fill_color="#FF1A1A", line_color="black") script1, div1 = components(p) cdn_js = CDN.js_files[0] cdn_css = CDN.css_files[0] return render_template("plot.html", script1=script1, div1=div1, cdn_js=cdn_js, cdn_css=cdn_css)