Ejemplo n.º 1
0
    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])))
Ejemplo n.º 2
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',
        )
Ejemplo n.º 3
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
Ejemplo n.º 4
0
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
Ejemplo n.º 5
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
            ]
        )
Ejemplo n.º 6
0
Archivo: bqplot.py Proyecto: 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)
Ejemplo n.º 7
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
    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)
        ])
Ejemplo n.º 9
0
 def __init__(self, scheme, count=None, **options):
     colors = self.palettes[scheme]
     super().__init__(scheme, count or len(colors))
     self.colors = self.mkpal(colors, self.count)
     self.opt = opt = getopt(options,
                             fig_title=self.scheme,
                             fig_width=960,
                             fig_height=150)
     data = np.arange(0, len(self.colors))
     cs = bq.ColorScale(colors=self.colors)
     hm = bq.HeatMap(color=np.array([data, data]), scales={"color": cs})
     self.figure = bq.Figure(marks=[hm],
                             layout=ipw.Layout(
                                 width="%spx" % opt.fig["width"],
                                 height="%spx" % opt.fig["height"]),
                             padding_x=0.0,
                             padding_y=0.0,
                             fig_margin={
                                 "top": 60,
                                 "bottom": 0,
                                 "left": 0,
                                 "right": 0
                             },
                             title=opt.fig["title"])
     self.vbox = ipw.VBox([self.figure, bq.Toolbar(figure=self.figure)])
Ejemplo n.º 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}
Ejemplo n.º 11
0
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"))
Ejemplo n.º 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
Ejemplo n.º 13
0
    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
Ejemplo n.º 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
Ejemplo n.º 15
0
    def display(self):
        pos = networkx.nx_pydot.graphviz_layout(self._graph, prog='dot')
        x, y = zip(*(pos[node] for node in self._graph.nodes()))

        fw_id_to_node_index = {
            self._fw_workflow.fws[i].fw_id: i
            for i in range(len(self._fw_workflow.fws))
        }

        node_data = [{
            'label': str(node.fw_id),
            'name': node.name,
            'state': node.state,
            'tasks': [str(t) for t in node.tasks],
            'shape': 'rect',
        } for node in self._fw_workflow.fws]

        link_data = [{
            'source': fw_id_to_node_index[source],
            'target': fw_id_to_node_index[target]
        } for source, target in self._graph.edges()]

        xs = bqplot.LinearScale(min=min(x), max=max(x))
        ys = bqplot.LinearScale(min=min(y), max=max(y))
        scales = {'x': xs, 'y': ys}

        graph = bqplot.Graph(node_data=node_data,
                             link_data=link_data,
                             scales=scales,
                             colors=['white'],
                             link_type='line',
                             highlight_links=False,
                             x=x,
                             y=y,
                             selected_style={
                                 'stroke': 'yellow',
                                 'stroke-width': '4',
                                 'opacity': '0.5'
                             })

        tooltip = bqplot.Tooltip(fields=['name', 'state', 'tasks'],
                                 format=['', '', ''])
        graph.tooltip = tooltip

        layout = ipywidgets.Layout(min_width='50%',
                                   width='auto',
                                   min_height='200px',
                                   height='auto')
        fig = bqplot.Figure(marks=[graph], layout=layout)
        #toolbar = bqplot.Toolbar(figure=fig)
        #return ipywidgets.VBox([fig, toolbar])
        return ipywidgets.VBox([fig])
Ejemplo n.º 16
0
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])
Ejemplo n.º 17
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])
Ejemplo n.º 18
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)
Ejemplo n.º 19
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
Ejemplo n.º 20
0
    def make_image_plot(self):

        marks = [self.bq_img]
        for interactor in self.interactors:
            marks += interactor.image_plot_marks

        image_plot = bq.Figure(marks=marks, padding_y=0)

        height, width, _ = self.raw_frame.get().shape
        # make sure the image is displayed with the correct aspect ratio
        image_plot.layout.width = '100%'
        image_plot.layout.margin = '0'
        image_plot.layout.height = str(self.size * self.FULL_INTERNAL_WIDTH *
                                       height / width +
                                       self.size * self.FULL_OFFSET) + 'px'

        return image_plot
Ejemplo n.º 21
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])
Ejemplo n.º 22
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
            ])
Ejemplo n.º 23
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
Ejemplo n.º 24
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
Ejemplo n.º 25
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()}
Ejemplo n.º 26
0
    def display(self):
        pos = networkx.nx_pydot.graphviz_layout(self._graph, prog='dot')
        x, y = zip(*(pos[node] for node in self._graph.nodes()))

        node_data = [{
            'label': str(node._id),
            'shape': 'rect',
            'tasks': [str(t) for t in node._tasks]
        } for node in self._graph.nodes()]

        link_data = [{
            'source': source.index[self],
            'target': target.index[self]
        } for source, target in self._graph.edges()]

        xs = bqplot.LinearScale()
        ys = bqplot.LinearScale()
        scales = {'x': xs, 'y': ys}

        graph = bqplot.Graph(node_data=node_data,
                             link_data=link_data,
                             scales=scales,
                             colors=['white'],
                             link_type='line',
                             highlight_links=False,
                             x=x,
                             y=y,
                             selected_style={
                                 'stroke': 'yellow',
                                 'stroke-width': '4',
                                 'opacity': '0.5'
                             })

        tooltip = bqplot.Tooltip(fields=['tasks'])
        graph.tooltip = tooltip

        layout = ipywidgets.Layout(min_width='50%',
                                   width='auto',
                                   min_height='200px',
                                   height='auto')
        fig = bqplot.Figure(marks=[graph], layout=layout)
        return ipywidgets.VBox([fig])
    def create_fig(self, *args):
        logger.info('Creating figure.')

        tooltip_widget = plt.Tooltip(fields=['size', 'label'])
        pie = plt.Pie(tooltip=tooltip_widget,
                      interactions={
                          'click': 'select',
                          'hover': 'tooltip'
                      })

        pie.radius = 110
        pie.inner_radius = 65
        pie.font_weight = 'bold'
        pie.selected_style = {
            "opacity": "1",
            "stroke": "white",
            "stroke-width": "4"
        }
        pie.unselected_style = {"opacity": "0.5"}
        logger.info('Returning figure.')

        return plt.Figure(marks=[pie])
Ejemplo n.º 28
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()
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
 def gui_figure (self) :
     self._x_scale = bq.LinearScale(min=0, max=self.opt.fig.width)
     self._y_scale = bq.LinearScale(min=0, max=self.opt.fig.height)
     if self.opt.fig.title is None :
         title, top = " ", 0
     else :
         title = str(self.opt.fig.title).strip() or " "
         top = 60 if title != " " else 0
     title = str(self.opt.fig.title) or " " if self.opt.fig.title else " "
     figure = bq.Figure(marks=([self.gui_graph]
                               + list(self.gui_marks.values())
                               + list(self.gui_tips.values())),
                        layout=ipw.Layout(width="%spx" % self.opt.fig.width,
                                          height="%spx" % self.opt.fig.height),
                        padding_x=self.opt.fig.padding,
                        padding_y=self.opt.fig.padding,
                        fig_margin={"top" : top,
                                    "bottom" : 0,
                                    "left" : 0,
                                    "right" : 0},
                        background_style={"fill" : self.opt.fig.background},
                        title=title)
     return figure