def __init__(self): # Setup & Axis stuff... x_sc = LinearScale(min=0, max=8) y_sc = LinearScale(min=0, max=8) x_ax = Axis(label='X', scale=x_sc) y_ax = Axis(label='Y', scale=y_sc, orientation='vertical') y_sc.reverse = True col_sc = ColorScale(min=-1, max=1, colors=['white', 'blue', 'red']) bg = plt.gridheatmap(np.zeros((16, 16)), scales={ 'column': x_sc, 'row': y_sc, 'color': col_sc }) bg.row = np.arange(16) / 2 bg.column = np.arange(16) / 2 self.board = bg fig = Figure(marks=[bg], axes=[x_ax, y_ax]) # Force square. fig.min_aspect_ratio = 1 fig.max_aspect_ratio = 1 # Give random data self.update(np.random.random((8, 4, 4))) self.fig = fig
def create_image_figure(): scale_x = LinearScale(allow_padding=False) scale_y = LinearScale(allow_padding=False) scales = {'x': scale_x, 'y': scale_y} axis_x = Axis(scale=scales['x']) axis_y = Axis(scale=scales['y'], orientation='vertical') figure = Figure(scales=scales, axes=[axis_x, axis_y], min_aspect_ratio=1, max_aspect_ratio=1, fig_margin={ 'top': 0, 'bottom': 50, 'left': 50, 'right': 0 }) figure.layout.height = '400px' figure.layout.width = '400px' scales_image = { 'x': scale_x, 'y': scale_y, 'image': ColorScale(scheme='viridis') } # 'image': ColorScale(colors=['black', 'white'])} image = ImageGL(image=np.zeros((0, 0)), scales=scales_image) figure.marks = (image, ) return figure, image
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, canInteract=True): # Setup & Axis stuff... x_sc = LinearScale(min=0, max=8) y_sc = LinearScale(min=0, max=8) y_sc.reverse = True x_ax = Axis(label='X', scale=x_sc) y_ax = Axis(label='Y', scale=y_sc, orientation='vertical') # Display starting position for checkers game. # Colour checkerboard... Extra stuff for alignment to grid. vals = np.zeros((8, 8)) vals[::2, ::2] = -1 vals[1::2, 1::2] = -1 col_sc = ColorScale(colors=['white', 'lightgray']) bg = plt.gridheatmap(vals, scales={ 'column': x_sc, 'row': y_sc, 'color': col_sc }) bg.row = np.arange(8) bg.column = np.arange(8) self.bg = bg # Foreground... # colors of pieces col_sc = ColorScale(colors=['firebrick', 'black']) # Create empty scatter grid. fg = Scatter(x=[], y=[]) fg.scales = {'x': x_sc, 'y': y_sc, 'color': col_sc} fg.color = [] fg.default_size = 550 fg.enable_move = canInteract print(fg.drag_size) fg.drag_size = 0.1 print(fg.drag_size) self.fg = fg fig = Figure(marks=[bg, fg], axes=[x_ax, y_ax]) # Force square. fig.min_aspect_ratio = 1 fig.max_aspect_ratio = 1 # display(fig) self.fig = fig
def __init__(self, dataset, udf, roi=None, channel=None, title=None, min_delta=1 / 60, udfresult=None): super().__init__( dataset=dataset, udf=udf, roi=roi, channel=channel, title=title, min_delta=min_delta, udfresult=udfresult, ) # keep bqplot and bqplot_image_gl as optional dependencies from bqplot import Figure, LinearScale, Axis, ColorScale from bqplot_image_gl import ImageGL scale_x = LinearScale(min=0, max=1) # Make sure y points down # See https://libertem.github.io/LiberTEM/concepts.html#coordinate-system scale_y = LinearScale(min=1, max=0) scales = {'x': scale_x, 'y': scale_y} axis_x = Axis(scale=scale_x, label='x') axis_y = Axis(scale=scale_y, label='y', orientation='vertical') s = self.data.shape aspect = s[1] / s[0] figure = Figure(scales=scales, axes=[axis_x, axis_y], scale_x=scale_x, scale_y=scale_y, min_aspect_ratio=aspect, max_aspect_ratio=aspect, title=self.title) scales_image = { 'x': scale_x, 'y': scale_y, 'image': ColorScale(min=0, max=1) } dtype = np.result_type(self.data, np.int8) image = ImageGL(image=self.data.astype(dtype), scales=scales_image) figure.marks = (image, ) self.figure = figure self.image = image
def __init__(self): self.episode_grid_heat_map = GridHeatMap(color=np.random.rand(11, 51) * 0, scales={ 'row': OrdinalScale(), 'column': OrdinalScale(), 'color': ColorScale() }, display_legend=False) self.episode_grid_heat_map_label = widgets.Label() self.episode_grid_heat_map_figure = Figure( title='Episode grid heat map', marks=[self.episode_grid_heat_map], layout=widgets.Layout(height='331px', width='100%')) def heat_map_click_callback(a, b): if self.result_permutation is not None: episode = self.result_permutation[b['data']['_cell_num']] + 1 color = b['data']['color'] self.episode_grid_heat_map_label.value = \ f'clicked on episode {episode} with {color}'\ 'successful cases' self.episode_grid_heat_map.on_click(heat_map_click_callback) self.episode_grid_heat_map.on_element_click(heat_map_click_callback) super(HeatMap, self).__init__([ self.episode_grid_heat_map_figure, self.episode_grid_heat_map_label ])
def __init__(self): self.episode_grid_heat_map = GridHeatMap( color=np.random.rand(11, 51) * 0, scales={ "row": OrdinalScale(), "column": OrdinalScale(), "color": ColorScale(), }, display_legend=False, ) self.episode_grid_heat_map_label = widgets.Label() self.episode_grid_heat_map_figure = Figure( title="Episode grid heat map", marks=[self.episode_grid_heat_map], layout=widgets.Layout(height="331px", width="100%"), ) def heat_map_click_callback(a, b): if self.result_permutation is not None: episode = self.result_permutation[b["data"]["_cell_num"]] + 1 color = b["data"]["color"] self.episode_grid_heat_map_label.value = ( f"clicked on episode {episode} with {color}" "successful cases" ) self.episode_grid_heat_map.on_click(heat_map_click_callback) self.episode_grid_heat_map.on_element_click(heat_map_click_callback) super(HeatMap, self).__init__( [ self.episode_grid_heat_map_figure, self.episode_grid_heat_map_label, ] )
def process(self, inputs): """ Plot the ROC curve Arguments ------- inputs: list list of input dataframes. Returns ------- Figure """ model = inputs[self.INPUT_PORT_NAME] if isinstance(model, dict): model = model['booster'] x_ord = OrdinalScale() y_sc = LinearScale() data = model.get_score(importance_type=self.conf.get('type', 'gain')) x_values = [] y_values = [] for key in data.keys(): x_values.append(key) y_values.append(data[key]) bar = Bars(x=x_values, y=y_values, scales={'x': x_ord, 'y': y_sc}) ax_x = Axis(scale=x_ord) ax_y = Axis(scale=y_sc, tick_format='0.2f', orientation='vertical') newFig = Figure(marks=[bar], axes=[ax_x, ax_y], padding_x=0.025, padding_y=0.025) return {self.OUTPUT_PORT_NAME: newFig}
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 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[0] 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]}) 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 new_fig
def __init__(self, obj, function, x_label="x", y_label="y", title=None): """ Function takes an object, and returns (x,y) point. """ self.obj = obj self.x_label = x_label self.y_label = y_label self.function = function self.x_values = [] self.y_values = [] self.title = title x_sc = LinearScale() y_sc = LinearScale() line = Lines(x=[], y=[], scales={ "x": x_sc, "y": y_sc }, stroke_width=3, colors=["red"]) ax_x = Axis(scale=x_sc, label=x_label) ax_y = Axis(scale=y_sc, orientation="vertical", label=y_label) self.widget = Figure(marks=[line], axes=[ax_x, ax_y], title=self.title)
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 _build_heatmap(self, df): # create the matrix x_sc, y_sc, col_sc = OrdinalScale(), OrdinalScale( reverse=True), ColorScale(scheme='RdYlGr') # define a tooltip self.matrix_tooltip = ipywidgets.VBox(layout={ 'width': '180px', 'height': '100px' }) # building the marks for inflow and outflow grid_map = GridHeatMap(row=df.index, column=df.columns, color=df, scales={ 'column': x_sc, 'row': y_sc, 'color': col_sc }, tooltip=self.matrix_tooltip, interactions={'hover': 'tooltip'}, stroke='transparent', null_color='transparent', selected_style={'opacity': 1.0}, unselected_style={'opacity': 0.4}) ax_x, ax_y = Axis(scale=x_sc, grid_lines='none', label=df.columns.name, tick_rotate=-25, tick_style={'text-anchor': 'end'}), \ Axis(scale=y_sc, grid_lines='none', label=df.index.name, orientation='vertical') # generating the figures inflow and outflow grid_ui = Figure(marks=[grid_map], axes=[ax_x, ax_y], padding_y=0.0, title='{} distribution'.format( self.widgets['universe_select'].value), fig_margin={ 'bottom': 90, 'left': 150, 'right': 10, 'top': 60 }, layout={ 'width': '100%', 'height': '100%' }) # set the callback for the hovering effect grid_map.on_hover(self.on_matrix_hover) # define the output object to get displayed return ipywidgets.VBox([grid_ui], layout={ 'width': '99%', 'min_height': '100%', 'overflow_x': 'hidden' })
def make_guided_figure_fixed(injpeak, injnum=1): fsx = LinearScale() fsy = LinearScale() xax = Axis(label='seconds', scale=fsx) yax = Axis(label='uWatt', scale=fsy, orientation='vertical') fig=Figure(axes=[xax,yax],min_aspect_ratio=1.2,\ fig_margin={'top':60, 'bottom':60, 'left':60, 'right':0}) # # fig=Figure()#axes=[xax,yax],min_aspect_ratio=1.2,\ return fig
def __init__(self): self.pie_plot = Pie(radius=150, inner_radius=80, interactions={'click': 'select'}, colors=['green', 'red'], label_color='black', font_size='14px', ) self.pie_figure = Figure(title='Success rate', marks=[self.pie_plot]) super(PiePlot, self).__init__([self.pie_figure])
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 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_fig(self, ts): ts.sort_index(inplace=True) df = ts.reset_index() # time = ts.Time self.xd = df[self.xlabel] self.yd = df[self.cols].T # line_style # {‘solid’, ‘dashed’, ‘dotted’, ‘dash_dotted’} – Line style. line = Lines(x=self.xd, y=self.yd, scales={ 'x': self.xScale, 'y': self.yScale }, labels=self.legends, display_legend=True, line_style='solid', marker='circle', selected_style={'opacity': '1'}, unselected_style={ 'opacity': '0.2' }) # enable_hover=True) # axes_options=axes_options) x_axis = Axis(scale=self.xScale, label=self.xlabel, grid_lines='none') y_axis = Axis(scale=self.yScale, label=self.ylabel, orientation='vertical', grid_lines='none') margin = dict(top=0, bottom=30, left=50, right=50) self.fig = Figure(marks=[line], axes=[x_axis, y_axis], legend_location='top-right', fig_margin=margin) # {'top':50,'left':60}) self.deb = HTML() self.deb2 = HTML()
def __init__(self): self.pie_plot = Pie( radius=150, inner_radius=80, interactions={"click": "select"}, colors=["green", "red"], label_color="black", font_size="14px", ) self.pie_figure = Figure(title="Success rate", marks=[self.pie_plot]) super(PiePlot, self).__init__([self.pie_figure])
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 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 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 __init__(self, callback=None, widget=None): self.callback = callback self.widget = widget self.DimensionalityReduction = DimensionalityReduction() self.x_scale = LinearScale() self.y_scale = LinearScale() pan_zoom = bq.interacts.PanZoom( scales={"x": [self.x_scale], "y": [self.y_scale]} ) self.scatter = Scatter( scales={"x": self.x_scale, "y": self.y_scale}, default_opacities=[0.7], interactions={"click": "select"}, selected_style={"opacity": 1.0, "stroke": "Black"}, unselected_style={"opacity": 0.5}, ) def scatter_callback(a, b): self.episode = b["data"]["index"] + 1 # 1-indexed # we only have failures self.episode = self.failures_indices[self.episode - 1] if self.callback is not None: self.callback( self.experiment, self.version, self.step, self.episode ) if self.widget is not None: self.widget.update( self.experiment, self.version, self.step, self.episode ) self.scatter.on_element_click(scatter_callback) self.toggle_buttons = widgets.ToggleButtons( options=OrderedDict([("Select", None), ("Zoom", pan_zoom)]) ) self.scatter_figure = Figure( marks=[self.scatter], layout=widgets.Layout(height="600px", width="100%"), ) traitlets.link( (self.toggle_buttons, "value"), (self.scatter_figure, "interaction"), ) super(DimensionalityReductionPlot, self).__init__( [self.scatter_figure, self.toggle_buttons] )
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, color_scale, label='', margin=(50, 0), direction='horizontal', width=80, **kwargs): self._x_scale = LinearScale(allow_padding=False) self._y_scale = LinearScale(allow_padding=False, orientation='vertical') scales = {'x': self._x_scale, 'y': self._y_scale, 'image': color_scale} self._mark = ImageGL(image=np.zeros((1, )), scales=scales) self._direction = direction if direction == 'horizontal': # self._x_axis.num_ticks = 5 axis = Axis(scale=scales['x'], label=label) fig_margin = { 'top': 0, 'bottom': 50, 'left': margin[0], 'right': margin[1] } layout = widgets.Layout(height=f'{width}px', width='auto') else: axis = Axis(scale=scales['y'], label=label, orientation='vertical', side='right') fig_margin = { 'top': margin[1], 'bottom': margin[0], 'left': 0, 'right': 50 } layout = widgets.Layout(width=f'{width}px', height='auto') self._figure = Figure(scales=scales, layout=layout, axes=[axis], fig_margin=fig_margin) self._figure.marks = [self._mark] super().__init__(children=[self._figure])
def __init__(self, callback=None, widget=None): self.callback = callback self.widget = widget self.DimensionalityReduction = DimensionalityReduction() self.x_scale = LinearScale() self.y_scale = LinearScale() pan_zoom = bq.interacts.PanZoom(scales={ 'x': [self.x_scale], 'y': [self.y_scale] }) self.scatter = Scatter(scales={ 'x': self.x_scale, 'y': self.y_scale }, default_opacities=[0.7], interactions={'click': 'select'}, selected_style={ 'opacity': 1.0, 'stroke': 'Black' }, unselected_style={'opacity': 0.5}) def scatter_callback(a, b): self.episode = b['data']['index'] + 1 # 1-indexed # we only have failures self.episode = self.failures_indices[self.episode - 1] if self.callback is not None: self.callback(self.experiment, self.seed, self.step, self.episode) if self.widget is not None: self.widget.update(self.experiment, self.seed, self.step, self.episode) self.scatter.on_element_click(scatter_callback) self.toggle_buttons = widgets.ToggleButtons( options=OrderedDict([('Select', None), ('Zoom', pan_zoom)])) self.scatter_figure = Figure(marks=[self.scatter], layout=widgets.Layout(height='600px', width='100%')) traitlets.link((self.toggle_buttons, 'value'), (self.scatter_figure, 'interaction')) super(DimensionalityReductionPlot, self).__init__([self.scatter_figure, self.toggle_buttons])
def create_map_figure(self): ax_col = ColorAxis(scale=self.col_scale, label="ratio", tick_format="0.2f") return Figure( marks=[self.geomap], axes=[ax_col], title="Wealth of The Netherlands", layout={ "min_width": "400px", "width": "auto", "min_height": "400px", "width": "auto", }, )
def process(self, inputs): """ Plot the ROC curve 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_col = input_df[self.conf['label']].values pred_col = input_df[self.conf['prediction']].values if isinstance(input_df, cudf.DataFrame): fpr, tpr, _ = metrics.roc_curve(label_col.get(), pred_col.get()) else: fpr, tpr, _ = metrics.roc_curve(label_col, pred_col) auc_value = metrics.auc(fpr, tpr) out = {} if self.outport_connected(self.OUTPUT_PORT_NAME): linear_x = LinearScale() linear_y = LinearScale() yax = Axis(label='True Positive Rate', scale=linear_x, orientation='vertical') xax = Axis(label='False Positive Rate', scale=linear_y, orientation='horizontal') panzoom_main = PanZoom(scales={'x': [linear_x]}) curve_label = 'ROC (area = {:.2f})'.format(auc_value) line = Lines(x=fpr, y=tpr, scales={'x': linear_x, 'y': linear_y}, colors=['blue'], labels=[curve_label], display_legend=True) new_fig = Figure(marks=[line], axes=[yax, xax], title='ROC Curve', interaction=panzoom_main) out.update({self.OUTPUT_PORT_NAME: new_fig}) if self.outport_connected(self.OUTPUT_VALUE_NAME): out.update({self.OUTPUT_VALUE_NAME: float(auc_value)}) return out
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 create_lineplot_figure(self): ax_x = Axis(scale=self.sc_x, label="Year", tick_values=self.years) ax_y = Axis(scale=self.sc_y, orientation="vertical", label="Thousands (Euro)") return Figure( marks=[self.lineplot], axes=[ax_x, ax_y], title="Income per Year (Click a province to show)", layout={ "min_width": "400px", "width": "auto", "min_height": "400px", "height": "auto", }, )