예제 #1
0
def live_plot(plot_string, topic_type, history=100, title=None):
    topic = plot_string[:plot_string.find(':') - 1]
    title = title if title else topic
    fields = plot_string.split(':')[1:]
    x_sc = bq.LinearScale()
    y_sc = bq.LinearScale()

    ax_x = bq.Axis(label='X', scale=x_sc, grid_lines='solid')
    ax_y = bq.Axis(label='Y', scale=y_sc, orientation='vertical', grid_lines='solid')

    lines = bq.Lines(x=np.array([]), y=np.array([]), scales={'x': x_sc, 'y': y_sc})
    fig = bq.Figure(axes=[ax_x, ax_y], marks=[lines], labels=fields, display_legend=True, title=title)
    data = []

    def cb(msg, data=data):
        data_el = []
        for f in fields:
            data_el.append(getattr(msg, f))
        data.append(data_el)
        data = data[-history:]
        ndat = np.asarray(data).T
        if lines:
            lines.y = ndat
            lines.x = np.arange(len(data))

    rospy.Subscriber(topic, topic_type, cb)
    return fig
예제 #2
0
    def init_bq_fig(self):
        self.bq_xscale = bq.LinearScale()
        self.bq_yscale = bq.LinearScale()
        self.bq_colorscale = bq.ColorScale(min=-1, max=1)
        self.bq_xax = bq.Axis(scale=self.bq_xscale)
        self.bq_yax = bq.Axis(scale=self.bq_yscale, orientation='vertical')
        self.bq_colorax = bq.ColorAxis(scale=self.bq_colorscale)
        self.bq_heat = bq.HeatMap(
            x=self.x,
            y=self.z,
            color=zeros_like(self.cY),
            scales={
                'x': self.bq_xscale,
                'y': self.bq_yscale,
                'color': self.bq_colorscale
            }

        )
        self.bq_fig = bq.Figure(
            marks=[self.bq_heat],
            axes=[
                self.bq_xax,
                self.bq_yax,
                self.bq_colorax
            ]
        )
def plot_timeseries(server, e, dataset_id):
    """This defines the initial bqplot time series plot"""
    dt_x = bq.DateScale()
    sc_y = bq.LinearScale()

    constraints = {
        "time>=": server.get("min_time"),
        "time<=": server.get("max_time")
    }

    df, var = get_timeseries(
        e=e,
        dataset=dataset_id,
        standard_name=server.get("standard_name"),
        constraints=constraints,
    )
    def_tt = bq.Tooltip(fields=["y"], formats=[".2f"], labels=["value"])
    time_series = bq.Lines(
        x=df.index,
        y=df[var],
        scales={
            "x": dt_x,
            "y": sc_y
        },
        tooltip=def_tt,
    )
    ax_x = bq.Axis(scale=dt_x, label="Time")
    ax_y = bq.Axis(scale=sc_y, orientation="vertical")
    figure = bq.Figure(marks=[time_series], axes=[ax_x, ax_y])
    figure.title = f"{dataset_id[:18]} - {var}"
    figure.layout.height = "300px"
    figure.layout.width = "800px"
    return figure
예제 #4
0
파일: bqplot.py 프로젝트: tboch/vaex
        def create(self, data):
            size = data.shape[0]
            assert len(data.shape) == 1
            xmin, xmax = self.limits[0]
            dx = (xmax - xmin) / size
            x = np.linspace(xmin, xmax - dx, size) + dx / 2
            # print xmin, xmax, x

            self.scale_x = bq.LinearScale(min=xmin + dx / 2, max=xmax - dx / 2)
            self.scale_y = bq.LinearScale()

            self.axis_x = bq.Axis(label='X', scale=self.scale_x)
            self.axis_y = bq.Axis(label='Y',
                                  scale=self.scale_y,
                                  orientation='vertical')
            self.bars = bq.Bars(x=x,
                                y=data,
                                scales={
                                    'x': self.scale_x,
                                    'y': self.scale_y
                                },
                                colors=[self.color])

            self.fig = bq.Figure(axes=[self.axis_x, self.axis_y],
                                 marks=[self.bars],
                                 padding_x=0)
예제 #5
0
파일: IVtws.py 프로젝트: world2005/IVtws
    def bqstreamplot(self):
        Cxs = bq.DateScale()
        Cys = bq.LinearScale()
        Cx = self.CallIVtable.index.values
        Cy = self.CallIVtable.as_matrix().transpose()
        Ccol = self.CallIVtable.columns.tolist()

        self.Cline = bq.Lines(x=Cx, y=Cy, scales={'x': Cxs, 'y': Cys},
                        colors=[i.hex for i in list(Color(rgb=(0.95,0,0)).range_to(Color(rgb=(0.45,0.1,0)), len(Ccol)))],
                        labels=Ccol,
                        enable_hover=True,
                        display_legend=True)
        Cxax = bq.Axis(scale=Cxs, label='Datetime', grid_lines='solid')
        Cyax = bq.Axis(scale=Cys, orientation='vertical', tick_format='0.1f', label='CallIV', grid_lines='solid')
        figC = bq.Figure(marks=[self.Cline], axes=[Cxax, Cyax], animation_duration=1000)

        Pxs = bq.DateScale()
        Pys = bq.LinearScale()
        Px = self.PutIVtable.index.values
        Py = self.PutIVtable.as_matrix().transpose()
        Pcol = self.PutIVtable.columns.tolist()

        self.Pline = bq.Lines(x=Px, y=Py, scales={'x': Pxs, 'y': Pys},
                        colors=[i.hex for i in list(Color(rgb=(0,0.75,0)).range_to(Color(rgb=(0,0,0.45)), len(Pcol)))],
                        labels=Pcol,
                        enable_hover=True,
                        display_legend=True)
        Pxax = bq.Axis(scale=Pxs, label='Datetime', grid_lines='solid')
        Pyax = bq.Axis(scale=Pys, orientation='vertical', tick_format='0.1f', label='PutIV', grid_lines='solid')
        figP = bq.Figure(marks=[self.Pline], axes=[Pxax, Pyax], animation_duration=1000)
        display(HBox(([figC,figP])))
예제 #6
0
    def init_elements(self):
        self.xscale = bq.LinearScale(
            min=np.min(self.xvals),
            max=np.max(self.xvals)
        )
        self.yscale = bq.LinearScale(
            min=self.ylim[0],
            max=self.ylim[1]
        )
        self.xax = bq.Axis(
            scale=self.xscale,
            label=self.labels['xlabel'],
            grid_lines='none'
        )
        self.yax = bq.Axis(
            scale=self.yscale,
            label=self.labels['ylabel'],
            orientation='vertical',
            grid_lines='none'
        )
        self.line = bq.Lines(
            x=self.xvals,
            y=self.yvals,
            scales={'x': self.xscale, 'y': self.yscale},
            colors=[self.color],
            interpolation='cardinal'
        )
        self.handdraw = bqi.HandDraw(lines=self.line)

        super().__init__(
            marks=[self.line],
            axes=[self.xax, self.yax],
            interaction=self.handdraw
        )
예제 #7
0
    def init_plot(self):
        self.xscale = bq.LinearScale()
        self.yscale = bq.LinearScale()
        self.zscale = bq.ColorScale(scheme='Reds')
        self.heat = bq.HeatMap(
            x=self.x,
            y=self.y,
            color=self.z,
            scales=dict(
                x=self.xscale,
                y=self.yscale,
                color=self.zscale
            )
        )
        self.xax = bq.Axis(
            scale=self.xscale,
            label=self.labels['x']
        )
        self.yax = bq.Axis(
            scale=self.yscale,
            label=self.labels['y'],
            orientation='vertical'
        )
        self.zax = bq.Axis(scale=self.zscale)

        super().__init__(
            marks=[self.heat],
            axes=[self.xax, self.yax, self.zax],
        )
예제 #8
0
def draw_graph(graph, pos=None):
    from numpy import array
    import networkx as nx
    import bqplot as bq

    if pos is None:
        pos = nx.spring_layout(graph)
    nodes = graph.nodes()
    x = [pos[n][0] for n in nodes]
    y = [pos[n][1] for n in nodes]
    lines_x = []
    lines_y = []
    for k, v in graph.edges():
        i1 = graph.nodes().index(k)
        i2 = graph.nodes().index(v)
        lines_x.append([x[i1], x[i2]])
        lines_y.append([y[i1], y[i2]])
    lines_x = array(lines_x)
    lines_y = array(lines_y)

    x_sc = bq.LinearScale()
    y_sc = bq.LinearScale()
    points = bq.Scatter(x=x, y=y, scales={'x': x_sc, 'y': y_sc})
    lines = bq.Lines(x=lines_x,
                     y=lines_y,
                     scales={
                         'x': x_sc,
                         'y': y_sc
                     },
                     colors=['red'])
    ax_x = bq.Axis(scale=x_sc)
    ax_y = bq.Axis(scale=y_sc, orientation='vertical')
    fig = bq.Figure(marks=[lines, points], axes=[ax_x, ax_y])
    return fig
예제 #9
0
    def lightcurve_widget(self):
        '''Create light curve widget'''
        xax = bq.Axis(label='Time (MJD)',
                      scale=self.sc_x,
                      grid_lines='solid',
                      label_location="middle")
        xax.tick_style = {'stroke': 'black', 'font-size': 12}

        yax = bq.Axis(label='Magnitude',
                      scale=self.sc_y,
                      orientation='vertical',
                      tick_format='0.1f',
                      grid_lines='solid',
                      label_location="middle")
        yax.tick_style = {'stroke': 'black', 'font-size': 12}

        panzoom = bq.PanZoom(scales={'x': [self.sc_x], 'y': [self.sc_y]})
        return bq.Figure(
            axes=[xax, yax],
            marks=[],
            layout=Layout(width='100%', height='auto'),
            fig_margin={
                'top': 0,
                'bottom': 40,
                'left': 50,
                'right': 0
            },
            legend_location='top-right',
        )
예제 #10
0
    def __init__(self, model=None, *args, **kwargs):

        super(GeneratorCostView, self).__init__(*args, **kwargs)

        if model is not None:
            self.model = model
        else:
            self.model = Generator()

        self._scale_x = bq.LinearScale(min=self.model.minimum_real_power,
                                       max=self.model.maximum_real_power)

        self._scale_y = bq.LinearScale(
            min=0, max=(max(self.model.cost_curve_values) * 1.5 + 50))

        self._scales = {
            'x': self._scale_x,
            'y': self._scale_y,
        }

        self._scatter = bq.Scatter(x=self.model.cost_curve_points,
                                   y=self.model.cost_curve_values,
                                   scales=self._scales)

        self._lines = bq.Lines(x=self.model.cost_curve_points,
                               y=self.model.cost_curve_values,
                               scales=self._scales)

        self._axes_x = bq.Axis(scale=self._scale_x)
        self._axes_y = bq.Axis(scale=self._scale_y,
                               orientation='vertical',
                               padding_x=0.025)

        f = bq.Figure(marks=[
            self._lines,
            self._scatter,
        ],
                      axes=[
                          self._axes_x,
                          self._axes_y,
                      ])

        children = [f]

        self.children = children

        t.link((self.model, 'maximum_real_power'), (self._scale_x, 'max'))
        t.link((self.model, 'cost_curve_points'), (self._scatter, 'x'))
        t.link((self.model, 'cost_curve_values'), (self._scatter, 'y'))

        t.link((self._lines, 'x'), (self._scatter, 'x'))
        t.link((self._lines, 'y'), (self._scatter, 'y'))

        # self._scatter.observe(self._callback_ydata, names=['y'])

        with self._scatter.hold_sync():
            self._scatter.enable_move = True
            self._scatter.update_on_move = True
            self._scatter.interactions = {'click': None}
예제 #11
0
파일: julia.py 프로젝트: fjcasanova/repo
def representation_complexe():
    real = widgets.BoundedFloatText(value=1,
                                    min=-2.0,
                                    max=2.0,
                                    step=0.1,
                                    disabled=True)

    imag = widgets.BoundedFloatText(value=1,
                                    min=-2.0,
                                    max=2.0,
                                    step=0.1,
                                    disabled=True)

    sc_x = bqplot.LinearScale(min=-2, max=2)
    sc_y = bqplot.LinearScale(min=-2, max=2)
    ax_x = bqplot.Axis(scale=sc_x, offset=dict(value=0.5), grid_lines='none')
    ax_y = bqplot.Axis(scale=sc_y,
                       orientation='vertical',
                       offset=dict(value=0.5),
                       grid_lines='none')

    z_point = bqplot.Scatter(x=[real.value],
                             y=[imag.value],
                             scales={
                                 'x': sc_x,
                                 'y': sc_y
                             },
                             colors=['green'],
                             enable_move=True)
    z_point.update_on_move = True

    fig = bqplot.Figure(marks=[z_point],
                        axes=[ax_x, ax_y],
                        min_aspect_ratio=1,
                        max_aspect_ratio=1)

    complex_z = widgets.HBox([
        widgets.Label('$z = $'), real,
        widgets.Label('$ + $'), imag,
        widgets.Label('$i$')
    ])

    def update_z(change=None):
        real.value = z_point.x[0]
        imag.value = z_point.y[0]

    z_point.observe(update_z, names=['x', 'y'])

    #def update_point(change=None):
    #    z_point.x = [real.value]
    #    z_point.y = [imag.value]

    #real.observe(update_point, names='value')
    #imag.observe(update_point, names='value')

    return widgets.VBox([fig, complex_z],
                        layout=widgets.Layout(align_items="center"))
예제 #12
0
    def get_input_form(self, figure_title, no_users=100):
        if self.fig:
            return self.fig

        self.figure_title = figure_title
        max_hours = 24 + 1
        max_users = no_users

        # Define scales
        x_scale = bqplot.LinearScale(min=0, max=max_hours)
        y_scale = bqplot.LinearScale(min=0, max=max_users)

        # Initialize data for our line
        line = bqplot.Lines(
            x=np.arange(0, max_hours),
            y=np.zeros(max_hours),
            scales={"x": x_scale, "y": y_scale},
            fill="bottom",
            fill_opacities=[0.5],
        )

        # Layout only - axes (plural of axis)
        x_axis = bqplot.Axis(scale=x_scale, label="Hour", grid_lines="none")
        y_axis = bqplot.Axis(
            scale=y_scale,
            label="Number of Users",
            grid_lines="none",
            orientation="vertical",
        )

        def _fix_input_callback(change):
            # ensures we draw integer values 0 or greater and that
            # 00:00 [0] and 24:00 [24] represent the same value.
            with line.hold_sync():

                if change["old"][-1] != change["new"][-1]:
                    line.y[0] = line.y[-1]
                elif change["old"][0] != change["new"][0]:
                    line.y[-1] = line.y[0]

                line.y = np.fmax(0, np.rint(line.y))

        line.observe(_fix_input_callback, names=["y"])

        handdraw_interaction = bqplot.interacts.HandDraw(lines=line)
        self.fig = bqplot.Figure(
            marks=[line],
            axes=[x_axis, y_axis],
            interaction=handdraw_interaction,
            animation_duration=150,
            title=self.figure_title,
        )

        return self.fig
예제 #13
0
파일: amoba.py 프로젝트: B-Lorentz/amoba
    def __init__(self):
        '''Initialization of a Gomoku game with an empty board and a random starting party'''
        self.A = np.zeros(
            (15, 15),
            dtype=int)  # this holds the information of the current game status
        # 0 means empty place
        # 1 is red
        # 2 is blue

        # the visualization of the table is generated by bqplot
        sc_x = bq.LinearScale(max=15.5, min=-1.5)
        sc_y = bq.LinearScale(max=15.5, min=-1.5)
        scatt1 = bq.Scatter(x=[],
                            y=[],
                            scales={
                                'x': sc_x,
                                'y': sc_y
                            },
                            colors=['red'],
                            default_size=500)
        scatt2 = bq.Scatter(x=[],
                            y=[],
                            scales={
                                'x': sc_x,
                                'y': sc_y
                            },
                            colors=['blue'],
                            default_size=500)
        winline = bq.Lines(x=[],
                           y=[],
                           scales={
                               'x': sc_x,
                               'y': sc_y
                           },
                           colors=['lightgreen'],
                           stroke_width=5)
        props = dict(tick_values=np.arange(16) - 0.5,
                     grid_color='black',
                     tick_style={'font-size': 0})
        ax_x = bq.Axis(scale=sc_x, **props)
        ax_y = bq.Axis(scale=sc_y, orientation='vertical', **props)
        fig = bq.Figure(marks=[scatt1, scatt2, winline], axes=[ax_x, ax_y])
        fig.max_aspect_ratio = 1.0
        fig.min_aspect_ratio = 1.0
        fig.layout.height = '600px'
        self.fig = fig

        # the starting player is randomly selected
        self.who_is_next = np.random.randint(1, 3)
        self.fig.title = 'Next player is ' + ['red ', 'blue '
                                              ][self.who_is_next - 1]
        # initially noone is winning
        self.win_string = False
예제 #14
0
def plot_orbit(z0=0.5+0.5*1j, c=0+0*1j):
    sc_x = bqplot.LinearScale(min=-1.2, max=1.2)
    sc_y = bqplot.LinearScale(min=-1.2, max=1.2)

    c_point = bqplot.Scatter(x=[c.real], y=[c.imag], scales={'x': sc_x, 'y': sc_y}, colors=['red'],
                   enable_move=True, default_size=200)
    c_point.update_on_move = True

    z_point = bqplot.Scatter(x=[z0.real], y=[z0.imag], scales={'x': sc_x, 'y': sc_y}, colors=['green'],
                   enable_move=True, default_size=200)
    z_point.update_on_move = True

    c_label = bqplot.Label(x=[c.real+.05], y=[c.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['red'],
                           text=['c'],
                           default_size=26, font_weight='bolder')

    z_label = bqplot.Label(x=[z0.real+.05], y=[z0.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['green'],
                           text=['z0'],
                           default_size=26, font_weight='bolder')
    
    scatt = bqplot.Scatter(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], default_size=20)

    theta = np.linspace(0, 2.*np.pi, 1000)
    x = np.cos(theta)
    y = np.sin(theta)
    circle = bqplot.Lines(x=x, y=y, scales={'x': sc_x, 'y': sc_y}, colors=['black'])
    lin = bqplot.Lines(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], stroke_width=1)

    def update_line(change=None):
        out = orbit(z_point.x + 1j*z_point.y, c_point.x + 1j*c_point.y)
        c_label.x = c_point.x + 0.05
        c_label.y = c_point.y + 0.05
        z_label.x = z_point.x + 0.05
        z_label.y = z_point.y + 0.05
        lin.x = out.real
        lin.y = out.imag
        scatt.x = out.real.flatten()
        scatt.y = out.imag.flatten()

    update_line()
    # update line on change of x or y of scatter
    c_point.observe(update_line, names=['x'])
    c_point.observe(update_line, names=['y'])
    z_point.observe(update_line, names=['x'])
    z_point.observe(update_line, names=['y'])
    ax_x = bqplot.Axis(scale=sc_x, offset=dict(value=0.5), grid_lines='none')
    ax_y = bqplot.Axis(scale=sc_y, orientation='vertical', offset=dict(value=0.5), grid_lines='none')

    fig = bqplot.Figure(marks=[scatt, lin, circle, c_point, z_point, c_label, z_label], axes=[ax_x, ax_y],
                 min_aspect_ratio=1, max_aspect_ratio=1)
    fig.layout.height = '800px'
    return fig
예제 #15
0
파일: bqpick.py 프로젝트: Japhiolite/bqcs
def add_del(scale, img):
    """Add function for ipywidget buttons to add and delete points"""

    scat = bq.Scatter(x=[],
                      y=[],
                      scales=scale,
                      colors=['orange'],
                      enable_move=True)

    image = bq.Image(x=np.array([scale['x'].min, scale['x'].max]),
                     y=np.array([scale['y'].min, scale['y'].max]),
                     image=img,
                     scales=scale,
                     enable_hover=False)

    interact_control = widgets.ToggleButtons(options=['Add', 'Delete'],
                                             style={'button_width': '130px'})

    def change_interact(shape):
        """Give a meaning to the buttons."""
        interact_params = {
            'Add': {
                'interactions': {
                    'click': 'add'
                },
                'enable_move': True
            },
            'Delete': {
                'interactions': {
                    'click': 'delete'
                },
                'enable_move': False
            }
        }

        for param, value in interact_params[interact_control.value].items():
            setattr(scat, param, value)

    interact_control.observe(change_interact)

    fig = bq.Figure(title='Cross-section',
                    marks=[image, scat],
                    padding_x=0,
                    padding_y=0)
    fig.axes = [
        bq.Axis(scale=scale['x']),
        bq.Axis(scale=scale['y'], orientation='vertical')
    ]

    return widgets.VBox([fig, interact_control])
예제 #16
0
    def create_fig(self):
        t1_values = self.get_values(self.t1)
        t2_values = self.get_values(self.t2)
        self.df = t1_values.merge(t2_values, how='inner', on='patient.id')

        sc_x = plt.LinearScale()
        sc_y = plt.LinearScale()

        self.mark = plt.Scatter(scales={'x': sc_x, 'y': sc_y}, default_size=16)

        ax_x = plt.Axis(scale=sc_x, label=self.t1.title)
        ax_y = plt.Axis(scale=sc_y,
                        label=self.t2.title,
                        orientation='vertical')
        self.fig = plt.Figure(marks=[self.mark], axes=[ax_x, ax_y])
    def make_pixel_intensities_pane(self):
        FULL_HEIGHT = 800

        scales = {
            'x': bq.LinearScale(min=0),
            'y': bq.LinearScale(min=0, max=255)
        }

        self.pixel_intensities_mark = bq.Lines(scales=scales,
                                               colors=['blue', 'green', 'red'],
                                               display_legend=True,
                                               opacities=[0.7] * 3)

        axes = [bq.Axis(scale=scales['y'], orientation='vertical')]

        self.pixel_intensities_fig = bq.Figure(
            marks=[self.pixel_intensities_mark], axes=axes)
        self.pixel_intensities_fig.layout.width = '100%'
        self.pixel_intensities_fig.layout.height = str(
            self.display_pane.size * FULL_HEIGHT) + 'px'
        self.pixel_intensities_fig.layout.margin = '0'
        self.pixel_intensities_fig.title = 'Pixel Intensities Along Segment'

        self.update_pixel_intensities_mark()

        return ipy.VBox([
            self.pixel_intensities_fig,
            bq.toolbar.Toolbar(figure=self.pixel_intensities_fig)
        ])
예제 #18
0
def create_plot():
    index = pd.date_range(start='2000-06-01', end='2001-06-01',
                          freq='30min') + timedelta(minutes=15)
    s = pd.Series(np.full(len(index), np.nan), index=index)

    x = index.values
    y = s

    x_sc = bq.DateScale()
    y_sc = bq.LinearScale(min=0)

    line = bq.Lines(
        x=x,
        y=y,
        scales={
            'x': x_sc,
            'y': y_sc
        },
        #display_legend=True, labels=["line 1"],
        #fill='bottom', # opacity does work with this option
        #fill_opacities = [0.5] *len(x)
    )

    panzoom = bq.PanZoom(scales={'x': [x_sc], 'y': [y_sc]})
    #p = bq.Scatter(x=x, y=y, scales= {'x': x_sc, 'y': y_sc})
    ax_x = bq.Axis(scale=x_sc)
    ax_y = bq.Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')

    #fig = bq.Figure(marks=[line, p], axes=[ax_x, ax_y])
    fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], interaction=panzoom)
    fig.layout.width = '95%'

    #p.interactions = {'click': 'select', 'hover': 'tooltip'}
    #p.selected_style = {'opacity': 1.0, 'fill': 'DarkOrange', 'stroke': 'Red'}
    #p.unselected_style = {'opacity': 0.5}
    #p.tooltip = bq.Tooltip(fields=['x', 'y'], formats=['', '.2f'])

    #sel = bq.interacts.IndexSelector(scale=p.scales['x'])
    #
    #def update_range(*args):
    #    if sel.selected:
    #        print(sel.selected[0])
    #
    #sel.observe(update_range, 'selected')
    #fig.interaction = sel

    return fig, line
예제 #19
0
    def __init__(self, lineFig):
        """
        """

        self.lineFig = lineFig
        self.marks = self.lineFig.marks
        y_ord = bq.OrdinalScale()
        x_sc = bq.LinearScale()

        legendLabels = []
        self.colours = []
        for mark in self.marks:
            legendLabels += mark.labels
            self.colours += mark.colors[:len(mark.labels)]

        self.bars = bq.Bars(
            y=[1] *
            len(legendLabels),  # all bars have a amplitude of 1    ## ?
            x=legendLabels,
            scales={
                'y': x_sc,
                'x': y_ord
            },
            colors=self.colours,
            padding=0.6,
            orientation='horizontal',
            stroke='white')  ## remove the black border around the bar

        self.bars.opacities = [ScatLegend.OPAC_BRIGHT] * len(self.bars.x)

        ax_y = bq.Axis(scale=y_ord, orientation="vertical")
        ax_x = bq.Axis(scale=x_sc)
        ax_x.visible = False
        margin = dict(top=40, bottom=0, left=110, right=5)
        self.fig = bq.Figure(marks=[self.bars],
                             axes=[ax_y, ax_x],
                             fig_margin=margin)

        # Variable height depending on number of bars in legend
        self.fig.layout.height = str(45 + 20 * len(legendLabels)) + 'px'
        self.fig.layout.width = '170px'

        self.fig.min_aspect_ratio = 0.000000000001  # effectively remove aspect ratio constraint
        self.fig.max_aspect_ratio = 999999999999999  # effectively remove aspect ratio constraint
        self.fig.background_style = {'fill': 'White'}

        self.bars.on_element_click(self.changeOpacity)
예제 #20
0
파일: viz.py 프로젝트: zerolugithub/vaex
 def create_axes(self):
     self.x_scale = bqplot.OrdinalScale()
     self.y_scale = bqplot.OrdinalScale(reverse=False)
     self.x_axis = bqplot.Axis(scale=self.x_scale)
     self.y_axis = bqplot.Axis(scale=self.y_scale, orientation='vertical')
     self.x_axis.color = blackish
     self.y_axis.color = blackish
     self.x_axis.label_color = blackish
     self.y_axis.label_color = blackish
     # self.y_axis.tick_style = {'fill': blackish, 'stroke':'none'}
     self.y_axis.grid_color = blackish
     self.x_axis.grid_color = blackish
     self.x_axis.label_offset = "2em"
     self.y_axis.label_offset = "3em"
     self.x_axis.grid_lines = 'none'
     self.y_axis.grid_lines = 'none'
     self.axes = [self.x_axis, self.y_axis]
예제 #21
0
 def get_axes(self, ylabel):
     font_size = 15
     axx = bq.Axis(
         scale=self.scales["x"],
         grid_lines="solid",
         tick_format="%H:%M:%S",
         tick_style={"font-size": font_size},
     )
     axy = bq.Axis(
         scale=self.scales["y"],
         grid_lines="solid",
         orientation="vertical",
         label=ylabel,
         label_offset="40px",
         tick_style={"font-size": font_size},
     )
     return axx, axy
예제 #22
0
    def __init__(self, precisions, recalls, thres):
        assert (len(recalls) == len(precisions) == len(thres))

        # Callback
        def index_change_callback(change):
            selected_recall = int(np.round(change.new[0]))
            index = np.abs(recalls - selected_recall).argmin()
            w_precision.value = "{:2.2f}".format(precisions[index])
            w_recall.value = "{:2.2f}".format(recalls[index])
            w_threshold.value = "{:2.2f}".format(thres[index])

        # Set up bqplot UI
        ls_x = bqplot.LinearScale(min=0, max=100)  # reverse=True)
        ls_y = bqplot.LinearScale(min=0, max=100)
        axis_y = bqplot.Axis(label='Recall', scale=ls_x)
        axis_x = bqplot.Axis(label='Precision',
                             scale=ls_y,
                             orientation='vertical')
        lines = bqplot.Lines(x=recalls,
                             y=precisions,
                             scales={
                                 'x': ls_x,
                                 'y': ls_y
                             },
                             colors=['orange'])
        index_sel = bqplot.interacts.IndexSelector(scale=ls_x,
                                                   marks=[lines],
                                                   color="blue",
                                                   colors=["green"])
        index_sel.observe(index_change_callback, names=['selected'])
        fig = bqplot.Figure(marks=[lines],
                            axes=[axis_x, axis_y],
                            title='Precision-recall curve',
                            interaction=index_sel)

        # Set up p/r/threshold text fields UI
        w_precision = widgets.Text(value="CLICK ON PLOT",
                                   description="Precision:")
        w_recall = widgets.Text(value="CLICK ON PLOT", description="Recall:")
        w_threshold = widgets.Text(value="CLICK ON PLOT",
                                   description="Threshold:")
        w_texts = widgets.HBox(children=[w_precision, w_recall, w_threshold])

        # Create final UI
        self.ui = widgets.VBox([fig, w_texts])
예제 #23
0
    def __init__(self, session, state=None):

        # if we allow padding, we sometimes get odd behaviour with the interacts
        self.scale_x = bqplot.LinearScale(min=0, max=1, allow_padding=False)
        self.scale_y = bqplot.LinearScale(min=0, max=1)

        super(BqplotBaseView, self).__init__(session, state=state)
        # session.hub.subscribe(self, SubsetCreateMessage,
        #                       handler=self.receive_message)

        self.scales = {'x': self.scale_x, 'y': self.scale_y}
        self.axis_x = bqplot.Axis(
            scale=self.scale_x, grid_lines='solid', label='x')
        self.axis_y = bqplot.Axis(scale=self.scale_y, orientation='vertical', tick_format='0.2f',
                                  grid_lines='solid', label='y')
        def update_axes(*ignore):
            self.axis_x.label = str(self.state.x_att)
            if self.is2d:
                self.axis_y.label = str(self.state.y_att)
        self.state.add_callback('x_att', update_axes)
        if self.is2d:
            self.state.add_callback('y_att', update_axes)
        self.figure = bqplot.Figure(scales=self.scales, animation_duration=0, axes=[
                                    self.axis_x, self.axis_y])
        self.figure.padding_y = 0
        self._fig_margin_default = self.figure.fig_margin
        self._fig_margin_zero = dict(self.figure.fig_margin)
        self._fig_margin_zero['left'] = 0
        self._fig_margin_zero['bottom'] = 0

        link((self.state, 'x_min'), (self.scale_x, 'min'), float_or_none)
        link((self.state, 'x_max'), (self.scale_x, 'max'), float_or_none)
        link((self.state, 'y_min'), (self.scale_y, 'min'), float_or_none)
        link((self.state, 'y_max'), (self.scale_y, 'max'), float_or_none)

        on_change([(self.state, 'show_axes')])(self._sync_show_axes)

        self.create_tab()
        self.output_widget = widgets.Output()

        self.main_widget = widgets.VBox([
                self.widget_toolbar,
                widgets.HBox([self.figure, self.tab]),
                self.output_widget
            ])
예제 #24
0
def make_pred_bqplot():
    x_sc = bq.LinearScale()
    y_sc = bq.LinearScale()

    ax_x = bq.Axis(label="Feature", scale=x_sc)  # , tick_format="0.0f"
    ax_y = bq.Axis(
        label="Target",
        scale=y_sc,
        orientation="vertical"  # , tick_format="0.0e"
    )

    line = bq.Lines(
        x=[0],
        y=[0],
        scales={
            "x": x_sc,
            "y": y_sc
        },
        colors=["darkblue"],
        opacities=[1],
    )

    scatter = bq.Scatter(
        x=[0],
        y=[0],
        scales={
            "x": x_sc,
            "y": y_sc
        },
        colors=["red"],
        opacities=[1],
    )
    out_plot = bq.Figure(
        axes=[ax_x, ax_y],
        marks=[line, scatter],
        #     interaction=interval_selector,
        # animation_duration=100,
    )

    out_plot.legend_style = {"stroke-width": 0}
    out_plot.layout.width = "flex"
    return {k: v for k, v in locals().items()}
예제 #25
0
    def _getFig(self):
        for v in self.model.label:
            x_sc = bq.LinearScale()
            y_sc = bq.LinearScale()

            x_ax = bq.Axis(label='Time',
                           scale=x_sc,
                           tick_format='0.0f',
                           color='black',
                           grid_lines='solid',
                           grid_color='#ddd')
            y_ax = bq.Axis(label=v,
                           scale=y_sc,
                           tick_format='0.2f',
                           color='black',
                           grid_lines='solid',
                           grid_color='#ddd',
                           orientation='vertical')

            # Generate a line (but does not plot it)
            l = bq.Lines(x=self.model.T,
                         y=self.sol[v],
                         colors=[self.colors[v]],
                         scales={
                             'x': x_sc,
                             'y': y_sc
                         })

            self.lines.update({v: l})

        fig = bq.Figure(axes=[x_ax, y_ax],
                        marks=self.lines.values(),
                        fig_margin={
                            'top': 10,
                            'bottom': 0,
                            'left': 60,
                            'right': 10
                        },
                        max_aspect_ratio=3,
                        min_aspect_ratio=2.5)
        fig.layout.width = '100%'
        return fig
예제 #26
0
    def _get_hist_figure(self, x, y, color, bidx):
        '''
        get a bqplot histogram figure with data and interactive sliders
        '''
        x_scale = bq.LinearScale()
        y_scale = bq.LinearScale()

        x_axis = bq.Axis(scale=x_scale, tick_values=None, num_ticks=3)
        y_axis = bq.Axis(scale=y_scale,
                         tick_values=None,
                         num_ticks=0,
                         orientation='vertical',
                         visible=False)

        line = bq.Lines(x=x,
                        y=y,
                        scales={
                            'x': x_scale,
                            'y': y_scale
                        },
                        colors=[color],
                        selected_style={'opacity': '1'},
                        unselected_style={'opacity': '0.2'})

        fast_sel = bq.interacts.FastIntervalSelector(marks=[line],
                                                     scale=x_scale,
                                                     color='orange')

        fig = bq.Figure(title=color,
                        marks=[line],
                        axes=[x_axis, y_axis],
                        fig_margin={
                            'top': 40,
                            'bottom': 40,
                            'left': 40,
                            'right': 40
                        },
                        interaction=fast_sel)
        fig.layout.width = '225px'
        fig.layout.height = '225px'

        return fig
예제 #27
0
 def __init__(self):
     # self.experiment_plot = plt.subplots(figsize=(18, 4))
     # self.experiment_plot_output = widgets.Output()
     self.x_sc = LinearScale()
     self.y_sc = LinearScale()
     ax_x = bq.Axis(label='steps', scale=self.x_sc, grid_lines='solid')
     ax_y = bq.Axis(label='loss',
                    scale=self.y_sc,
                    orientation='vertical',
                    side='left',
                    grid_lines='solid')
     self.scales = {'x': self.x_sc, 'y': self.y_sc}
     self.experiment_figure = Figure(
         title='comparison',
         marks=[],
         layout=widgets.Layout(width='100%'),
         axes=[ax_x, ax_y],
         legend_location='top-right',
     )
     super(LearningCurve, self).__init__([self.experiment_figure])
예제 #28
0
 def __init__(self):
     # self.experiment_plot = plt.subplots(figsize=(18, 4))
     # self.experiment_plot_output = widgets.Output()
     self.x_sc = LinearScale()
     self.y_sc = LinearScale()
     ax_x = bq.Axis(label="steps", scale=self.x_sc, grid_lines="solid")
     ax_y = bq.Axis(
         label="success rate",
         scale=self.y_sc,
         orientation="vertical",
         side="left",
         grid_lines="solid",
     )
     self.scales = {"x": self.x_sc, "y": self.y_sc}
     self.experiment_figure = Figure(
         title="comparison",
         marks=[],
         layout=widgets.Layout(width="100%"),
         axes=[ax_x, ax_y],
         legend_location="top-right",
     )
     super(PolicyComparison, self).__init__([self.experiment_figure])
예제 #29
0
    def __init__(self, session, state=None):

        # if we allow padding, we sometimes get odd behaviour with the interacts
        self.scale_x = bqplot.LinearScale(min=0, max=1, allow_padding=False)
        self.scale_y = bqplot.LinearScale(min=0, max=1)

        super(BqplotBaseView, self).__init__(session, state=state)

        self.scales = {'x': self.scale_x, 'y': self.scale_y}
        self.axis_x = bqplot.Axis(
            scale=self.scale_x, grid_lines='none', label='x')
        self.axis_y = bqplot.Axis(scale=self.scale_y, orientation='vertical', tick_format='0.2f',
                                  grid_lines='none', label='y')

        def update_axes(*ignore):
            self.axis_x.label = str(self.state.x_att)
            if self.is2d:
                self.axis_y.label = str(self.state.y_att)

        self.state.add_callback('x_att', update_axes)
        if self.is2d:
            self.state.add_callback('y_att', update_axes)
        self.figure = bqplot.Figure(scales=self.scales, animation_duration=0,
                                    axes=[self.axis_x, self.axis_y],
                                    fig_margin={'left': 60, 'bottom': 60, 'top': 10, 'right': 10})
        self.figure.padding_y = 0
        self._fig_margin_default = self.figure.fig_margin
        self._fig_margin_zero = dict(self.figure.fig_margin)
        self._fig_margin_zero['left'] = 0
        self._fig_margin_zero['bottom'] = 0

        link((self.state, 'x_min'), (self.scale_x, 'min'), float_or_none)
        link((self.state, 'x_max'), (self.scale_x, 'max'), float_or_none)
        link((self.state, 'y_min'), (self.scale_y, 'min'), float_or_none)
        link((self.state, 'y_max'), (self.scale_y, 'max'), float_or_none)

        on_change([(self.state, 'show_axes')])(self._sync_show_axes)

        self.create_layout()
예제 #30
0
def plot():
    co2_conc = in_dd1.value
    key_x = in_dd2.value
    key_y = in_dd3.value

    dir_name = Path(co2_dict[co2_conc])
    df = get_df(dir_name)

    sc_x = bq.LinearScale(min=5, max=25)
    sc_y = bq.LinearScale()

    da_x = df[key_x]
    da_y = df[key_y]

    ax_x = bq.Axis(scale=sc_x, grid_lines='solid', label=key_x)
    ax_y = bq.Axis(scale=sc_y, orientation='vertical', label=key_y)

    lines = bq.Lines(x=da_x,
                     y=da_y,
                     scales={
                         'x': sc_x,
                         'y': sc_y
                     },
                     stroke_width=3,
                     colors=['blue'])

    #ax.plot('wavlen_um','total_trans',data=df)
    #ax.set_title(key)
    #ax.set_xlim([5,25])
    grid[:, 1:2] = bq.Figure(marks=[lines],
                             axes=[ax_x, ax_y],
                             layout=Layout(width='auto', height='auto'),
                             fig_margin=dict(top=60,
                                             bottom=40,
                                             left=40,
                                             right=0),
                             title=key_x + ' vs ' + key_y +
                             ' with CO2 conc. = ' + co2_conc)