Python bokeh.layouts.gridplot() Examples
The following are 23
code examples of bokeh.layouts.gridplot().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bokeh.layouts
, or try the search function
.
Example #1
Source File: MultiPlot.py From ndlib with BSD 2-Clause "Simplified" License | 5 votes |
def plot(self, ncols=2): """ :param ncols: Number of grid columns :return: a bokeh figure image """ grid = gridplot(self.plots, ncols=ncols) return grid
Example #2
Source File: coKriging.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def plot_cross_covariance(trace, lags, df, n_exp=2, n_gaus=2, nuggets=None, iter_plot=200): n_equations = trace['weights'].shape[1] n_iter = trace['weights'].shape[0] lags_tiled = np.tile(lags, (iter_plot, 1)) b_var = [] for i in range(0, df.shape[1]): # n_equations, (n_exp+n_gaus)): # Init tensor b = np.zeros((len(lags), n_iter, 0)) for i_exp in range(0, n_exp): # print(i_exp, "exp") b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gaus)] * exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp]))) for i_gaus in range(n_exp, n_gaus + n_exp): # print(i_gaus) b = np.dstack((b, trace['weights'][:, i_gaus + i * (n_exp + n_gaus)] * gaus_vario(lags, trace['sill'][:, i_gaus], trace['range'][:, i_gaus]))) # Sum the contributins of each function if nuggets is not None: b_all = 1 - (b.sum(axis=2) + nuggets[i]) else: b_all = 1 - (b.sum(axis=2)) # Append each variable b_var.append(b_all[:, -iter_plot:].T) p_all = [] for e, el in enumerate(df.columns): p = bp.figure(x_axis_type="log") p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08) p.title.text = el p.xaxis.axis_label = "lags" p.yaxis.axis_label = "Semivariance" p_all = np.append(p_all, p) grid = bl.gridplot(list(p_all), ncols=5, plot_width=250, plot_height=150) show(grid)
Example #3
Source File: coKriging.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def plot_cross_variograms(trace, lags, df, n_exp=2, n_gaus=2, iter_plot=200, experimental=None): n_equations = trace['weights'].shape[1] n_iter = trace['weights'].shape[0] lags_tiled = np.tile(lags, (iter_plot, 1)) b_var = [] for i in range(0, df.shape[1]): # n_equations, (n_exp+n_gaus)): # Init tensor b = np.zeros((len(lags), n_iter, 0)) for i_exp in range(0, n_exp): # print(i_exp, "exp") b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gaus)] * exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp]))) for i_gaus in range(n_exp, n_gaus + n_exp): # print(i_gaus) b = np.dstack((b, trace['weights'][:, i_gaus + i * (n_exp + n_gaus)] * gaus_vario(lags, trace['sill'][:, i_gaus], trace['range'][:, i_gaus]))) # Sum the contributins of each function b_all = b.sum(axis=2) # Append each variable b_var.append(b_all[:, -iter_plot:].T) p_all = [] for e, el in enumerate(df.columns): p = bp.figure(x_axis_type="log") p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08) if experimental is not None: p.scatter(experimental['lags'], y=experimental[el], color='navy', size=2) p.title.text = el p.xaxis.axis_label = "lags" p.yaxis.axis_label = "Semivariance" p_all = np.append(p_all, p) grid = bl.gridplot(list(p_all), ncols=5, plot_width=200, plot_height=150) show(grid)
Example #4
Source File: health.py From choochoo with GNU General Public License v2.0 | 5 votes |
def health(): ''' # Health ''' ''' $contents ''' ''' ## Load Data Open a connection to the database and load the data we require. ''' s = session('-v2') health = std_health_statistics(s) ''' ## Health and Fitness ''' output_file(filename='/dev/null') fitness, fatigue = like(N.FITNESS_ANY, health.columns), like(N.FATIGUE_ANY, health.columns) colours = ['black'] * len(fitness) + ['red'] * len(fatigue) alphas = [1.0] * len(fitness) + [0.5] * len(fatigue) ff = multi_line_plot(900, 300, N.TIME, fitness + fatigue, health, colours, alphas=alphas) xrange = ff.x_range if ff else None add_multi_line_at_index(ff, N.TIME, fitness + fatigue, health, colours, alphas=alphas, index=-1) atd = std_distance_time_plot(900, 200, health, x_range=xrange) shr = multi_plot(900, 200, N.TIME, [N.DAILY_STEPS, N.REST_HR_BPM], health, ['grey', 'red'], alphas=[1, 0.5], x_range=xrange, rescale=True, plotters=[bar_plotter(dt.timedelta(hours=20)), dot_plotter()]) add_curve(shr, N.TIME, N.REST_HR_BPM, health, color='red', y_range_name=N.REST_HR_BPM) show(gridplot([[ff], [atd], [shr]]))
Example #5
Source File: plot.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _make_axes(self, plot): width, height = self.renderer.get_size(plot) x_axis, y_axis = None, None keys = self.layout.keys(full_grid=True) if self.xaxis: flip = self.shared_xaxis rotation = self.xrotation lsize = self._fontsize('xlabel').get('fontsize') tsize = self._fontsize('xticks', common=False).get('fontsize') xfactors = list(unique_iterator([wrap_tuple(k)[0] for k in keys])) x_axis = make_axis('x', width, xfactors, self.layout.kdims[0], flip=flip, rotation=rotation, label_size=lsize, tick_size=tsize) if self.yaxis and self.layout.ndims > 1: flip = self.shared_yaxis rotation = self.yrotation lsize = self._fontsize('ylabel').get('fontsize') tsize = self._fontsize('yticks', common=False).get('fontsize') yfactors = list(unique_iterator([k[1] for k in keys])) y_axis = make_axis('y', height, yfactors, self.layout.kdims[1], flip=flip, rotation=rotation, label_size=lsize, tick_size=tsize) if x_axis and y_axis: plot = filter_toolboxes(plot) r1, r2 = ([y_axis, plot], [None, x_axis]) if self.shared_xaxis: r1, r2 = r2, r1 if self.shared_yaxis: x_axis.margin = (0, 0, 0, 50) r1, r2 = r1[::-1], r2[::-1] plot = gridplot([r1, r2]) elif y_axis: models = [y_axis, plot] if self.shared_yaxis: models = models[::-1] plot = Row(*models) elif x_axis: models = [plot, x_axis] if self.shared_xaxis: models = models[::-1] plot = Column(*models) return plot
Example #6
Source File: plot.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def initialize_plot(self, ranges=None, plots=[]): ranges = self.compute_ranges(self.layout, self.keys[-1], None) passed_plots = list(plots) plots = [[None for c in range(self.cols)] for r in range(self.rows)] for i, coord in enumerate(self.layout.keys(full_grid=True)): r = i % self.rows c = i // self.rows subplot = self.subplots.get(wrap_tuple(coord), None) if subplot is not None: plot = subplot.initialize_plot(ranges=ranges, plots=passed_plots) plots[r][c] = plot passed_plots.append(plot) else: passed_plots.append(None) plot = gridplot(plots[::-1], merge_tools=self.merge_tools, sizing_mode=self.sizing_mode, toolbar_location=self.toolbar) plot = self._make_axes(plot) title = self._get_title_div(self.keys[-1]) if title: plot = Column(title, plot) self.handles['title'] = title self.handles['plot'] = plot self.handles['plots'] = plots self._update_callbacks(plot) if self.shared_datasource: self.sync_sources() if self.top_level: self.init_links() self.drawn = True return self.handles['plot']
Example #7
Source File: BokehRenderer.py From BAC0 with GNU Lesser General Public License v3.0 | 5 votes |
def modify_document(self, doc): doc.clear() self.build_plot() layout = gridplot(self.plots, ncols=2) doc.add_root(layout) self._pcb = doc.add_periodic_callback(self.update_data, 10000) return doc
Example #8
Source File: gallery_generator.py From arviz with Apache License 2.0 | 5 votes |
def exec_file(self): print("running {0}".format(self.filename)) thumbfile = op.join("example_thumbs", self.thumbfilename) cx, cy = self.thumbloc pngfile = op.join(self.target_dir, self.pngfilename) plt.close("all") if self.backend == "matplotlib": my_globals = {"pl": plt, "plt": plt} with open(self.filename, "r") as fp: code_text = fp.read() code_text = re.sub(r"(plt\.show\S+)", "", code_text) exec(compile(code_text, self.filename, "exec"), my_globals) fig = plt.gcf() fig.canvas.draw() fig.savefig(pngfile, dpi=75) elif self.backend == "bokeh": pngfile = thumbfile with open(self.filename, "r") as fp: code_text = fp.read() code_text += BOKEH_EXPORT_CODE.format(pngfilename=thumbfile) with rc_context(rc={"plot.bokeh.show": False}): exec( code_text, {"export_png": export_png, "ndarray": ndarray, "gridplot": gridplot}, ) create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)
Example #9
Source File: __init__.py From arviz with Apache License 2.0 | 5 votes |
def show_layout(ax, show=True, force_layout=False): """Create a layout and call bokeh show.""" if show is None: show = rcParams["plot.bokeh.show"] if show: import bokeh.plotting as bkp layout = create_layout(ax, force_layout=force_layout) bkp.show(layout)
Example #10
Source File: bokeh.py From backtrader_plotting with GNU General Public License v3.0 | 5 votes |
def get_analyzer_panel(self, analyzers: List[bt.Analyzer]) -> Optional[Panel]: if len(analyzers) == 0: return None table_width = int(self.p.scheme.analyzer_tab_width / self.p.scheme.analyzer_tab_num_cols) acolumns = [] for analyzer in analyzers: table_header, elements = self._tablegen.get_analyzers_tables(analyzer, table_width) acolumns.append(column([table_header] + elements)) childs = gridplot(acolumns, ncols=self.p.scheme.analyzer_tab_num_cols, toolbar_options={'logo': None}) return Panel(child=childs, title='Analyzers')
Example #11
Source File: bokeh.py From backtrader_plotting with GNU General Public License v3.0 | 5 votes |
def _get_nodata_panel(self): chart_grid = gridplot([], toolbar_location=self.p.scheme.toolbar_location, toolbar_options={'logo': None}) return Panel(child=chart_grid, title="No Data")
Example #12
Source File: dataIndicatorsHandler.py From stock with Apache License 2.0 | 5 votes |
def add_plot(stockStat, conf): p_list = [] logging.info("############################", type(conf["dic"])) # 循环 多个line 信息。 for key, val in enumerate(conf["dic"]): logging.info(key) logging.info(val) p1 = figure(width=1000, height=150, x_axis_type="datetime") # add renderers stockStat["date"] = pd.to_datetime(stockStat.index.values) # ["volume","volume_delta"] # 设置20个颜色循环,显示0 2 4 6 号序列。 p1.line(stockStat["date"], stockStat[val], color=Category20[20][key * 2]) # Set date format for x axis 格式化。 p1.xaxis.formatter = DatetimeTickFormatter( hours=["%Y-%m-%d"], days=["%Y-%m-%d"], months=["%Y-%m-%d"], years=["%Y-%m-%d"]) # p1.xaxis.major_label_orientation = radians(30) #可以旋转一个角度。 p_list.append([p1]) gp = gridplot(p_list) script, div = components(gp) return { "script": script, "div": div, "title": conf["title"], "desc": conf["desc"] }
Example #13
Source File: zmq_demo.py From pysdr with GNU General Public License v3.0 | 4 votes |
def main_doc(doc): # Frequncy Sink (line plot) fft_plot = pysdr.base_plot('Freq [MHz]', 'PSD [dB]', 'Frequency Sink', disable_horizontal_zooming=True) f = (np.linspace(-sample_rate/2.0, sample_rate/2.0, fft_size) + center_freq)/1e6 fft_line = fft_plot.line(f, np.zeros(len(f)), color="aqua", line_width=1) # set x values but use dummy values for y # Time Sink (line plot) time_plot = pysdr.base_plot('Time [ms]', ' ', 'Time Sink', disable_horizontal_zooming=True) t = np.linspace(0.0, samples_in_time_plots / sample_rate, samples_in_time_plots) * 1e3 # in ms timeI_line = time_plot.line(t, np.zeros(len(t)), color="aqua", line_width=1) # set x values but use dummy values for y timeQ_line = time_plot.line(t, np.zeros(len(t)), color="red", line_width=1) # set x values but use dummy values for y # Waterfall Sink ("image" plot) waterfall_plot = pysdr.base_plot(' ', 'Time', 'Waterfall', disable_all_zooming=True) waterfall_plot._set_x_range(0, fft_size) # Bokeh tries to automatically figure out range, but in this case we need to specify it waterfall_plot._set_y_range(0, waterfall_samples) waterfall_plot.axis.visible = False # i couldn't figure out how to update x axis when freq changes, so just hide them for now waterfall_data = waterfall_plot.image(image = [shared_buffer['waterfall']], # input has to be in list form x = 0, # start of x y = 0, # start of y dw = fft_size, # size of x dh = waterfall_samples, # size of y palette = "Spectral9") # closest thing to matlab's jet # IQ/Constellation Sink ("circle" plot) iq_plot = pysdr.base_plot(' ', ' ', 'IQ Plot') #iq_plot._set_x_range(-1.0, 1.0) # this is to keep it fixed at -1 to 1. you can also just zoom out with mouse wheel and it will stop auto-ranging #iq_plot._set_y_range(-1.0, 1.0) iq_data = iq_plot.circle(np.zeros(samples_in_time_plots), np.zeros(samples_in_time_plots), line_alpha=0.0, # setting line_width=0 didn't make it go away, but this works fill_color="aqua", fill_alpha=0.5, size=4) # size of circles # Utilization bar (standard plot defined in gui.py) utilization_plot = pysdr.utilization_bar(1.0) # sets top of bar to be 100% utilization_data = utilization_plot.quad(top=[shared_buffer['utilization']], bottom=[0], left=[0], right=[1], color="#B3DE69") #adds 1 rectangle # Add four plots to document, using the gridplot method of arranging them doc.add_root(utilization_plot) doc.add_root(gridplot([[fft_plot, time_plot], [waterfall_plot, iq_plot]], sizing_mode="scale_width", merge_tools=False)) # Spacer(width=20, sizing_mode="fixed") # This function gets called periodically, and is how the "real-time streaming mode" works def plot_update(): timeI_line.data_source.data['y'] = shared_buffer['i'] # send most recent I to time sink timeQ_line.data_source.data['y'] = shared_buffer['q'] # send most recent Q to time sink iq_data.data_source.data['x'] = shared_buffer['i'] # send most recent I to IQ iq_data.data_source.data['y'] = shared_buffer['q'] # send most recent Q to IQ fft_line.data_source.data['y'] = shared_buffer['psd'] # send most recent psd to freq sink waterfall_data.data_source.data['image'] = [shared_buffer['waterfall']] # send waterfall 2d array to waterfall sink utilization_data.data_source.data['top'] = [shared_buffer['utilization']] # send most recent utilization level (only need to adjust top of rectangle) # Add a periodic callback to be run every x milliseconds doc.add_periodic_callback(plot_update, 150) # pull out a theme from themes.py doc.theme = pysdr.black_and_white
Example #14
Source File: _plotting.py From backtesting.py with GNU Affero General Public License v3.0 | 4 votes |
def plot_heatmaps(heatmap: pd.Series, agg: str, ncols: int, filename: str = '', plot_width: int = 1200, open_browser: bool = True): if not (isinstance(heatmap, pd.Series) and isinstance(heatmap.index, pd.MultiIndex)): raise ValueError('heatmap must be heatmap Series as returned by ' '`Backtest.optimize(..., return_heatmap=True)`') _bokeh_reset(filename) param_combinations = combinations(heatmap.index.names, 2) dfs = [heatmap.groupby(list(dims)).agg(agg).to_frame(name='_Value') for dims in param_combinations] plots = [] cmap = LinearColorMapper(palette='Viridis256', low=min(df.min().min() for df in dfs), high=max(df.max().max() for df in dfs), nan_color='white') for df in dfs: name1, name2 = df.index.names level1 = df.index.levels[0].astype(str).tolist() level2 = df.index.levels[1].astype(str).tolist() df = df.reset_index() df[name1] = df[name1].astype('str') df[name2] = df[name2].astype('str') fig = _figure(x_range=level1, y_range=level2, x_axis_label=name1, y_axis_label=name2, plot_width=plot_width // ncols, plot_height=plot_width // ncols, tools='box_zoom,reset,save', tooltips=[(name1, '@' + name1), (name2, '@' + name2), ('Value', '@_Value{0.[000]}')]) fig.grid.grid_line_color = None fig.axis.axis_line_color = None fig.axis.major_tick_line_color = None fig.axis.major_label_standoff = 0 fig.rect(x=name1, y=name2, width=1, height=1, source=df, line_color=None, fill_color=dict(field='_Value', transform=cmap)) plots.append(fig) fig = gridplot( plots, ncols=ncols, toolbar_options=dict(logo=None), toolbar_location='above', merge_tools=True, ) show(fig, browser=None if open_browser else 'none') return fig
Example #15
Source File: dashboard.py From skein with BSD 3-Clause "New" or "Revised" License | 4 votes |
def build_html(): """Build the html, to be served by IndexHandler""" source = AjaxDataSource(data_url='./data', polling_interval=INTERVAL, method='GET') # OHLC plot p = figure(plot_height=400, title='OHLC', sizing_mode='scale_width', tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None, y_axis_location="right", y_axis_label="Price ($)") p.x_range.follow = "end" p.x_range.follow_interval = 100 p.x_range.range_padding = 0 p.line(x='time', y='average', alpha=0.25, line_width=3, color='black', source=source) p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue', source=source) p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2, color='black', source=source) p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source, alpha=0.8) # MACD plot p2 = figure(plot_height=200, title='MACD', sizing_mode='scale_width', x_range=p.x_range, x_axis_label='Time (s)', tools="xpan,xwheel_zoom,xbox_zoom,reset", y_axis_location="right") p2.line(x='time', y='macd', color='darkred', line_width=2, source=source) p2.line(x='time', y='macd9', color='navy', line_width=2, source=source) p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue', alpha=0.5, source=source) # Combine plots together plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000) # Compose html from plots and template script, div = components(plot, theme=theme) html = template.render(resources=CDN.render(), script=script, div=div) return html
Example #16
Source File: trial_viewer.py From autopilot with Mozilla Public License 2.0 | 4 votes |
def trial_viewer(step_data, roll_type = "ewm", roll_span=100, bar=False): """ Args: step_data: grad_data: """ step_data.loc[step_data['response'] == 'L','response'] = 0 step_data.loc[step_data['response'] == 'R','response'] = 1 step_data.loc[step_data['target'] == 'L','target'] = 0 step_data.loc[step_data['target'] == 'R','target'] = 1 palette = [cc.rainbow[i] for i in range(len(step_data['subject'].unique()))] palette = [cc.rainbow[i*15] for i in range(5)] mice = sorted(step_data['subject'].unique()) current_step = step_data.groupby('subject').last().reset_index() current_step = current_step[['subject','step']] plots = [] p = figure(x_range=step_data['subject'].unique(),title='Subject Steps', plot_height=200) p.xaxis.major_label_orientation = np.pi / 2 p.vbar(x=current_step['subject'], top=current_step['step'], width=0.9) plots.append(p) for i, (mus, group) in enumerate(step_data.groupby('subject')): if roll_type == "ewm": meancx = group['correct'].ewm(span=roll_span,ignore_na=True).mean() else: meancx = group['correct'].rolling(window=roll_span).mean() title_str = "{}, step: {}".format(mus, group.step.iloc[-1]) p = figure(plot_height=100,y_range=(0,1),title=title_str) if bar: hline = Span(location=bar, dimension="width", line_color='red', line_width=1) p.renderers.append(hline) p.line(group['trial_num'], meancx, color=palette[group['step'].iloc[0]-1]) plots.append(p) grid = gridplot(plots, ncols=1) show(grid)
Example #17
Source File: __init__.py From arviz with Apache License 2.0 | 4 votes |
def create_layout(ax, force_layout=False): """Transform bokeh array of figures to layout.""" ax = np.atleast_2d(ax) subplot_order = rcParams["plot.bokeh.layout.order"] if force_layout: from bokeh.layouts import gridplot as layout ax = ax.tolist() layout_args = { "sizing_mode": rcParams["plot.bokeh.layout.sizing_mode"], "toolbar_location": rcParams["plot.bokeh.layout.toolbar_location"], } elif any(item in subplot_order for item in ("row", "column")): # check number of rows match = re.match(r"(\d*)(row|column)", subplot_order) n = int(match.group(1)) if match.group(1) is not None else 1 subplot_order = match.group(2) # set up 1D list of axes ax = [item for item in ax.ravel().tolist() if item is not None] layout_args = {"sizing_mode": rcParams["plot.bokeh.layout.sizing_mode"]} if subplot_order == "row" and n == 1: from bokeh.layouts import row as layout elif subplot_order == "column" and n == 1: from bokeh.layouts import column as layout else: from bokeh.layouts import layout if n != 1: ax = np.array(ax + [None for _ in range(int(np.ceil(len(ax) / n)) - len(ax))]) if subplot_order == "row": ax = ax.reshape(n, -1) else: ax = ax.reshape(-1, n) ax = ax.tolist() else: if subplot_order in ("square", "square_trimmed"): ax = [item for item in ax.ravel().tolist() if item is not None] n = int(np.ceil(len(ax) ** 0.5)) ax = ax + [None for _ in range(n ** 2 - len(ax))] ax = np.array(ax).reshape(n, n) ax = ax.tolist() if (subplot_order == "square_trimmed") and any( all(item is None for item in row) for row in ax ): from bokeh.layouts import layout ax = [row for row in ax if not all(item is None for item in row)] layout_args = {"sizing_mode": rcParams["plot.bokeh.layout.sizing_mode"]} else: from bokeh.layouts import gridplot as layout layout_args = { "sizing_mode": rcParams["plot.bokeh.layout.sizing_mode"], "toolbar_location": rcParams["plot.bokeh.layout.toolbar_location"], } # ignore "fixed" sizing_mode without explicit width and height if layout_args.get("sizing_mode", "") == "fixed": layout_args.pop("sizing_mode") return layout(ax, **layout_args)
Example #18
Source File: bokeh.py From backtrader_plotting with GNU General Public License v3.0 | 4 votes |
def generate_model_tabs(self, fp: FigurePage, tradingdomain=None) -> List[Panel]: observers = [x for x in fp.figure_envs if isinstance(x.master, bt.Observer)] datas = [x for x in fp.figure_envs if isinstance(x.master, bt.DataBase)] inds = [x for x in fp.figure_envs if isinstance(x.master, bt.Indicator)] # now assign figures to tabs # 1. assign default tabs if no manual tab is assigned for figure in [x for x in datas if x.plottab is None]: figure.plottab = 'Plots' if self.is_tabs_single else 'Datas' for figure in [x for x in inds if x.plottab is None]: figure.plottab = 'Plots' if self.is_tabs_single else 'Indicators' for figure in [x for x in observers if x.plottab is None]: figure.plottab = 'Plots' if self.is_tabs_single else 'Observers' # 2. group panels by desired tabs # groupby expects the groups to be sorted or else will produce duplicated groups sorted_figs = list(itertools.chain(datas, inds, observers)) # 3. filter tradingdomains if tradingdomain is not None: filtered = [] for f in sorted_figs: lgs = f.get_tradingdomains() for lg in lgs: if lg is True or lg == tradingdomain: filtered.append(f) sorted_figs = filtered sorted_figs.sort(key=lambda x: x.plottab) tabgroups = itertools.groupby(sorted_figs, lambda x: x.plottab) panels = [] def build_panel(objects, panel_title): if len(objects) == 0: return Bokeh._sort_plotobjects(objects) g = gridplot([[x.figure] for x in objects], toolbar_options={'logo': None}, toolbar_location=self.p.scheme.toolbar_location, sizing_mode=self.p.scheme.plot_sizing_mode, ) panels.append(Panel(title=panel_title, child=g)) for tabname, figures in tabgroups: build_panel(list(figures), tabname) return panels # endregion
Example #19
Source File: layout.py From pairstrade-fyp-2019 with MIT License | 4 votes |
def main(): output_dir = "../../jupyter-py/output/" + get_current_time() execution_command = """ python ../../jupyter-py/backtest_pair.py --strategy_type {} --output_dir {} --backtest_start {} --backtest_end {} --stk0 {} --stk1 {} """ if backtest_params["strategy_type"] == "kalman": execution_command += " --kalman_estimation_length 200" elif backtest_params["strategy_type"] == "cointegration": execution_command += " --lookback 76" elif backtest_params["strategy_type"] == "distance": execution_command += " --lookback 70" execution_command= execution_command.format(backtest_params["strategy_type"], output_dir, backtest_params["backtest_start"], backtest_params["backtest_end"], backtest_params["stk_0"], backtest_params["stk_1"]) # os.system("rm -rf ../../jupyter-py/output") os.system(execution_command) stock_list = glob.glob("../../ib-data/nyse-daily-tech/*.csv") for i, file in enumerate(stock_list): stock_list[i] = os.path.basename(file)[:-4] # get results from log file backtest_df, trades_df = Decoder.get_strategy_status(output_dir) metrics_dict = Decoder.get_strategy_performance(output_dir) # build figures normalized_price_fig = build_normalized_price_fig(backtest_df) spread_fig = build_spread_fig(backtest_df, trades_df) pv_fig = build_pv_fig(backtest_df) widget_wb = build_widgets_wb(stock_list) # build_final_gridplot grid = gridplot([[widget_wb, normalized_price_fig], [pv_fig, spread_fig]], sizing_mode='fixed') curdoc().add_root(grid)
Example #20
Source File: base.py From Pandas-Bokeh with MIT License | 4 votes |
def plot_grid(children, show_plot=True, return_html=False, **kwargs): """Create a grid of plots rendered on separate canvases and shows the layout. plot_grid is designed to layout a set of plots. --------------------------------------------------------------- Parameters: -children (list of lists of Plot) – An array of plots to display in a grid, given as a list of lists of Plot objects. To leave a position in the grid empty, pass None for that position in the children list. OR list of Plot if called with ncols. OR an instance of GridSpec. - show_plot (bool, default=True) - Show the plot grid when function gets called - sizing_mode ("fixed", "stretch_both", "scale_width", "scale_height", "scale_both") – How will the items in the layout resize to fill the available space. Default is "fixed". For more information on the different modes see sizing_mode description on LayoutDOM. - toolbar_location (above, below, left, right) – Where the toolbar will be located, with respect to the grid. Default is above. If set to None, no toolbar will be attached to the grid. -ncols (int, optional) – Specify the number of columns you would like in your grid. You must only pass an un-nested list of plots (as opposed to a list of lists of plots) when using ncols. - plot_width (int, optional) – The width you would like all your plots to be - plot_height (int, optional) – The height you would like all your plots to be. - toolbar_options (dict, optional) – A dictionary of options that will be used to construct the grid’s toolbar (an instance of ToolbarBox). If none is supplied, ToolbarBox’s defaults will be used. - merge_tools (True, False) – Combine tools from all child plots into a single toolbar. ------------------------------------------------------------------- Returns: A row or column containing the grid toolbar and the grid of plots (depending on whether the toolbar is left/right or above/below). The grid is always a Column of Rows of plots.""" layout = gridplot(children=children, **kwargs) if show_plot: show(layout) if return_html: return embedded_html(layout) return layout
Example #21
Source File: coKriging.py From gempy with GNU Lesser General Public License v3.0 | 4 votes |
def plot_cross_variograms(self, iter_plot=200, trace=None, experimental=None): """ Plot the analytical cross-variogram of a given MCMC inference Args: iter_plot (int): Number of traces to plot trace (pymc3.trace): trace with the sill, range and weights of each property experimental (bool): if True plot the experimental variogram as well Returns: None """ if not trace: trace = self.trace assert trace, 'set the trace to the object' n_exp = self.n_exp n_gauss = self.n_gauss lags = self.lags # DEP- n_equations = trace['weights'].shape[1] n_iter = trace['weights'].shape[0] lags_tiled = np.tile(lags, (iter_plot, 1)) b_var = [] for i in range(0, self.n_properties): # DEP- n_equations, (n_exp+n_gaus)): # Init tensor b = np.zeros((len(lags), n_iter, 0)) for i_exp in range(0, n_exp): b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gauss)] * exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp]))) for i_gauss in range(n_exp, n_gauss + n_exp): b = np.dstack((b, trace['weights'][:, i_gauss + i * (n_exp + n_gauss)] * gaus_vario(lags, trace['sill'][:, i_gauss], trace['range'][:, i_gauss]))) # Sum the contributins of each function b_all = b.sum(axis=2) # Append each variable b_var.append(b_all[:, -iter_plot:].T) # Bokeh code to plot this p_all = [] for e, el in enumerate(self.properties): p = bp.figure()#x_axis_type="log") p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08) if experimental: p.scatter(self.lags, y=self.exp_var[el], color='navy', size=2) p.title.text = el p.xaxis.axis_label = "lags" p.yaxis.axis_label = "Semivariance" p_all = np.append(p_all, p) grid = bl.gridplot(list(p_all), ncols=5, plot_width=250, plot_height=150) show(grid)
Example #22
Source File: coKriging.py From gempy with GNU Lesser General Public License v3.0 | 4 votes |
def plot_cross_covariance(self, nuggets=False, iter_plot=200): """ Plot the cross covariance for the given properties Args: nuggets (numpy.array): subtracted nuggets iter_plot (int): number of traces to plot Returns: None """ n_exp = self.n_exp n_gauss = self.n_gauss trace = self.trace lags = self.lags n_equations = trace['weights'].shape[1] n_iter = trace['weights'].shape[0] lags_tiled = np.tile(lags, (iter_plot, 1)) b_var = [] for i in range(0, self.n_properties): # n_equations, (n_exp+n_gaus)): # Init tensor b = np.zeros((len(lags), n_iter, 0)) for i_exp in range(0, n_exp): # print(i_exp, "exp") b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gauss)] * exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp]))) for i_gaus in range(n_exp, n_gauss + n_exp): # print(i_gaus) b = np.dstack((b, trace['weights'][:, i_gaus + i * (n_exp + n_gauss)] * gaus_vario(lags, trace['sill'][:, i_gaus], trace['range'][:, i_gaus]))) # Sum the contributins of each function if nuggets: b_all = 1 - (b.sum(axis=2) + self.nuggets[i]) else: b_all = 1 - (b.sum(axis=2)) # Append each variable b_var.append(b_all[:, -iter_plot:].T) p_all = [] for e, el in enumerate(self.properties): p = bp.figure(x_axis_type="log") p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08) p.title.text = el p.xaxis.axis_label = "lags" p.yaxis.axis_label = "Semivariance" p_all = np.append(p_all, p) grid = bl.gridplot(list(p_all), ncols=5, plot_width=250, plot_height=150) show(grid)
Example #23
Source File: comparison_plot.py From estimagic with BSD 3-Clause "New" or "Revised" License | 4 votes |
def comparison_plot( results, color_dict=None, height=None, width=500, axis_for_every_parameter=False, x_padding=0.1, num_bins=50, ): """Make a comparison plot from a dictionary containing optimization results. Args: results (list): List of estimagic optimization results where the info can have been extended with 'model' and 'model_name' color_dict (dict): mapping from the model class names to colors. height (int): height of the plot. width (int): width of the plot (in pixels). axis_for_every_parameter (bool): if False the x axis is only shown once for every group of parameters. x_padding (float): the x_range is extended on each side by x_padding times the range of the data num_bins (int): number of bins Returns: source_dfs, grid """ source_dfs, plot_info = comparison_plot_inputs( results=results, x_padding=x_padding, num_bins=num_bins, color_dict=color_dict, fig_height=height, ) source_dict, figure_dict, glyph_dict = _create_comparison_plot_components( source_dfs=source_dfs, plot_info=plot_info, axis_for_every_parameter=axis_for_every_parameter, width=width, ) model_classes = sorted({res.info["model_class"] for res in results}) plots_with_callbacks = _add_callbacks( source_dict=source_dict, figure_dict=figure_dict, glyph_dict=glyph_dict, model_classes=model_classes, ) grid = gridplot(plots_with_callbacks, toolbar_location="right", ncols=1) show(grid) return source_dfs, grid