def process(self, inputs): """ Plot the lines from the input dataframe. The plotted lines are the columns in the input dataframe which are specified in the `lines` of node's `conf` The plot title is defined in the `title` of the node's `conf` Arguments ------- inputs: list list of input dataframes. Returns ------- Figure """ input_df = inputs[self.INPUT_PORT_NAME] num_points = self.conf['points'] stride = max(len(input_df) // num_points, 1) date_co = DateScale() linear_co = LinearScale() yax = Axis(label='', scale=linear_co, orientation='vertical') xax = Axis(label='Time', scale=date_co, orientation='horizontal') panzoom_main = PanZoom(scales={'x': [date_co]}) lines = [] for line in self.conf['lines']: col_name = line['column'] label_name = line['label'] color = line['color'] if (isinstance(input_df, cudf.DataFrame) or isinstance(input_df, dask_cudf.DataFrame)): line = Lines(x=input_df['datetime'][::stride].to_array(), y=input_df[col_name][::stride].to_array(), scales={ 'x': date_co, 'y': linear_co }, colors=[color], labels=[label_name], display_legend=True) else: line = Lines(x=input_df['datetime'][::stride], y=input_df[col_name][::stride], scales={ 'x': date_co, 'y': linear_co }, colors=[color], labels=[label_name], display_legend=True) lines.append(line) new_fig = Figure(marks=lines, axes=[yax, xax], title=self.conf['title'], interaction=panzoom_main) return {self.OUTPUT_PORT_NAME: new_fig}
def __init__(self): vals = getDefaultPosition() x_sc = LinearScale(min=0, max=4) y_sc = LinearScale(min=0, max=8) y_sc.reverse = True x_sc.allow_padding = False y_sc.allow_padding = False # -1 are the empty squares (not in output from network) col_sc = ColorScale(min=-1, max=1, colors=['red', 'white', 'black']) x_ax = Axis(label='X', scale=x_sc) y_ax = Axis(label='Y', scale=y_sc, orientation='vertical') bg = plt.gridheatmap(vals, scales={ 'column': x_sc, 'row': y_sc, 'color': col_sc }) self.board = bg fig = Figure(marks=[bg], axes=[x_ax, y_ax]) fig.min_aspect_ratio = 0.63 # Idfk why this makes it have an aspect ratio around 0.5 but w/e fig.max_aspect_ratio = 0.63 self.fig = fig
def __init__(self, rgb=False, **kwargs): self._color_scale = ColorScale(colors=['black', 'white'], min=0, max=1) scales = { 'x': LinearScale(allow_padding=False), 'y': LinearScale(allow_padding=False, orientation='vertical'), 'image': self._color_scale } if rgb: self._mark = ImageGL(image=np.zeros((1, 1, 3)), scales=scales) else: self._mark = ImageGL(image=np.zeros((1, 1)), scales=scales) self._rgb = rgb link((self._mark, 'visible'), (self, 'visible')) super().__init__(**kwargs)
def process(self, inputs): """ Plot the P & L graph from the `strategy_returns` column. `label` in the `conf` defines the stock symbol name Arguments ------- inputs: list list of input dataframes. Returns ------- Figure """ input_df = inputs[self.INPUT_PORT_NAME] if isinstance(input_df, dask_cudf.DataFrame): input_df = input_df.compute() # get the computed value label = 'stock' if 'label' in self.conf: label = self.conf['label'] num_points = self.conf['points'] stride = max(len(input_df) // num_points, 1) date_co = DateScale() linear_co = LinearScale() yax = Axis(label='Cumulative return', scale=linear_co, orientation='vertical') xax = Axis(label='Time', scale=date_co, orientation='horizontal') panzoom_main = PanZoom(scales={'x': [date_co]}) if (isinstance(input_df, cudf.DataFrame) or isinstance(input_df, dask_cudf.DataFrame)): line = Lines( x=input_df['datetime'][::stride].to_array(), y=(input_df['strategy_returns'].cumsum())[::stride].to_array(), scales={ 'x': date_co, 'y': linear_co }, colors=['blue'], labels=[label], display_legend=True) else: line = Lines(x=input_df['datetime'][::stride], y=(input_df['strategy_returns'].cumsum())[::stride], scales={ 'x': date_co, 'y': linear_co }, colors=['blue'], labels=[label], display_legend=True) new_fig = Figure(marks=[line], axes=[yax, xax], title='P & L', interaction=panzoom_main) return {self.OUTPUT_PORT_NAME: new_fig}
def __init__(self): self.threads = [] self.tick_server_process = None self.context = None self.socket = None self.df = pd.DataFrame(data={'AAPL': [], 'SMA1': [], 'SMA2': []}) self.x_sc = DateScale() self.y_sc = LinearScale() self.line = Lines(x=[], y=[], scales={ 'x': self.x_sc, 'y': self.y_sc }, stroke_width=2.5, display_legend=True, labels=['Asset Price'], colors=['dodgerblue']) self.sma1 = Lines(x=[], y=[], scales={ 'x': self.x_sc, 'y': self.y_sc }, stroke_width=1.5, display_legend=True, labels=['SMA1'], colors=['darkorange']) self.sma2 = Lines(x=[], y=[], scales={ 'x': self.x_sc, 'y': self.y_sc }, stroke_width=1.5, display_legend=True, labels=['SMA2'], colors=['limegreen']) self.ax_x = Axis(scale=self.x_sc, grid_lines='solid', label='Time') self.ax_y = Axis(scale=self.y_sc, orientation='vertical', tick_format='0.2f', grid_lines='solid', label='Price') self.fig = Figure(marks=[self.line, self.sma1, self.sma2], axes=[self.ax_x, self.ax_y], title='Streaming Data', legend_location='top-left', layout=Layout(flex='1 1 auto', width='100%')) display(HBox([self.fig]).add_class('theme-dark'))
def get_final_plot(self, quad_funcs=[np.abs, np.angle]): if not self.done.is_set(): raise Exception( "Cannot get final plot since plotter is not done or was not run." ) from bqplot import LinearScale, ColorScale, ColorAxis, Axis, Lines, Figure, Tooltip, HeatMap from bqplot.toolbar import Toolbar from ipywidgets import VBox, HBox if self.final_buffer is None: self.final_buffer = self._final_buffer.get() if self.plot_dims.value == 2: raise NotImplementedError( "2 dimensional get_final_plot not yet implemented.") elif self.plot_dims.value == 1: figs = [] for quad_func in quad_funcs: sx = LinearScale() sy = LinearScale() ax = Axis(label=self.axis_label(-1), scale=sx) ay = Axis( label= f"{self.descriptor.data_name} ({self.descriptor.data_unit})", scale=sy, orientation='vertical') line = Lines(x=self.x_values, y=quad_func(self.final_buffer), scales={ 'x': sx, 'y': sy }) fig = Figure(marks=[line], axes=[ax, ay], title=self.filter_name) figs.append(fig) if len(figs) <= 2: return HBox(figs) elif len(figs) == 4: return VBox([HBox([figs[0], figs[1]]), HBox([figs[2], figs[3]])]) elif len(figs) == 3 or len(figs) > 4: raise Exception("Please use 1, 2, or 4 quadrature functions.")
def make_guided_figure(injpeak, injnum=1): fsx = LinearScale() fsy = LinearScale() xax = Axis(label='seconds', scale=fsx) yax = Axis(label='uWatt', scale=fsy, orientation='vertical') flpr = bqplot.marks.Lines(x=injpeak.seconds, y=injpeak.xs_power, scales={ 'x': fsx, 'y': fsy }, colors=['black']) blpts = bqplot.marks.Scatter(x=injpeak.guided_bp_seconds, y=injpeak.guided_bp_power, scales={ 'x': fsx, 'y': fsy }) rngpts=bqplot.marks.Scatter(x=[injpeak.guided_intstart,injpeak.guided_intstop],\ y=[np.quantile(injpeak.final_xs_powerbl,0.25),np.quantile(injpeak.final_xs_powerbl,0.25)],\ scales={'x':fsx,'y':fsy}, colors=['gold'],marker='rectangle',default_skew=0.99,default_size=400) bls = [] for blseg in injpeak.blsegs: newbl = bqplot.marks.Lines(x=blseg.seconds, y=blseg.blvals, scales={ 'x': fsx, 'y': fsy }) bls.append(newbl) injpeak.plot_bls = bls fig=Figure(marks=[flpr,blpts,rngpts,*bls],axes=[xax,yax],min_aspect_ratio=1.2,\ fig_margin={'top':60, 'bottom':60, 'left':60, 'right':0}) fig.title = f'Injection {injnum}' blpts.enable_move = True blpts.restrict_y = True blpts.on_drag_end(injpeak.bl_guided_callback) rngpts.enable_move = True rngpts.restrict_x = True rngpts.on_drag_end(injpeak.rng_guided_callback) return fig
def create_figure(stock, dt_scale, sc, color_id, f, indicator_figure_height, figure_width, add_new_indicator): sc_co = LinearScale() ax_y = Axis(label='RSI', scale=sc_co, orientation='vertical') new_line = Lines(x=stock.datetime, y=stock['out'], scales={'x': dt_scale, 'y': sc_co}, colors=[CATEGORY20[color_id[0]]]) new_fig = Figure(marks=[new_line], axes=[ax_y]) new_fig.layout.height = indicator_figure_height new_fig.layout.width = figure_width figs = [new_line] # add new figure add_new_indicator(new_fig) return figs
def __init__(self): # Initialize the chart with a default ticker self.data_chart = pd.DataFrame() self.chart_dropdown_x = Dropdown(description='X-Axis', layout=Layout(width='380px')) self.chart_dropdown_y = Dropdown(description='Y-Axis', layout=Layout(width='380px')) self.x_sc = LinearScale() self.y_sc = LinearScale() self.tt = Tooltip(fields=['name', 'x', 'y'], formats=['', '.2f', '.2f']) self.scatter = Scatter(scales={ 'x': self.x_sc, 'y': self.y_sc }, colors=['dodgerblue'], tooltip=self.tt, unhovered_style={'opacity': 0.5}) self.ax_x = Axis(scale=self.x_sc) self.ax_y = Axis(scale=self.y_sc, orientation='vertical', tick_format='0.2f') self.fig = Figure(marks=[], axes=[self.ax_x, self.ax_y], animation_duration=1000, padding_x=0, layout={ 'width': "100%", 'height': "500px" }) self.data_grid = DataGrid(layout={'width': "720px", 'height': "200px"}) self.box = VBox([ HBox([self.fig]), HBox([self.chart_dropdown_x, self.chart_dropdown_y]) ]) display(self.box)
def on_update(but_event): u"""Update button click event handler.""" val_min = self._input_fmin.value val_mid = self._input_fmid.value val_max = self._input_fmax.value center = brain.data['center'] time_idx = brain.data['time_idx'] time_arr = brain.data['time'] if not val_min < val_mid < val_max: raise ValueError('Incorrect relationship between' + ' fmin, fmid, fmax. Given values ' + '{0}, {1}, {2}' .format(val_min, val_mid, val_max)) if center is None: # 'hot' or another linear color map dt_min = val_min dt_max = val_max else: # 'mne' or another divergent color map dt_min = -val_max dt_max = val_max self._lut = self._brain.update_lut(fmin=val_min, fmid=val_mid, fmax=val_max) k = 1 / (dt_max - dt_min) b = 1 - k * dt_max self._brain.data['k'] = k self._brain.data['b'] = b for v in brain.views: for h in brain.hemis: if (time_arr is None) or (time_idx is None): act_data = brain.data[h + '_array'] else: act_data = brain.data[h + '_array'][:, time_idx] smooth_mat = brain.data[h + '_smooth_mat'] act_data = smooth_mat.dot(act_data) act_data = k * act_data + b act_data = np.clip(act_data, 0, 1) act_color_new = self._lut(act_data) brain.overlays[h + '_' + v].color = act_color_new self._update_colors() x_sc, col_sc = LinearScale(), ColorScale(colors=self._colors) ax_x = Axis(scale=x_sc) heat = HeatMap(x=cbar_ticks, color=color, scales={'x': x_sc, 'color': col_sc}) cbar_fig.axes = [ax_x] cbar_fig.marks = [heat]
def create_figure(stock, dt_scale, sc, color_id, f, indicator_figure_height, figure_width, add_new_indicator): sc_co = LinearScale() sc_co2 = LinearScale() ax_y = Axis(label='Bollinger b1', scale=sc_co, orientation='vertical') ax_y2 = Axis(label='Bollinger b2', scale=sc_co2, orientation='vertical', side='right') new_line = Lines(x=stock.datetime.to_array(), y=stock['out0'].to_array(), scales={'x': dt_scale, 'y': sc_co}, colors=[CATEGORY20[color_id[0]]]) new_line2 = Lines(x=stock.datetime.to_array(), y=stock['out1'].to_array(), scales={'x': dt_scale, 'y': sc_co2}, colors=[CATEGORY20[(color_id[0] + 1) % len(CATEGORY20)]]) new_fig = Figure(marks=[new_line, new_line2], axes=[ax_y, ax_y2]) new_fig.layout.height = indicator_figure_height new_fig.layout.width = figure_width figs = [new_line, new_line2] add_new_indicator(new_fig) return figs
def create_figure(stock, dt_scale, sc, color_id, f, indicator_figure_height, figure_width, add_new_indicator): sc_co = LinearScale() sc_co2 = LinearScale() sc_co3 = LinearScale() sc_co4 = LinearScale() sc_co5 = LinearScale() sc_co6 = LinearScale() sc_co7 = LinearScale() ax_y = Axis(label='PPSR PP', scale=sc_co, orientation='vertical') ax_y2 = Axis(label='PPSR R1', scale=sc_co2, orientation='vertical', side='right') ax_y3 = Axis(label='PPSR S1', scale=sc_co3, orientation='vertical', side='right') ax_y4 = Axis(label='PPSR R2', scale=sc_co4, orientation='vertical', side='right') ax_y5 = Axis(label='PPSR S2', scale=sc_co5, orientation='vertical', side='right') ax_y6 = Axis(label='PPSR R3', scale=sc_co6, orientation='vertical', side='right') ax_y7 = Axis(label='PPSR S3', scale=sc_co7, orientation='vertical', side='right') new_line = Lines(x=stock.datetime.to_array(), y=stock['out0'].to_array(), scales={'x': dt_scale, 'y': sc_co}, colors=[CATEGORY20[color_id[0]]]) new_line2 = Lines(x=stock.datetime.to_array(), y=stock['out1'].to_array(), scales={'x': dt_scale, 'y': sc_co2}, colors=[CATEGORY20[(color_id[0] + 1) % len(CATEGORY20)]]) new_line3 = Lines(x=stock.datetime.to_array(), y=stock['out2'].to_array(), scales={'x': dt_scale, 'y': sc_co3}, colors=[CATEGORY20[(color_id[0] + 2) % len(CATEGORY20)]]) new_line4 = Lines(x=stock.datetime.to_array(), y=stock['out3'].to_array(), scales={'x': dt_scale, 'y': sc_co4}, colors=[CATEGORY20[(color_id[0] + 3) % len(CATEGORY20)]]) new_line5 = Lines(x=stock.datetime.to_array(), y=stock['out4'].to_array(), scales={'x': dt_scale, 'y': sc_co5}, colors=[CATEGORY20[(color_id[0] + 4) % len(CATEGORY20)]]) new_line6 = Lines(x=stock.datetime.to_array(), y=stock['out5'].to_array(), scales={'x': dt_scale, 'y': sc_co6}, colors=[CATEGORY20[(color_id[0] + 5) % len(CATEGORY20)]]) new_line7 = Lines(x=stock.datetime.to_array(), y=stock['out6'].to_array(), scales={'x': dt_scale, 'y': sc_co7}, colors=[CATEGORY20[(color_id[0] + 6) % len(CATEGORY20)]]) new_fig = Figure(marks=[new_line, new_line2, new_line3, new_line4, new_line5, new_line6, new_line7], axes=[ax_y, ax_y2, ax_y3, ax_y4, ax_y5, ax_y6, ax_y7]) new_fig.layout.height = indicator_figure_height new_fig.layout.width = figure_width figs = [new_line, new_line2, new_line3, new_line4, new_line5, new_line6, new_line7] add_new_indicator(new_fig) return figs
def first_time(): percentage, names = update_data(sheet, question) x_ord = OrdinalScale(domain=names) y_sc = LinearScale() bar = Bars(x=names, y=percentage, scales={'x': x_ord, 'y': y_sc}) ax_x = Axis(scale=x_ord, grid_lines='solid', label='') ax_y = Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Percent') fig = Figure(marks=[bar], axes=[ax_x, ax_y], title=question) return fig
def __init__(self): self.niveau = Dropdown(options=[('Niveau {}'.format(i), i) for i in RushHour.niveaux()]) self.niveau.observe(lambda widget: self.change_niveau(widget.owner.value)) self.voiture = Dropdown(options=[]) self.modele = Plateau(1) self.vue = Figure(scale_x = LinearScale(min=0, max=self.modele.dimension), scale_y = LinearScale(min=self.modele.dimension, max=0)) self.vue.layout.width="75ex" self.vue.layout.width="75ex" self.vue.layout.height=self.vue.layout.width; self.vue.vue_voitures = {} for lettre, couleur in couleurs.items(): vue_voiture = Lines(x=[], y=[], scales={'x':self.vue.scale_x, 'y':self.vue.scale_y}, fill='inside', colors=[couleurs[lettre]], visible=False, tooltip=Tooltip(fields=["lettre"],show_labels=False), ) vue_voiture.lettre = "coucou" # lettre vue_voiture.on_click(lambda vue_voiture, _: self.choix_voiture(vue_voiture.lettre)) self.vue.vue_voitures[lettre] = vue_voiture self.vue.marks = list(self.vue.vue_voitures.values()) boutton_solution = Button(description="Solution") boutton_solution.on_click(self.montre_solution) VBox.__init__(self, [HBox([self.niveau, boutton_solution]), self.vue, self.boutton_direction('U'), HBox([self.boutton_direction('L'), self.voiture, self.boutton_direction('R')]), self.boutton_direction('D') ]) self.layout.align_items = 'center' self.change_niveau(1)
def __init__(self, model, key): param = model.params[key] if type(param.value) == np.ndarray and key != 'T13': self.n = len(param.value) else: self.n = 1 os = LinearScale() ls = LinearScale() ax_x = Axis(scale=os, grid_lines='solid', label='Iterations') ax_y = Axis(scale=ls, orientation='vertical', tick_format='0.2f', grid_lines='solid', label=key) colors = [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ] self.lines = [] for k in range(self.n): self.lines.append( Lines(x=np.array([]), y=np.array([]), scales={ 'x': os, 'y': ls }, colors=[colors[k]], stroke_width=2, display_legend=True, labels=['{}_{}'.format(key, k)])) super().__init__(marks=self.lines, axes=[ax_x, ax_y], title=key, legend_location='bottom-right')
def set_data(self, data, index, ylabel, add=False): # add decide whether draw figure on top if isinstance(data, pd.Series): self.data = data elif isinstance(data, pd.DataFrame): # Pandas DataFrame if index is not None: self.data = data.set_index(index) else: self.data = data else: print("The input data type is not supported") self.xlabel = self.data.index.name if self.data.index.name is not None else "index" self.cols = list(self.data) self.legends = [' '.join(legend) for legend in self.cols] if ylabel is not None: self.ylabel = ylabel elif len(self.data.columns.levels[0]) == 1: self.legends = [' '.join(legend[1::]) for legend in self.cols] else: self.ylabel = '' self.xScale = LinearScale() self.yScale = LinearScale() self.create_fig(self.data)
def process(self, inputs): """ Takes `datetime`, `open`, `close`, `high`, `volume` columns in the dataframe to plot the bqplot figure for this stock. Arguments ------- inputs: list list of input dataframes. Returns ------- bqplot.Figure """ stock = inputs[0] num_points = self.conf['points'] stride = max(len(stock) // num_points, 1) label = 'stock' if 'label' in self.conf: label = self.conf['label'] sc = LinearScale() sc2 = LinearScale() dt_scale = DateScale() ax_x = Axis(label='Date', scale=dt_scale) ax_y = Axis(label='Price', scale=sc, orientation='vertical', tick_format='0.0f') # Construct the marks ohlc = OHLC(x=stock['datetime'][::stride], y=stock[['open', 'high', 'low', 'close']] .as_gpu_matrix()[::stride, :], marker='candle', scales={'x': dt_scale, 'y': sc}, format='ohlc', stroke='blue', display_legend=True, labels=[label]) bar = Bars(x=stock['datetime'][::stride], y=stock['volume'][::stride], scales={'x': dt_scale, 'y': sc2}, padding=0.2) def_tt = Tooltip(fields=['x', 'y'], formats=['%Y-%m-%d', '.2f']) bar.tooltip = def_tt bar.interactions = { 'legend_hover': 'highlight_axes', 'hover': 'tooltip', 'click': 'select', } sc.min = stock['close'].min() - 0.3 * \ (stock['close'].max() - stock['close'].min()) sc.max = stock['close'].max() sc2.max = stock['volume'].max()*4.0 f = Figure(axes=[ax_x, ax_y], marks=[ohlc, bar], fig_margin={"top": 0, "bottom": 60, "left": 60, "right": 60}) return f
def create_figure(stock, dt_scale, sc, color_id, f, indicator_figure_height, figure_width, add_new_indicator): sc_co = LinearScale() ax_y = Axis(label='MACD', scale=sc_co, orientation='vertical') new_line = Lines(x=stock.datetime.to_array(), y=[stock['out0'].to_array(), stock['out1'].to_array(), stock['out2'].to_array()], scales={'x': dt_scale, 'y': sc_co}) new_fig = Figure(marks=[new_line], axes=[ax_y]) new_fig.layout.height = indicator_figure_height new_fig.layout.width = figure_width figs = [new_line] # add new figure add_new_indicator(new_fig) return figs
def get_figs(self): x = OrdinalScale() y = LinearScale() # because it is common to all kernels, all kernels react # each time a state is set on a kernel col_sc = OrdinalColorScale(colors=['White', 'Green', 'Red']) figs = [] for kernel_id in self.config['kernels'].keys(): bar = Bars(x=[0], y=[[0]], scales={'x': x, 'y': y, 'color': col_sc}, orientation='horizontal')#, stroke='White') xax = Axis(scale=x, orientation='vertical') yax = Axis(scale=y, orientation='horizontal', num_ticks=0) bar.color = ['White'] bar.on_hover(show_func) ins = button bar.tooltip = ins fig = Figure(marks=[bar], axes=[xax, yax], background_style={'fill': 'White'}, layout=Layout(width='99%', height='10px'), fig_margin={'top': 0, 'bottom': 0, 'left': 0, 'right': 0}) figs.append(fig) bars.append(bar) return figs
def get_figs(self, opname, color): x = OrdinalScale() y = LinearScale() col_sc = OrdinalColorScale(colors=['White', color]) figs = [] for _ in range(self.fpga.config[f'{opname}_nb']): time = [[0, 0], [0, 0]] busy = [False, False] bar = Bars(x=[0], y=time, scales={'x': x, 'y': y, 'color': col_sc}, orientation='horizontal', stroke='White') xax = Axis(scale=x, orientation='vertical') yax = Axis(scale=y, orientation='horizontal', num_ticks=0) bar.color = busy fig = Figure(marks=[bar], axes=[xax, yax], background_style={'fill': 'White'}, layout=Layout(width='99%', height='10px'), fig_margin={'top': 0, 'bottom': 0, 'left': 0, 'right': 0}) figs.append(fig) return figs
def __init__(self, model, **kwargs): # Get data from model self._data = model.results.power_generated # type: Pandas dataframe self._gens = list(self._data.columns) # type: list # retrieve keyword args self._bar_colors = kwargs.get('bar_colors') self._selected_gen = kwargs.get('selected_gen') self._enable_tooltip = kwargs.get('enable_tooltip', True) self._custom_tooltip = kwargs.get('custom_tooltip') # Set and adjust vars for bar chart tt = self._make_tooltip() self._x_data = range(1, len(self._data) + 1) self._y_data = [] for gen in self._gens: self._y_data.append(self._data[gen].as_matrix()) x_sc = OrdinalScale() y_sc = LinearScale() # Set essential bar chart attributes if self._bar_colors: self.colors = self._bar_colors self._all_colors = self.colors self.display_legend = True self.padding = 0.2 self.scales = {'x': x_sc, 'y': y_sc} self.tooltip = tt self.x = self._x_data self.set_y() # Construct bqplot Bars object super(GenDispatchBars, self).__init__(**kwargs)
def soln_comparison(df, title=None): """ Returns an ordered horizontal bar chart comparing a given value over multiple solutions. Args: df: pandas DataFrame with solution names as the index and one column of numerical data (if there is more than one column it will plot the first one). title: Optional title for the chart Returns: bqplot Figure object """ val_name = df.columns[0] df = df.sort_values(by=[val_name], ascending=False) title = f'{val_name} comparison' if title is None else title y_scale = LinearScale() y_axis = Axis(scale=y_scale, label=val_name, orientation='horizontal') x_scale = OrdinalScale() x_axis = Axis(scale=x_scale, grid_lines='none', orientation='vertical') bars = Bars(x=df.index.values, y=df[val_name].values, scales={ 'x': x_scale, 'y': y_scale }, orientation='horizontal') fig = Figure(marks=[bars], axes=[x_axis, y_axis], padding_y=0, title=title, fig_margin={ 'top': 60, 'bottom': 60, 'left': 200, 'right': 60 }) return fig
def init_dashboard(self): from bqplot import DateScale, LinearScale, DateScale, Axis, Lines, Figure, Tooltip from bqplot.colorschemes import CATEGORY10, CATEGORY20 from bqplot.toolbar import Toolbar from ipywidgets import VBox, Tab from IPython.display import display from tornado import gen cpu_sx = LinearScale() cpu_sy = LinearScale() cpu_x = Axis(label='Time (s)', scale=cpu_sx) cpu_y = Axis(label='CPU Usage (%)', scale=cpu_sy, orientation='vertical') mem_sx = LinearScale() mem_sy = LinearScale() mem_x = Axis(label='Time (s)', scale=mem_sx) mem_y = Axis(label='Memory Usage (MB)', scale=mem_sy, orientation='vertical') thru_sx = LinearScale() thru_sy = LinearScale() thru_x = Axis(label='Time (s)', scale=thru_sx) thru_y = Axis(label='Data Processed (MB)', scale=thru_sy, orientation='vertical') colors = CATEGORY20 tt = Tooltip(fields=['name'], labels=['Filter Name']) self.cpu_lines = { str(n): Lines(labels=[str(n)], x=[0.0], y=[0.0], colors=[colors[i]], tooltip=tt, scales={ 'x': cpu_sx, 'y': cpu_sy }) for i, n in enumerate(self.other_nodes) } self.mem_lines = { str(n): Lines(labels=[str(n)], x=[0.0], y=[0.0], colors=[colors[i]], tooltip=tt, scales={ 'x': mem_sx, 'y': mem_sy }) for i, n in enumerate(self.other_nodes) } self.thru_lines = { str(n): Lines(labels=[str(n)], x=[0.0], y=[0.0], colors=[colors[i]], tooltip=tt, scales={ 'x': thru_sx, 'y': thru_sy }) for i, n in enumerate(self.other_nodes) } self.cpu_fig = Figure(marks=list(self.cpu_lines.values()), axes=[cpu_x, cpu_y], title='CPU Usage', animation_duration=50) self.mem_fig = Figure(marks=list(self.mem_lines.values()), axes=[mem_x, mem_y], title='Memory Usage', animation_duration=50) self.thru_fig = Figure(marks=list(self.thru_lines.values()), axes=[thru_x, thru_y], title='Data Processed', animation_duration=50) tab = Tab() tab.children = [self.cpu_fig, self.mem_fig, self.thru_fig] tab.set_title(0, 'CPU') tab.set_title(1, 'Memory') tab.set_title(2, 'Throughput') display(tab) perf_queue = Queue() self.exit_perf = Event() def wait_for_perf_updates(q, exit, cpu_lines, mem_lines, thru_lines): while not exit.is_set(): messages = [] while not exit.is_set(): try: messages.append(q.get(False)) except queue.Empty as e: time.sleep(0.05) break for message in messages: filter_name, time_val, cpu, mem_info, processed = message mem = mem_info[0] / 2.**20 vmem = mem_info[1] / 2.**20 proc = processed / 2.**20 cpu_lines[filter_name].x = np.append( cpu_lines[filter_name].x, [time_val.total_seconds()]) cpu_lines[filter_name].y = np.append( cpu_lines[filter_name].y, [cpu]) mem_lines[filter_name].x = np.append( mem_lines[filter_name].x, [time_val.total_seconds()]) mem_lines[filter_name].y = np.append( mem_lines[filter_name].y, [mem]) thru_lines[filter_name].x = np.append( thru_lines[filter_name].x, [time_val.total_seconds()]) thru_lines[filter_name].y = np.append( thru_lines[filter_name].y, [proc]) for n in self.other_nodes: n.perf_queue = perf_queue self.perf_thread = Thread(target=wait_for_perf_updates, args=(perf_queue, self.exit_perf, self.cpu_lines, self.mem_lines, self.thru_lines)) self.perf_thread.start()
def cost_display(n_days=7): users = widgets.IntText(value=8, description='Number of total users') storage_per_user = widgets.IntText(value=10, description='Storage per user (GB)') mem_per_user = widgets.IntText(value=2, description="RAM per user (GB)") machines = widgets.Dropdown( description='Machine', options=machines_list['Machine type'].values.tolist()) persistent = widgets.Dropdown(description="Persistent Storage?", options={ 'HDD': 'hdd', 'SSD': 'ssd' }, value='hdd') autoscaling = widgets.Checkbox(value=False, description='Autoscaling?') text_avg_num_machine = widgets.Text(value='', description='Average # Machines:') text_cost_machine = widgets.Text(value='', description='Machine Cost:') text_cost_storage = widgets.Text(value='', description='Storage Cost:') text_cost_total = widgets.Text(value='', description='Total Cost:') hr = widgets.HTML(value="---") # Define axes limits y_max = 100. date_stop, date_range = create_date_range(n_days) # Create axes and extra variables for the viz xs_hd = DateScale( min=date_start, max=date_stop, ) ys_hd = LinearScale(min=0., max=y_max) # Shading for weekends is_weekend = np.where([ii in [6, 7] for ii in date_range.dayofweek], 1, 0) is_weekend = is_weekend * (float(y_max) + 50.) is_weekend[is_weekend == 0] = -10 line_fill = Lines(x=date_range, y=is_weekend, scales={ 'x': xs_hd, 'y': ys_hd }, colors=['black'], fill_opacities=[.2], fill='bottom') # Set up hand draw widget line_hd = Lines(x=date_range, y=10 * np.ones(len(date_range)), scales={ 'x': xs_hd, 'y': ys_hd }, colors=['#E46E2E']) line_users = Lines(x=date_range, y=10 * np.ones(len(date_range)), scales={ 'x': xs_hd, 'y': ys_hd }, colors=['#e5e5e5']) line_autoscale = Lines(x=date_range, y=10 * np.ones(len(date_range)), scales={ 'x': xs_hd, 'y': ys_hd }, colors=['#000000']) handdraw = HandDraw(lines=line_hd) xax = Axis(scale=xs_hd, label='Day', grid_lines='none', tick_format='%b %d') yax = Axis(scale=ys_hd, label='Numer of Users', orientation='vertical', grid_lines='none') # FIXME add `line_autoscale` when autoscale is enabled fig = Figure(marks=[line_fill, line_hd, line_users], axes=[xax, yax], interaction=handdraw) def _update_cost(change): # Pull values from the plot max_users = max(handdraw.lines.y) max_buffer = max_users * 1.05 # 5% buffer line_users.y = [max_buffer] * len(handdraw.lines.y) if max_users > users.value: users.value = max_users autoscaled_users = autoscale(handdraw.lines.y) line_autoscale.y = autoscaled_users # Calculate costs active_machine = machines_list[machines_list['Machine type'] == machines.value] machine_cost = active_machine['Price (USD / hr)'].values.astype( float) * 24 # To make it cost per day users_for_cost = autoscaled_users if autoscaling.value is True else [ max_buffer ] * len(handdraw.lines.y) num_machines = calculate_machines_needed(users_for_cost, mem_per_user.value, active_machine) avg_num_machines = np.mean(num_machines) cost_machine = integrate_cost(num_machines, machine_cost) cost_storage = integrate_cost( num_machines, storage_cost[persistent.value] * storage_per_user.value) cost_total = cost_machine + cost_storage # Set the values for iwidget, icost in [(text_cost_machine, cost_machine), (text_cost_storage, cost_storage), (text_cost_total, cost_total), (text_avg_num_machine, avg_num_machines)]: if iwidget is not text_avg_num_machine: icost = locale.currency(icost, grouping=True) else: icost = '{:.2f}'.format(icost) iwidget.value = icost # Set the color if autoscaling.value is True: line_autoscale.colors = ['#000000'] line_users.colors = ['#e5e5e5'] else: line_autoscale.colors = ['#e5e5e5'] line_users.colors = ['#000000'] line_hd.observe(_update_cost, names='y') # autoscaling.observe(_update_cost) # FIXME Uncomment when we implement autoscaling persistent.observe(_update_cost) machines.observe(_update_cost) storage_per_user.observe(_update_cost) mem_per_user.observe(_update_cost) # Show it fig.title = 'Draw your usage pattern over time.' # FIXME autoscaling when it's ready display(users, machines, mem_per_user, storage_per_user, persistent, fig, hr, text_cost_machine, text_avg_num_machine, text_cost_storage, text_cost_total) return fig
def show_pipeline(self, subgraph=None, pipeline_name=None): """If a pipeline name is specified query the database, otherwise show the current pipeline.""" if subgraph: graph = subgraph elif pipeline_name: cs = self.session.query( adb.Connection).filter_by(pipeline_name=pipeline_name).all() if len(cs) == 0: print(f"No results for pipeline {pipeline_name}") return temp_edges = [(c.node1.hash_val, c.node2.hash_val, { 'connector_in': c.node2_name, 'connector_out': c.node1_name }) for c in cs] nodes = set([c.node1 for c in cs] + [c.node2 for c in cs]) for node in nodes: self.meas_graph.add_node(node.hash_val, node_obj=node) graph = nx.DiGraph() graph.add_edges_from(temp_edges) else: graph = self.meas_graph if not graph or len(graph.nodes()) == 0: raise Exception( "Could not find any nodes. Has a pipeline been created (try running create_default_pipeline())" ) else: from bqplot import Figure, LinearScale from bqplot.marks import Graph, Lines, Label from ipywidgets import Layout, HTML from IPython.display import HTML as IPHTML, display # nodes = list(dgraph.nodes()) indices = {n: i for i, n in enumerate(graph.nodes())} node_data = [{ 'label': dat['node_obj'].node_label(), 'data': dat['node_obj'].print(show=False) } for n, dat in graph.nodes(data=True)] link_data = [{ 'source': indices[s], 'target': indices[t] } for s, t in graph.edges()] # Update the tooltip chart table = HTML( "<b>Re-evaluate this plot to see information about filters. Otherwise it will be stale.</b>" ) table.add_class("hover_tooltip") display( IPHTML(""" <style> .hover_tooltip table { border-collapse: collapse; padding: 8px; } .hover_tooltip th, .hover_tooltip td { text-align: left; padding: 8px; } .hover_tooltip tr:nth-child(even) { background-color: #cccccc; padding: 8px; } </style> """)) hovered_symbol = '' def hover_handler(self, content, hovered_symbol=hovered_symbol, table=table): symbol = content.get('data', '') if (symbol != hovered_symbol): hovered_symbol = symbol table.value = symbol['data'] sel_objs = [ dat['node_obj'] for n, dat in graph.nodes(data=True) if isinstance(dat['node_obj'], adb.StreamSelect) ] sel_objs.sort(key=lambda x: x.qubit_name) selectors = [sel.hash_val for sel in sel_objs] qubit_names = [sel.qubit_name for sel in sel_objs] pipeline_names = [ sel.qubit_name if qubit_names.count(sel.qubit_name) == 1 else sel.qubit_name + " " + sel.stream_type for sel in sel_objs ] loc = {} def next_level(nodes, iteration=0, offset=0, accum=[]): if len(accum) == 0: loc[nodes[0]] = {'x': 0, 'y': 0} accum = [nodes] next_gen_nodes = list( reduce(operator.add, [list(graph.successors(n)) for n in nodes])) l = len(next_gen_nodes) if l > 0: for k, n in enumerate(next_gen_nodes): loc[n] = {'x': k, 'y': -(iteration + 1)} accum.append(next_gen_nodes) return next_level(next_gen_nodes, iteration=iteration + 1, offset=2.5 * l, accum=accum) else: return accum hierarchy = [next_level([q]) for q in selectors] widest = [max([len(row) for row in qh]) for qh in hierarchy] for i in range(1, len(selectors)): offset = sum(widest[:i]) loc[selectors[i]]['x'] += offset for n in nx.descendants(graph, selectors[i]): loc[n]['x'] += offset x = [loc[n]['x'] for n in graph.nodes()] y = [loc[n]['y'] for n in graph.nodes()] xs = LinearScale(min=min(x) - 0.5, max=max(x) + 0.6) ys = LinearScale(min=min(y) - 0.5, max=max(y) + 0.6) fig_layout = Layout(width='960px', height='500px') graph = Graph(node_data=node_data, link_data=link_data, x=x, y=y, scales={ 'x': xs, 'y': ys }, link_type='line', colors=['orange'] * len(node_data), directed=True) bgs_lines = [] middles = [] for i in range(len(selectors)): if i == 0: start = -0.4 end = widest[0] - 0.6 elif i == len(selectors): start = sum(widest) - 0.4 end = max(x) + 0.4 else: start = sum(widest[:i]) - 0.4 end = sum(widest[:i + 1]) - 0.6 middles.append(0.5 * (start + end)) bgs_lines.append( Lines( x=[start, end], y=[[min(y) - 0.5, min(y) - 0.5], [max(y) + 0.5, max(y) + 0.5]], scales={ 'x': xs, 'y': ys }, fill='between', # opacity does not work with this option fill_opacities=[0.1 + 0.5 * i / len(selectors)], stroke_width=0.0)) labels = Label(x=middles, y=[max(y) + 0.65 for m in middles], text=pipeline_names, align='middle', scales={ 'x': xs, 'y': ys }, default_size=14, font_weight='bolder', colors=['#4f6367']) fig = Figure(marks=bgs_lines + [graph, labels], layout=fig_layout) graph.tooltip = table graph.on_hover(hover_handler) return fig
open_btn = widgets.Button(description="Open",disable=False, layout=Layout(width='10%')) file_box = Box([save_btn, open_btn]) file_box.layout.display = 'flex' file_box.layout.justify_content = 'flex-end' file_box.layout.align_itmes = 'stretch' control_box1 = VBox([HBox(m),HBox(params_box+[sound_chk, sound_btn]), HBox([add_btn, art_slt, delete_btn, replace_btn, play_all_btn])]) fig_margin_default = {'top':40, 'bottom':40, 'left':40, 'right':40} min_height_default = 10 min_width_default = 10 # Create Sound Wave plot container x_time = LinearScale(min=0., max=100) y_sound = LinearScale(min=-.5, max=.5) ax_sound_y = Axis(label='Amplitude', scale=y_sound, orientation='vertical', side='left', grid_lines='solid') ax_time_x = Axis(label='Time', scale=x_time, grid_lines='solid') #Initialization sound_line = Lines(x=[], y=[], colors=['Blue'], scales={'x': x_time, 'y': y_sound}, visible=True) fig_sound = plt.figure(marks=[sound_line], axes=[ax_time_x, ax_sound_y], title='Sound wave', fig_margin = fig_margin_default, min_height = min_height_default, min_widht = min_width_default, preserve_aspect=True) # Create Articulator Position Evolution Container y_art = LinearScale(min=-3., max=3.) ax_art_y = Axis(label='Position', scale=y_art, orientation='vertical', side='left', grid_lines='solid') # ax_time_x = Axis(label='Time', scale=x_time, grid_lines='solid') #Initialization art_lines = Lines(x=[], y=[], #colors=['Blue'],
def set_data(self, data, index, ylabel, add=False): self.alldims = list(data) self.xScale = LinearScale() #self.xScale.min, self.xScale.max = self.data.index.min(), self.data.index.max() # min=self.data.index.min(),max=self.data.index.max() self.xScale.allow_padding = False self.yScale = LinearScale() self.yScale.allow_padding = False # add decide whether draw figure on top if self.ptype == 'PCA': from sklearn.decomposition import IncrementalPCA ipca = IncrementalPCA(n_components=2, batch_size=3) # data.values if index is not None: Y = data[index].values xlist = list(data) #.columns xlist.remove(index) X = data[xlist].values else: X = data.values[:, :-1] Y = data.values[:, -1] ipca.fit(X) pca_data = ipca.transform(X) self.colors = Y cols = ['component1', 'component2'] df = pd.DataFrame(pca_data, columns=cols) self.data = df #.set_index('component1') self.cols = ['component2'] self.xlabel = 'component1' self.ylabel = 'component2' self.create_fig(self.data) return if isinstance(data, pd.Series): self.data = data elif isinstance(data, pd.DataFrame): # Pandas DataFrame if self.dims is not None and len(self.dims) > 1: self.data = data[self.dims[0:2]] #.set_index(self.dims[0]) self.colors = data.values[:, -1] if len( self.dims) == 2 else data[self.dims[2]].values self.data.index.name = self.dims[0] elif index is not None: self.data = data.set_index(index) else: self.data = data else: print("The input data type is not supported") self.xlabel = self.data.index.name if self.data.index.name is not None else "index" self.cols = list(self.data) if self.dims is None else self.dims[1] y = getattr(self.data.columns, "levels", None) if ylabel is not None: self.ylabel = ylabel elif y is None: # One level self.ylabel = '' self.legends = [legend for legend in self.cols] if self.xlabel in self.legends: self.legends.remove(self.xlabel) if self.dims is not None and len(self.dims) > 1: self.ylabel = self.dims[1] elif len(self.data.columns.levels[0]) == 1: self.legends = [' '.join(legend[1::]) for legend in self.cols] self.ylabel = self.data.columns.levels[0][0] else: self.ylabel = '' self.create_fig(self.data)
def __init__(self, brain): self._brain = brain self._input_fmin = None self._input_fmid = None self._input_fmax = None self._btn_upd_mesh = None self._colors = None if brain.data['center'] is None: dt_min = brain.data['fmin'] dt_max = brain.data['fmax'] else: dt_min = -brain.data['fmax'] dt_max = brain.data['fmax'] self._lut = brain.data['lut'] self._cbar_data = np.linspace(0, 1, self._lut.N) cbar_ticks = np.linspace(dt_min, dt_max, self._lut.N) color = np.array((self._cbar_data, self._cbar_data)) cbar_w = 500 cbar_fig_margin = {'top': 15, 'bottom': 15, 'left': 5, 'right': 5} self._update_colors() x_sc, col_sc = LinearScale(), ColorScale(colors=self._colors) ax_x = Axis(scale=x_sc) heat = HeatMap(x=cbar_ticks, color=color, scales={'x': x_sc, 'color': col_sc}) self._add_inputs() fig_layout = widgets.Layout(width='%dpx' % cbar_w, height='60px') cbar_fig = Figure(axes=[ax_x], marks=[heat], fig_margin=cbar_fig_margin, layout=fig_layout) def on_update(but_event): u"""Update button click event handler.""" val_min = self._input_fmin.value val_mid = self._input_fmid.value val_max = self._input_fmax.value center = brain.data['center'] time_idx = brain.data['time_idx'] time_arr = brain.data['time'] if not val_min < val_mid < val_max: raise ValueError('Incorrect relationship between' + ' fmin, fmid, fmax. Given values ' + '{0}, {1}, {2}' .format(val_min, val_mid, val_max)) if center is None: # 'hot' or another linear color map dt_min = val_min dt_max = val_max else: # 'mne' or another divergent color map dt_min = -val_max dt_max = val_max self._lut = self._brain.update_lut(fmin=val_min, fmid=val_mid, fmax=val_max) k = 1 / (dt_max - dt_min) b = 1 - k * dt_max self._brain.data['k'] = k self._brain.data['b'] = b for v in brain.views: for h in brain.hemis: if (time_arr is None) or (time_idx is None): act_data = brain.data[h + '_array'] else: act_data = brain.data[h + '_array'][:, time_idx] smooth_mat = brain.data[h + '_smooth_mat'] act_data = smooth_mat.dot(act_data) act_data = k * act_data + b act_data = np.clip(act_data, 0, 1) act_color_new = self._lut(act_data) brain.overlays[h + '_' + v].color = act_color_new self._update_colors() x_sc, col_sc = LinearScale(), ColorScale(colors=self._colors) ax_x = Axis(scale=x_sc) heat = HeatMap(x=cbar_ticks, color=color, scales={'x': x_sc, 'color': col_sc}) cbar_fig.axes = [ax_x] cbar_fig.marks = [heat] self._btn_upd_mesh.on_click(on_update) info_widget = widgets.VBox((cbar_fig, self._input_fmin, self._input_fmid, self._input_fmax, self._btn_upd_mesh)) ipv.gcc().children += (info_widget,)
year_label = Label(x=[0.75], y=[0.10], default_size=46, font_weight='bolder', colors=['orange'], text=[str(initial_year)], enable_move=True) # %% [markdown] # #### Defining Axes and Scales # # The inherent skewness of the income data favors the use of a `LogScale`. Also, since the color coding by regions does not follow an ordering, we use the `OrdinalColorScale`. # %% {"collapsed": true} x_sc = LogScale(min=income_min, max=income_max) y_sc = LinearScale(min=life_exp_min, max=life_exp_max) c_sc = OrdinalColorScale(domain=data['region'].unique().tolist(), colors=CATEGORY10[:6]) size_sc = LinearScale(min=pop_min, max=pop_max) # %% {"collapsed": true} ax_y = Axis(label='Life Expectancy', scale=y_sc, orientation='vertical', side='left', grid_lines='solid') ax_x = Axis(label='Income per Capita', scale=x_sc, grid_lines='solid') # %% [markdown] # #### Creating the Scatter Mark with the appropriate size and color parameters passed #
def __init__(self, volume=None, default_directory=os.getcwd(), title='', enhancement_steps=1000, **kwargs): def on_chosen_path_change(old_path, new_path): self.dataset = FolderDataset(new_path) # TODO: If the path doesn't contain images, display a warning # A widget for changing the image folder self.pathchooser = PathChooser( chosen_path_desc='Image folder:', default_directory=default_directory, on_chosen_path_change=on_chosen_path_change, ) self.pathchooser.layout.margin = '0 0 10px 0' # The number of increments of the min/max slider self.enhancement_steps = enhancement_steps self.scales = { 'x': LinearScale(), 'y': LinearScale(), } # The currently displayed image will be in bytes at `self.image_plot.image.value` self.image_plot = BQImage( image=IPyImage(), scales=self.scales, ) self.figure = Figure( marks=[self.image_plot], padding_x=0, padding_y=0, animation_duration=1000, fig_margin={ 'top': 0, 'right': 0, 'bottom': 0, 'left': 0, }, layout=Layout( grid_area='figure', margin='0', width='320px', height='320px', ), ) # Custom toolbar toolbar_width = '100%' toolbar_margin = '0px 0 2px 0' self.pan_zoom = PanZoom(scales={ 'x': [self.scales['x']], 'y': [self.scales['y']], }, ) self.save_button = Button( description='Save Image', tooltip='Save Image', icon='save', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.save_button.on_click(self.save_current_image) self.hide_button = Button( description='Hide Image', tooltip='Hide Image', icon='eye-slash', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, )) self.hide_button.on_click(self.hide_current_image) self.pan_zoom_toggle_button = ToggleButton( description='Pan / Zoom', tooltip='Pan/Zoom', icon='arrows', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.pan_zoom_toggle_button.observe(self.on_pan_zoom_toggle, names='value') self.reset_pan_zoom_button = Button( description='Undo Zoom', tooltip='Reset pan/zoom', icon='refresh', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.reset_pan_zoom_button.on_click(self.reset_pan_zoom) self.reset_enhancements_button = Button( description='Un-Enhance', tooltip='Reset enhancements', icon='ban', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.reset_enhancements_button.on_click(self.reset_enhancements) self.mini_map = IPyImage(layout=Layout( grid_area='mini-map', margin='0', )) self.mini_map.width = 180 self.mini_map.height = 180 # PERFORMANCE CONCERN # Ideally instead of four observations, this would observe 'scales' on `self.pan_zoom` # However, it doesn't fire updates # Ref: https://github.com/bloomberg/bqplot/issues/800 self.image_plot.scales['x'].observe(self.on_pan_zoom_change('x_min'), names='min') self.image_plot.scales['x'].observe(self.on_pan_zoom_change('x_max'), names='max') self.image_plot.scales['y'].observe(self.on_pan_zoom_change('y_min'), names='min') self.image_plot.scales['y'].observe(self.on_pan_zoom_change('y_max'), names='max') self.plane_toggle = ToggleButtons( options=['yz', 'xz', 'xy'], description='', disabled=False, button_style='', tooltips=[ 'Step in x direction', 'Step in y direction', 'Step in z direction' ], layout=Layout( width='200px', # flex='1 1 auto', margin='7px 0 auto auto', ), ) self.plane_toggle.style.button_width = 'auto' self.plane_toggle.observe(self.on_plane_change, names='value') self.toolbar = VBox( children=[ self.save_button, self.hide_button, self.pan_zoom_toggle_button, self.reset_pan_zoom_button, self.reset_enhancements_button, ], layout=Layout( grid_area='toolbar', margin='0', ), ) # Image enhancements self.min_max_slider = FloatRangeSlider( value=[0, 255], min=0, max=255, step=255 / self.enhancement_steps, description='Min/Max:', orientation='horizontal', readout=True, readout_format='.1f', continuous_update=True, layout=Layout( grid_area='min-max-slider', margin='10px 0 10px -10px', width='100%', ), ) self.min_max_slider.observe(self.on_min_max_change, names='value') self.index_slider = IntSlider( value=0, min=0, max=1, step=1, description='Index:', orientation='horizontal', readout=True, readout_format='d', continuous_update=True, layout=Layout( grid_area='index-slider', margin='8px -20px 10px -36px', width='100%', ), ) self.index_slider.observe(self.on_image_index_change, names='value') # Animation self.play = Play( value=self.index_slider.value, min=self.index_slider.min, max=self.index_slider.max, step=self.index_slider.step, ) jslink((self.play, 'value'), (self.index_slider, 'value')) # Keep 'max' in sync as well self.index_slider.observe(self.on_index_slider_max_change, names='max') self.bottom_bar = HBox( children=[ self.play, self.index_slider, self.plane_toggle, ], layout=Layout( grid_area='bottom-bar', margin=f'10px -20px 0 0', # overflow='hidden', )) # Layout self.gridbox = GridBox(children=[ self.figure, self.toolbar, self.mini_map, self.min_max_slider, self.bottom_bar, ], ) # Initially hidden without data self.gridbox.layout.display = 'none' self._dataset = None if volume is not None: self.dataset = VolumeDataset(volume) # Hide pathchooser when using a volume self.pathchooser.layout.display = 'none' # Call VBox super class __init__ super().__init__( children=[ self.pathchooser, self.gridbox, ], layout=Layout(width='auto'), **kwargs, )