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):
        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):
        # 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
예제 #4
0
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
예제 #5
0
    def update_scatter(self, elem):
        col = self.x_selecta.value
        if is_datetime(self.measures, col):
            x_sc = DateScale()
        else:
            x_sc = LinearScale()
        self.ax_x.scale = x_sc
        self.scat.x = self.measures[col]
        self.ax_x.label = col

        col = self.y_selecta.value
        if is_datetime(self.measures, col):
            y_sc = DateScale()
        else:
            y_sc = LinearScale()
        self.ax_y.scale = y_sc
        self.scat.y = self.measures[col]
        self.ax_y.label = col

        col = self.c_selecta.value
        if is_datetime(self.measures, col):
            c_sc = DateColorScale()
        else:
            c_sc = ColorScale()
        self.ax_c.scale = c_sc
        self.scat.color = self.measures[col]
        self.ax_c.label = col
        self.scat.scales = {
            "x": x_sc,
            "y": y_sc,
            "color": c_sc,
        }
예제 #6
0
파일: artists.py 프로젝트: jacobjma/abTEM
    def __init__(self, colors='red', gl=False, **kwargs):
        if isinstance(colors, str):
            colors = [colors]

        color_scale = ColorScale(scheme='plasma')

        scales = {
            'x': LinearScale(allow_padding=False),
            'y': LinearScale(allow_padding=False, orientation='vertical'),
            'color': color_scale,
            'size': LinearScale(min=0, max=1),
        }

        if gl:
            mark = ScatterGL(x=np.zeros((1, )),
                             y=np.zeros((1, )),
                             scales=scales,
                             colors=['red'])
        else:
            mark = Scatter(x=np.zeros((1, )),
                           y=np.zeros((1, )),
                           scales=scales,
                           colors=['red'])

        # link((self, 'color'), (mark, 'color'))

        super().__init__(mark=mark, **kwargs)

        link((self._mark, 'visible'), (self, 'visible'))
예제 #7
0
    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'
                               })
예제 #8
0
        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]
예제 #9
0
파일: bqp.py 프로젝트: saisunku/LiberTEM
    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
예제 #10
0
 def __init__(self, df, map_file, province_id_to_name) -> None:
     self.df = df
     self.yearly_df = self.df.pipe(self.reshape_with_period_cols)
     self.years = list(self.yearly_df.columns)
     self.sc_x = LinearScale()
     self.sc_y = LinearScale()
     self.col_scale = ColorScale(scheme="Greens")
     self.geomap = self.create_map(map_file)
     self.lineplot = self.create_lineplot()
     self.province_id_to_name = province_id_to_name.copy()
     self.year_slider = IntSlider(
         description="year",
         min=1995,
         max=2001,
         continuous_update=False,
         layout=Layout(width="100%"),
     )
예제 #11
0
파일: artists.py 프로젝트: jacobjma/abTEM
    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)
예제 #12
0
    def __init__(self, viewer, array_maker):

        # FIXME: need to use weakref to avoid circular references
        self.viewer = viewer

        self.scale_image = ColorScale()
        self.scales = {
            'x': self.viewer.scale_x,
            'y': self.viewer.scale_y,
            'image': self.scale_image
        }

        super().__init__(image=EMPTY_IMAGE, scales=self.scales)

        self.array_maker = array_maker

        self.viewer.figure.axes[0].scale.observe(self.debounced_update, 'min')
        self.viewer.figure.axes[0].scale.observe(self.debounced_update, 'max')
        self.viewer.figure.axes[1].scale.observe(self.debounced_update, 'min')
        self.viewer.figure.axes[1].scale.observe(self.debounced_update, 'max')

        self.update()
예제 #13
0
    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,)
예제 #14
0
    def process(self, inputs):
        """
        Plot the Scatter plot

        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
        num_points = self.conf['points']
        stride = max(len(input_df) // num_points, 1)

        sc_x = scaleMap[self.conf.get('col_x_scale', 'LinearScale')]()
        sc_y = scaleMap[self.conf.get('col_y_scale', 'LinearScale')]()

        x_col = self.conf['col_x']
        y_col = self.conf['col_y']
        ax_y = Axis(label=y_col,
                    scale=sc_y,
                    orientation='vertical',
                    side='left')

        ax_x = Axis(label=x_col,
                    scale=sc_x,
                    num_ticks=10,
                    label_location='end')
        m_chart = dict(top=50, bottom=70, left=50, right=100)
        if 'col_color' in self.conf:
            color_col = self.conf['col_color']
            sc_c1 = ColorScale()
            ax_c = ColorAxis(scale=sc_c1,
                             tick_format='0.2%',
                             label=color_col,
                             orientation='vertical',
                             side='right')
            if isinstance(input_df, (cudf.DataFrame, dask_cudf.DataFrame)):
                scatter = Scatter(
                    x=input_df[x_col][::stride].to_array(),
                    y=input_df[y_col][::stride].to_array(),
                    color=input_df[color_col][::stride].to_array(),
                    scales={
                        'x': sc_x,
                        'y': sc_y,
                        'color': sc_c1
                    },
                    stroke='black')
            else:
                scatter = Scatter(x=input_df[x_col][::stride],
                                  y=input_df[y_col][::stride],
                                  color=input_df[color_col][::stride],
                                  scales={
                                      'x': sc_x,
                                      'y': sc_y,
                                      'color': sc_c1
                                  },
                                  stroke='black')
            fig = Figure(axes=[ax_x, ax_c, ax_y],
                         marks=[scatter],
                         fig_margin=m_chart,
                         title=self.conf['title'])

        else:
            if isinstance(input_df, (cudf.DataFrame, dask_cudf.DataFrame)):
                scatter = Scatter(x=input_df[x_col][::stride].to_array(),
                                  y=input_df[y_col][::stride].to_array(),
                                  scales={
                                      'x': sc_x,
                                      'y': sc_y
                                  },
                                  stroke='black')
            else:
                scatter = Scatter(x=input_df[x_col][::stride],
                                  y=input_df[y_col][::stride],
                                  scales={
                                      'x': sc_x,
                                      'y': sc_y
                                  },
                                  stroke='black')
            fig = Figure(axes=[ax_x, ax_y],
                         marks=[scatter],
                         fig_margin=m_chart,
                         title=self.conf['title'])
        return {self.OUTPUT_PORT_NAME: fig}
예제 #15
0
파일: cyplot.py 프로젝트: orpheus92/CyQuery
    def create_fig(self, ts):

        if self.ptype != 'PCA' and self.dims == None:
            ts.sort_index(inplace=True)
            df = ts.reset_index()  # time = ts.Time

        else:
            df = ts
        self.xd = df[self.xlabel]
        self.yd = df[self.cols].T

        if self.ptype == 'PCA' or self.dims is not None:
            pplt = Scatter(x=self.xd.values.ravel(), y=self.yd.values.ravel(), scales={'x': self.xScale, \
            'y': self.yScale, 'color': ColorScale(scheme=self.scheme)}, selected_style={'opacity': '1'}, \
            unselected_style={'opacity': '0.2'},color = self.colors, default_size=32)

        elif not self.ptype:
            pplt = Lines(x=self.xd, y=self.yd, scales={'x': self.xScale, 'y': self.yScale}, labels=self.legends,
                         display_legend=True, line_style=self.linestyle, stroke_width = 1, marker = 'circle', \
                         interpolation = self.interp)
            # {‘linear’, ‘basis’, ‘cardinal’, ‘monotone’}
        else:
            pplt = Lines(x=self.xd, y=self.yd, scales={'x': self.xScale, 'y': self.yScale}, labels=self.legends, \
                         display_legend=True, line_style=self.linestyle, selected_style={'opacity': '1'}, \
                         unselected_style={'opacity': '0.2'},interpolation=self.interp)
            # 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')
        c_axis = ColorAxis(scale=ColorScale(scheme=self.scheme),
                           orientation='vertical',
                           side='right')

        axis = [x_axis, y_axis, c_axis] if isinstance(
            pplt, Scatter) else [x_axis, y_axis]

        if self.debug:
            margin = dict(top=0, bottom=40, left=50, right=50)
        else:
            margin = dict(top=0, bottom=50, left=50, right=50)

        self.fig = Figure(marks=[pplt],
                          axes=axis,
                          legend_location='top-right',
                          fig_margin=margin)  # {'top':50,'left':60})

        if self.debug:
            self.deb = HTML()

        y = getattr(self, "vbox", None)
        if y is not None:
            box_layout = Layout(display='flex',
                                flex_flow='column',
                                align_items='stretch')
            if self.debug:
                self.vbox = VBox(
                    [self.selection_interacts, self.fig, self.deb],
                    layout=box_layout)
            else:
                self.vbox = VBox([self.selection_interacts, self.fig],
                                 layout=box_layout)
예제 #16
0
    def _init_grid(self):

        # Set up scales for the spatial x, spatial y, spectral, and flux
        self.scale_x = bqplot.LinearScale(min=0, max=1)
        self.scale_y = bqplot.LinearScale(min=0, max=1)
        self.scale_spec = bqplot.LinearScale(min=0, max=1)
        self.scale_flux = bqplot.LinearScale(min=0, max=1)

        # Set up colorscale
        self.scale_cutout_image = ColorScale(colors=['black', 'white'])
        self.scale_spec2d_image = ColorScale(colors=['black', 'white'])

        # Set up axes
        self.axis_x = bqplot.Axis(scale=self.scale_x,
                                  grid_lines='solid',
                                  label='x')
        self.axis_y = bqplot.Axis(scale=self.scale_y,
                                  grid_lines='solid',
                                  label='y',
                                  orientation='vertical')

        self.axis_spec = bqplot.Axis(scale=self.scale_spec,
                                     grid_lines='solid',
                                     label='spec')
        self.axis_flux = bqplot.Axis(scale=self.scale_flux,
                                     grid_lines='solid',
                                     label='flux',
                                     orientation='vertical')

        # Set up bqplot viewers
        # =====================

        # Cutout
        # ------
        self.fig_cutout = bqplot.Figure(scales={
            'x': self.scale_x,
            'y': self.scale_y
        },
                                        axes=[self.axis_x, self.axis_y],
                                        layout={
                                            'width': '500px',
                                            'height': '400px'
                                        })
        self.fig_cutout.interaction = PanZoom(scales={
            'x': [self.scale_x],
            'y': [self.scale_y]
        })

        # Spec 2d
        # -------
        self.fig_spec2d = bqplot.Figure(scales={
            'x': self.scale_spec,
            'y': self.scale_y
        },
                                        axes=[self.axis_spec, self.axis_y],
                                        layout={
                                            'width': '500px',
                                            'height': '400px'
                                        })

        self.fig_spec2d.interaction = PanZoom(scales={
            'x': [self.scale_spec],
            'y': [self.scale_y]
        })

        # Spec 1d
        # -------
        self.fig_spec1d = bqplot.Figure(scales={
            'x': self.scale_spec,
            'y': self.scale_flux
        },
                                        axes=[self.axis_spec, self.axis_flux],
                                        layout={
                                            'width': '500px',
                                            'height': '400px'
                                        })

        self.fig_spec1d.interaction = PanZoom(scales={
            'x': [self.scale_spec],
            'y': [self.scale_flux]
        })

        # info box
        # --------
        self.info_box = Textarea(value='Hello World')
        self.info_box.layout.height = '100%'
        self.info_box.layout.width = '100%'
        self.info_box.layout.align_self = 'flex-end'

        # Set up content of figures
        # =========================

        self.cutout_mark = AstroImage(scales={
            'x': self.scale_x,
            'y': self.scale_y,
            'image': self.scale_cutout_image
        })
        self.fig_cutout.marks = [self.cutout_mark]

        self.spec2d_mark = AstroImage(
            scales={
                'x': self.scale_spec,
                'y': self.scale_y,
                'image': self.scale_spec2d_image
            })
        self.fig_spec2d.marks = [self.spec2d_mark]

        self.spec1d_mark = bqplot.Lines(scales={
            'x': self.scale_spec,
            'y': self.scale_flux
        },
                                        x=[],
                                        y=[])
        self.fig_spec1d.marks = [self.spec1d_mark]

        GridBox.__init__(self, [
            self.fig_cutout,
            HTML(), self.fig_spec2d,
            HTML(),
            HTML(),
            HTML(), self.info_box,
            HTML(), self.fig_spec1d
        ],
                         layout=Layout(width='100%',
                                       grid_template_columns='35% 5% 35%',
                                       grid_template_rows='30% 5% 30%',
                                       grid_gap='30px 30px'))

        self.layout.justify_content = "center"
        self.layout.align_items = "center"
예제 #17
0
파일: vgan.py 프로젝트: cyhsu/vgan
def sidebarCalendarHeatmap(PI):
    dataframe = pd.read_json('./Data/PIcontribution/{}.json'.format(PI))
    figs, years = [], np.unique(dataframe.index.year)

    #-- Calendar Heatmap by bqplot.
    for year in years[:
                      -1]:  #-- years[:-1] is because the end year + 1 is the upper bound.
        data = dataframe[str(year)]
        data = pd.DataFrame({
            'data': data.trajectory,
            'fill': 1,
            'day': data.index.dayofweek,
            'week': data.index.isocalendar().week
        })
        data.loc[(data.index.month == 1) & (data.week > 50), 'week'] = 0
        data.loc[(data.index.month == 12) & (data.week < 10),
                 'week'] = data.week.max() + 1

        fill_data = data.pivot('day', 'week', 'fill').values[::-1]
        fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data)

        plot_data = data.pivot('day', 'week', 'data').values  #[::-1]
        plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data)

        monthlabels = np.arange(data.index[0],
                                data.index[-1] + np.timedelta64(1, 'D'),
                                dtype='datetime64[D]')[::7]
        daylabels = list(['Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat', 'Sun'])

        Layout = widgets.Layout(width='auto', height='200px')
        #Layout = widgets.Layout(width='100%',height='200px')
        fig = bplt.figure(
            layout=Layout,
            fig_margin=dict(top=20, bottom=20, left=60, right=40),
            padding_y=0,
        )

        xmin, xmax = np.datetime64('{:04d}-01-01'.format(year)), np.datetime64(
            '{:04d}-12-31'.format(year))
        bplt.scales(
            scales={
                'x': DateScale(
                    min=xmin,
                    max=xmax,
                    offset={'value': 1},
                ),
                'y': OrdinalScale(reverse=True)
            })
        bplt.gridheatmap(fill_data,
                         row=daylabels,
                         column=monthlabels,
                         stroke='white',
                         opacity=0.3,
                         scales={'color': ColorScale(scheme='Grays')},
                         axes_options={'color': {
                             'visible': False
                         }})

        grid_map = bplt.gridheatmap(
            plot_data,
            row=daylabels,
            column=monthlabels,
            opacity=0.7,
            stroke='white',
            scales={'color': ColorScale(colors=['whitesmoke', 'darkgreen'])},
            axes_options={
                'row': {
                    'label_offset': '3em',
                    'label': str(year),
                    'num_ticks': 4,
                    'grid_lines': 'none'
                },
                'column': {
                    'num_ticks': 5,
                    'grid_lines': 'none'
                },
                'color': {
                    'visible': False
                }
            })
        figs.append(fig)
    return widgets.VBox(figs,
                        layout=widgets.Layout(
                            align_items='center',
                            justify_content='center',
                            margin='2%',
                        ))
예제 #18
0
    def __init__(
        self,
        measures,
        x=None,
        y=None,
        c=None,
        mouseover=False,
        host="localhost",
        port=4090,
    ):
        """Interactive scatter plot visualisation - this is a base class,
        use either `ROIScatterViz` for one image with multiple ROIs
        or `ImageScatterViz` for a scatterplot with multiple images
        """
        self.port = port
        self.measures = measures
        self.columns = list(measures.columns)
        x_col = x if x else self.columns[0]
        y_col = y if y else self.columns[1]
        c_col = c if c else self.columns[2]

        selector_layout = widgets.Layout(height="40px", width="100px")
        self.x_selecta = widgets.Dropdown(
            options=self.columns,
            value=x_col,
            description="",
            disabled=False,
            layout=selector_layout,
        )
        self.y_selecta = widgets.Dropdown(
            options=self.columns,
            value=y_col,
            description="",
            disabled=False,
            layout=selector_layout,
        )

        self.c_selecta = widgets.Dropdown(
            options=self.columns,
            value=c_col,
            description="",
            disabled=False,
            layout=selector_layout,
        )

        self.sheet = widgets.Output()
        self.thumbs = {}
        self.goto = widgets.HTML("")
        if is_datetime(self.measures, x_col):
            x_sc = DateScale()
        else:
            x_sc = LinearScale()

        if is_datetime(self.measures, y_col):
            y_sc = DateScale()
        else:
            y_sc = LinearScale()

        if is_datetime(self.measures, c_col):
            c_sc = DateColorScale(scheme="viridis")
        else:
            c_sc = ColorScale()

        self.scat = Scatter(
            x=self.measures[self.x_selecta.value],
            y=self.measures[self.y_selecta.value],
            color=self.measures[self.c_selecta.value],
            scales={
                "x": x_sc,
                "y": y_sc,
                "color": c_sc,
            },
            names=self.measures.index,
            display_names=False,
            fill=True,
            default_opacities=[
                0.8,
            ],
        )
        self.ax_x = Axis(scale=x_sc, label=self.x_selecta.value)
        self.ax_y = Axis(scale=y_sc,
                         label=self.y_selecta.value,
                         orientation="vertical")
        self.ax_c = ColorAxis(
            scale=c_sc,
            label=self.c_selecta.value,
            orientation="vertical",
            offset={
                "scale": y_sc,
                "value": 100
            },
        )
        self.fig = Figure(
            marks=[
                self.scat,
            ],
            axes=[self.ax_x, self.ax_y, self.ax_c],
        )
        self.scat.on_element_click(self.goto_db)
        self.scat.on_element_click(self.show_data)
        if mouseover:
            self.scat.on_hover(self.show_thumb)
            self.scat.tooltip = widgets.HTML("")
        self.x_selecta.observe(self.update_scatter)
        self.y_selecta.observe(self.update_scatter)
        self.c_selecta.observe(self.update_scatter)
        self.connector = OMEConnect(host=host, port=4064)
        self.connector.gobtn.on_click(self.setup_graph)
        super().__init__([self.connector])
예제 #19
0
map_mark = Map(map_data=topo_load('map_data/WorldMap.json'),
               scales={'projection': sc_geo},
               colors={
                   682: 'Green',
                   356: 'Red',
                   643: '#0000ff',
                   'default_color': 'DarkOrange'
               })
fig = plt.figure(marks=[map_mark],
                 fig_color='deepskyblue',
                 title='Advanced Map Example')
if kommune.check_isnotebook():
    display(fig)
"""# Example 3"""
sc_geo = Mercator()
sc_c1 = ColorScale(scheme='YlOrRd')

map_styles = {
    'color': {
        643: 105.,
        4: 21.,
        398: 23.,
        156: 42.,
        124: 78.,
        76: 98.
    },
    'scales': {
        'projection': sc_geo,
        'color': sc_c1
    },
    'colors': {