示例#1
0
 def setUp(self):
     self.size = (250, 250)
     data_source = ArrayDataSource(arange(10))
     index_range = DataRange1D()
     index_range.add(data_source)
     index_mapper = LinearMapper(range=index_range)
     self.linescatterplot = LineScatterPlot1D(
         index=data_source,
         index_mapper=index_mapper,
         border_visible=False,
     )
     self.linescatterplot.outer_bounds = list(self.size)
示例#2
0
    def test_change_min_max(self):
        """ Test that changing min_value and max_value does not break map. """

        datarange = self.colormap.range

        # Perform a dummy mapping.
        a = ArrayDataSource(array([0.0, 0.5, 1.0]))
        datarange.add(a)
        b = self.colormap.map_screen(a.get_data())
        datarange.remove(a)

        # Update the min_value.
        datarange.low = -1.0

        # Test that the map still works.
        a = ArrayDataSource(array([-1.0, 0.0, 1.0]))
        datarange.add(a)
        b = self.colormap.map_screen(a.get_data())
        datarange.remove(a)
        expected = array([0.0, 0.5, 1.0])

        close = allclose(ravel(b[:,:1]), expected, atol=0.02)
        self.assertTrue(close,
            "Changing min value broke map.  Expected %s.  Got %s" % (expected, b[:,:1]))

        # Update the max_value.
        datarange.high = 0.0
        # Test that the map still works.
        a = ArrayDataSource(array([-1.0, -0.5, 0.0]))
        datarange.add(a)
        b = self.colormap.map_screen(a.get_data())
        datarange.remove(a)
        expected = array([0.0, 0.5, 1.0])

        close = allclose(ravel(b[:,:1]), expected, atol=0.02)
        self.assertTrue(close,
            "Changing min value broke map.  Expected %s.  Got %s" % (expected, b[:,:1]))


        return
示例#3
0
 def test_reversed_set_screen_bounds(self):
     ary = array([5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
     ds = ArrayDataSource(ary)
     r = DataRange1D(ds)
     mapper = LinearMapper(range=r)
     self.assertFalse(mapper._low_bound_initialized)
     self.assertFalse(mapper._high_bound_initialized)
     mapper.screen_bounds = (100.0, 0.0)
     self.assertTrue(mapper._low_bound_initialized)
     self.assertTrue(mapper._high_bound_initialized)
     result = mapper.map_screen(ary)
     assert_equal(result, array([100, 80, 60, 40, 20, 0]))
     return
示例#4
0
    def _timeseries_changed(self, new):
        # Filter down to days
        cols = new.columns
        idx = [time.mktime(d.utctimetuple()) for d in new.index]
        self.index_ds.set_data(idx)
        vals = []
        self.rows = list(reversed(cols[2:-6:2]))
        for col in self.rows:
            data = new[col]
            vals.append(ArrayDataSource(data.view(numpy.ndarray)))

        self.value_ds = vals
        self._rebuild_plot()
示例#5
0
    def _add_lines(self, flip=False):
        # When non fliped is index objects
        if flip:
            self.index_labels = self.plot_data.var_n
            pl_itr = self.plot_data.mat.iterrows()
        else:
            self.index_labels = self.plot_data.obj_n
            pl_itr = self.plot_data.mat.iteritems()
        idx = ArrayDataSource(range(len(self.index_labels)))
        self.index_range.add(idx)

        line_styles = ['solid', 'dot dash', 'dash', 'dot', 'long dash']
        i = 0
        for name, vec in pl_itr:
            i += 1
            vals = ArrayDataSource(vec.values)
            self.value_range.add(vals)
            plot = LinePlot(index=idx, index_mapper=self.index_mapper,
                            value=vals, value_mapper=self.value_mapper,
                            color=COLOR_PALETTE[i % 4], line_style=line_styles[i % 4])
            self.add(plot)
            self.plots[name] = plot
示例#6
0
    def drawquiver(self, x1c, y1c, x2c, y2c, color, linewidth=1.0, scale=1.0):
        """ drawquiver draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
        parameters:
            x1c - array of x1 coordinates
            y1c - array of y1 coordinates
            x2c - array of x2 coordinates
            y2c - array of y2 coordinates
            color - color of the line
            linewidth - linewidth of the line
        example usage:
            drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
            draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200

        """
        x1, y1, x2, y2 = self.remove_short_lines(x1c,
                                                 y1c,
                                                 x2c,
                                                 y2c,
                                                 min_length=0)
        if len(x1) > 0:
            xs = ArrayDataSource(x1)
            ys = ArrayDataSource(y1)

            quiverplot = QuiverPlot(
                index=xs,
                value=ys,
                index_mapper=LinearMapper(range=self._plot.index_mapper.range),
                value_mapper=LinearMapper(range=self._plot.value_mapper.range),
                origin=self._plot.origin,
                arrow_size=0,
                line_color=color,
                line_width=linewidth,
                ep_index=np.array(x2) * scale,
                ep_value=np.array(y2) * scale)
            self._plot.add(quiverplot)
            # we need this to track how many quiverplots are in the current
            # plot
            self._quiverplots.append(quiverplot)
示例#7
0
 def test_basic(self):
     ary = array([5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
     ds = ArrayDataSource(ary)
     r = DataRange1D(ds)
     mapper = LinearMapper(range=r)
     self.assertFalse(mapper._low_bound_initialized)
     self.assertFalse(mapper._high_bound_initialized)
     mapper.low_pos = 50
     self.assertTrue(mapper._low_bound_initialized)
     mapper.high_pos = 100
     self.assertTrue(mapper._high_bound_initialized)
     result = mapper.map_screen(ary)
     assert_equal(result, array([50, 60, 70, 80, 90, 100]))
     return
示例#8
0
    def test_custom_bounds_func(self):
        def custom_func(low, high, margin, tight_bounds):
            assert_equal(low, 0.0)
            assert_equal(high, 9.0)
            assert_equal(tight_bounds, False)
            assert_equal(margin, 1.0)
            return -999., 999.

        r = DataRange1D(tight_bounds=False, margin=1.0, bounds_func=custom_func)
        ary = arange(10.0)
        ds = ArrayDataSource(ary)
        r.sources.append(ds)
        assert_equal(r.low, -999.)
        assert_equal(r.high, 999.)
 def test_errorbarplot(self):
     """ Coverage test to check basic case works """
     size = (50, 50)
     x = np.array([1, 2])
     y = np.array([5, 10])
     errors = np.array([1, 2])
     low = ArrayDataSource(y - errors)
     high = ArrayDataSource(y + errors)
     errorbar_plot = ErrorBarPlot(
         index=ArrayDataSource(x),
         values=ArrayDataSource(y),
         index_mapper=LinearMapper(range=DataRange1D(low=0, high=3)),
         value_mapper=LinearMapper(range=DataRange1D(low=0, high=15)),
         value_low=low,
         value_high=high,
         color='blue',
         line_width=3.0,
     )
     errorbar_plot.outer_bounds = list(size)
     gc = PlotGraphicsContext(size)
     gc.render_component(errorbar_plot)
     actual = gc.bmp_array[:, :, :]
     self.assertFalse(alltrue(actual == 255))
示例#10
0
    def test_simple_map(self):

        a = ArrayDataSource(array([0.0, 0.5, 1.0]))
        self.colormap.range.add(a)
        b = self.colormap.map_screen(a.get_data())
        self.colormap.range.remove(a)

        expected = array([0.0, 0.5, 1.0])

        close = allclose(ravel(b[:,:1]), expected, atol=0.02)
        self.assertTrue(close,
            "Simple map failed.  Expected %s.  Got %s" % (expected, b[:,:1]))

        return
示例#11
0
    def setUp(self):
        self.size = (250, 250)
        index_data_source = ArrayDataSource(arange(10))
        index_range = DataRange1D()
        index_range.add(index_data_source)
        index_mapper = LinearMapper(range=index_range)

        value_data_source = ArrayDataSource(arange(1, 11))
        value_range = DataRange1D()
        value_range.add(value_data_source)
        value_mapper = LinearMapper(range=value_range)

        text_data_source = ArrayDataSource(
            array(["one", "two", "three", "four", "five"]))

        self.text_plot = TextPlot(
            index=index_data_source,
            index_mapper=index_mapper,
            value=value_data_source,
            value_mapper=value_mapper,
            border_visible=False,
            text=text_data_source,
        )
        self.text_plot.outer_bounds = list(self.size)
示例#12
0
    def _create_plot(self, orientation="h", p_type=ToolbarPlot):
        """
        Creates a plot from a single Nx2 data array or a tuple of
        two length-N 1-D arrays.  The data must be sorted on the index if any
        reverse-mapping tools are to be used.

        Pre-existing "index" and "value" datasources can be passed in.
        """
        index = ArrayDataSource(self.column(self.xc), sort_order="none")
        value = ArrayDataSource(self.column(self.yc))
        index_range = DataRange1D()
        index_range.add(index)
        index_mapper = self.mappers[self.xm](range=index_range)
        value_range = DataRange1D()
        value_range.add(value)
        value_mapper = self.mappers[self.ym](range=value_range)
        if self.p_type == "line" and self.outline_width <= 0:
            self.outline_width = 1

        plot = p_type(index=index,
                      value=value,
                      index_mapper=index_mapper,
                      value_mapper=value_mapper,
                      orientation=orientation,
                      border_visible=True,
                      bgcolor="transparent")
        if issubclass(p_type, ScatterPlot):
            plot.marker = self.marker
            plot.marker_size = self.marker_size
            plot.outline_color = self.line_color
            plot.color = self.color
        elif issubclass(p_type, LinePlot):
            plot.line_wdith = self.outline_width
            plot.line_style = self.line_style
            plot.color = self.line_color
        return plot
示例#13
0
    def _add_ci_bars(self):
        # Create vertical bars to indicate confidence interval
        # index = self.mk_ads('index')
        index = ArrayDataSource(range(len(self.index_labels)))
        value_lo = self.mk_ads('ylow')
        value_hi = self.mk_ads('yhigh')

        plot_ci = ErrorBarPlot(
            index=index, index_mapper=self.index_mapper,
            value_low=value_lo, value_high=value_hi,
            value_mapper=self.value_mapper,
            border_visible=True,
            name='CIbars')

        self.add(plot_ci)
示例#14
0
    def _make_plot_frame(self):
        super(MainEffectsPlot, self)._make_plot_frame()
        # Update plot ranges and mappers
        self.index_labels = self.plot_data.obj_n
        index = ArrayDataSource(range(len(self.index_labels)))
        self.index_range.add(index)
        for name in ['values', 'ylow', 'yhigh']:
            value = self.mk_ads(name)
            self.value_range.add(value)

        # Add label with average standard error
        avg_text = "Average standard error: {}".format(self.avg_std_err)
        self._add_avg_std_err(avg_text)

        add_default_grids(self)
示例#15
0
    def line_plot(self, x, y, new_plot=True):
        if self.plot is None or new_plot:
            if isinstance(x, (float, int)):
                x = [x]

            if isinstance(y, (float, int)):
                y = [y]

            self.plot = LinePlot(
                index=ArrayDataSource(x),
                value=ArrayDataSource(y),
                index_mapper=LinearMapper(range=self.index_range),
                value_mapper=LinearMapper(range=self.value_range))

            self.add(self.plot)
        else:

            datax = self.plot.index.get_data()
            datay = self.plot.value.get_data()
            nx = hstack((datax, [x]))
            ny = hstack((datay, [y]))

            self.plot.index.set_data(nx)
            self.plot.value.set_data(ny)
示例#16
0
    def _dipole_data_model_changed(self, old, new):
        print('dipole_data_model_changed')
        #self.dipole_plot.index_range = self.signals_renderer.index_range
        #self.dipole_plot.index = self.signals_renderer.index
        print(dir(self.dipole_data_model.x_index))
        xs = ArrayDataSource(self.dipole_data_model.x_index,
                             sort_order='ascending')
        xrange = DataRange1D()
        xrange.add(xs)

        self.dipole_plot.index.set_data(self.dipole_data_model.x_index)
        self.dipole_plot.value.set_data(self.dipole_data_model.data)

        self.dipole_plot.index_mapper.range = xrange

        self.dipole_plot.request_redraw()
    def test_reverse_construction(self):
        mapper = LinearMapper()
        r = DataRange1D()
        ds = ArrayDataSource()
        ary = array([1, 2, 3, 4, 5, 6, 7])

        mapper.range = r
        mapper.low_pos = 1.0
        mapper.high_pos = 7.0
        r.add(ds)
        ds.set_data(ary)

        self.assertTrue(r.low == 1)
        self.assertTrue(r.high == 7)
        screen_pts = mapper.map_screen(array([1, 3, 7]))
        self.assertTrue(tuple(screen_pts) == (1.0, 3.0, 7.0))
        return
示例#18
0
    def __init__(self, index, series_a, series_b, series_c, **kw):
        super(PlotExample, self).__init__(**kw)

        plot_data = ArrayPlotData(index=index)
        starting_values = np.ones(10) * 0.5
        starting_vals = ArrayDataSource(starting_values, sort_order="none")
        series_a = series_a + starting_values
        plot_data.set_data('series_a', series_a)
        plot_data.set_data('series_b', series_b)
        plot_data.set_data('series_c', series_c)
        self.plot = Plot(plot_data)

        self.plot.plot(('index', 'series_a'),
                       type='bar',
                       bar_width=0.8,
                       color='auto',
                       starting_value=starting_vals)

        # set the plot's value range to 0, otherwise it may pad too much
        self.plot.value_range.low = 0

        tick_positions_and_labels = {
            x: 'label_{}'.format(x)
            for x in range(1, 11)
        }
        tick_generator = ShowAllTickGenerator(
            positions=tick_positions_and_labels.keys())

        def formatter(value):
            return tick_positions_and_labels[int(value)]

        plot_axis = PlotAxis(
            component=self.plot,
            mapper=self.plot.x_mapper,
            # labels=labels,
            orientation='bottom',
            tick_generator=tick_generator,
            tick_label_rotate_angle=-45.,
            tick_label_alignment='corner',
            tick_label_formatter=formatter,
            tick_label_offset=3)

        self.plot.underlays.remove(self.plot.index_axis)
        self.plot.index_axis = plot_axis
        self.plot.overlays.append(plot_axis)
示例#19
0
    def test_piecewise_construction(self):
        ary = array([1, 2, 3, 4, 5, 6, 7])
        ds = ArrayDataSource()
        ds.set_data(ary)
        r = DataRange1D()
        r.add(ds)
        self.assert_(r.low_setting == "auto")
        self.assert_(r.high_setting == "auto")
        self.assert_(r.low == 1)
        self.assert_(r.high == 7)

        mapper = LinearMapper()
        mapper.range = r
        mapper.low_pos = 1.0
        mapper.high_pos = 7.0
        screen_pts = mapper.map_screen(array([1, 3, 7]))
        self.assert_(tuple(screen_pts) == (1.0, 3.0, 7.0))
        return
示例#20
0
    def test_array_factory(self):
        """ Test that the array factory creates valid colormap. """

        colors = array([[0.0,0.0,0.0], [1.0,1.0,1.0]])
        cm = ColorMapper.from_palette_array(colors)
        cm.range = DataRange1D()

        ar = ArrayDataSource(array([0.0, 0.5, 1.0]))
        cm.range.add(ar)
        b = cm.map_screen(ar.get_data())
        cm.range.remove(ar)

        expected = array([0.0, 0.5, 1.0])

        self.assertTrue(allclose(ravel(b[:,:1]), expected, atol=0.02),
            "Array factory failed.  Expected %s.  Got %s" % (expected, b[:,:1]))

        return
示例#21
0
def make_data_sources(session, index_sort="none", *args):
    """ Given a list of arguments, returns a list of (index, value) datasources
    to create plots from.
    """
    # Make sure everything is a numpy array
    data = []
    for arg in args:
        if isinstance(arg, list) or isinstance(arg, tuple):
            data.append(array(arg))
        else:
            data.append(arg)

    if len(data) == 0:
        raise ChacoShellError("Insufficient data for plot.")

    # 1D array(s)
    if len(data[0].shape) == 1:
        if len(data) == 1:
            # Only a single array was provided
            index_ds = ArrayDataSource(arange(len(data[0])),
                                       sort_order="ascending")
            value_ds = ArrayDataSource(data[0], sort_order="none")
            return [(index_ds, value_ds)]

        else:
            # multiple arrays were provided
            index_ds = ArrayDataSource(data[0], sort_order=index_sort)
            return [(index_ds, ArrayDataSource(v, sort_order="none"))
                    for v in data[1:]]

    # 2D arrays
    elif len(data[0].shape) == 2:
        sources = []
        # Loop over all the 2D arrays
        for ary in data:
            if ary.shape[0] > ary.shape[1]:
                index_ary = ary[:, 0]
                value_arrays = ary[:, 1:]
            else:
                index_ary = ary[0]
                value_arrays = transpose(ary[1:])
            index_ds = ArrayDataSource(index_ary, sort_order=index_sort)
            sources.extend([(index_ds, ArrayDataSource(v, sort_order="none"))
                            for v in value_arrays])
        return sources

    # Not a two-dimensional array, error.
    else:
        raise ChacoShellError(
            "Unable to create plot data sources from array of shape " +
            str(data[1].shape) + ".")
def _create_plot_component():
    # make 10 random points
    x = arange(10)
    x = ArrayDataSource(x, sort_order="ascending")
    y = random_sample(10)

    # Plot the data
    pd = ArrayPlotData(x=x, y=y)

    plot = Plot(pd)
    plot.orientation = 'v'
    line_plot = plot.plot(("x", "y"))[0]

    # Add the tool to the plot both as a tool and as an overlay
    tool = HittestTool(component=plot, line_plot=line_plot)
    plot.tools.append(tool)
    plot.overlays.append(tool)

    return plot
示例#23
0
    def _add_lines(self):
        # index = self.mk_ads('index')
        index = ArrayDataSource(range(len(self.index_labels)))
        value = self.mk_ads('values')

        # Create lineplot
        plot_line = LinePlot(
            index=index, index_mapper=self.index_mapper,
            value=value, value_mapper=self.value_mapper,
            name='line')

        # Add datapoint enhancement
        plot_scatter = ScatterPlot(
            index=index, index_mapper=self.index_mapper,
            value=value, value_mapper=self.value_mapper,
            color="blue", marker_size=5,
            name='scatter',
        )

        self.add(plot_line, plot_scatter)
示例#24
0
 def set_result_data(self):
     if self.invalid:
         return
     if self.cursor:
         self.cursor.current_position = self.synth.synth_freq, 0
     pd = self.plot_data
     if not pd:
         return
     g = self.Beamformer.grid
     try:
         map_data = self.Beamformer.synthetic(self.synth.synth_freq,
                                              self.synth.synth_type_).T
         map_data = L_p(map_data)
     except:
         map_data = arange(0, 19.99, 20. / g.size).reshape(g.shape)
     pd.set_data("map_data", map_data)
     f = self.Beamformer.freq_data
     if self.zoom and self.zoom.box:
         sector = self.zoom.box
     else:
         sector = (g.x_min, g.y_min, g.x_max, g.y_max)
     pd.set_data("xpoly", array(sector)[[0, 2, 2, 0]])
     pd.set_data("ypoly", array(sector)[[1, 1, 3, 3]])
     ads = pd.get_data("freqs")
     if not ads:
         freqs = ArrayDataSource(f.fftfreq()[f.ind_low:f.ind_high],
                                 sort_order='ascending')
         pd.set_data("freqs", freqs)
     else:
         ads.set_data(f.fftfreq()[f.ind_low:f.ind_high],
                      sort_order='ascending')
     self.synth.enumerate()
     try:
         spectrum = self.Beamformer.integrate(sector)[f.ind_low:f.ind_high]
         spectrum = L_p(spectrum)
     except:
         spectrum = f.fftfreq()[f.ind_low:f.ind_high]
     pd.set_data("spectrum", spectrum)
示例#25
0
def create_gridded_scatter_plot(x,
                                y,
                                orientation="h",
                                color="red",
                                width=1.0,
                                fill_color="red",
                                marker="square",
                                marker_size=2,
                                value_mapper_class=LinearMapper,
                                padding=30):

    assert len(x) == len(y)

    # If you know it is monotonically increasing, sort_order can
    # be set to 'ascending'
    index = ArrayDataSource(x, sort_order='none')
    value = ArrayDataSource(y, sort_order="none")

    index_range = DataRange1D(tight_bounds=False)
    index_range.add(index)
    index_mapper = LinearMapper(range=index_range)

    value_range = DataRange1D(tight_bounds=False)
    value_range.add(value)
    value_mapper = value_mapper_class(range=value_range)

    plot = ScatterPlot(
        index=index,
        value=value,
        index_mapper=index_mapper,
        value_mapper=value_mapper,
        orientation=orientation,
        color=color,
        fill_color=fill_color,
        marker=marker,
        marker_size=marker_size,
        padding=[40, 15, 15, 20],  # left, right, top, bottom
        border_visible=True,
        border_width=1,
        bgcolor="white",
        use_backbuffer=True,
        backbuffer_padding=False,
        unified_draw=True,
        draw_layer="plot",
        overlay_border=True)

    vertical_grid = PlotGrid(component=plot,
                             mapper=index_mapper,
                             orientation='vertical',
                             line_color="gray",
                             line_style='dot',
                             use_draw_order=True)

    horizontal_grid = PlotGrid(component=plot,
                               mapper=value_mapper,
                               orientation='horizontal',
                               line_color="gray",
                               line_style='dot',
                               use_draw_order=True)

    vertical_axis = PlotAxis(orientation='left',
                             mapper=plot.value_mapper,
                             use_draw_order=True)

    horizontal_axis = PlotAxis(orientation='bottom',
                               title='Time (s)',
                               mapper=plot.index_mapper,
                               use_draw_order=True)

    plot.underlays.append(vertical_grid)
    plot.underlays.append(horizontal_grid)

    # Have to add axes to overlays because we are backbuffering the main plot,
    # and only overlays get to render in addition to the backbuffer.
    plot.overlays.append(vertical_axis)
    plot.overlays.append(horizontal_axis)
    return plot
示例#26
0
    def new_series(self, x=None, y=None, plotid=0, **kw):
        '''
        '''

        plot, scatter, _line = super(ResidualsGraph,
                                     self).new_series(x=x,
                                                      y=y,
                                                      plotid=plotid,
                                                      **kw)
        for underlay in plot.underlays:
            if underlay.orientation == 'bottom':
                underlay.visible = False
                underlay.padding_bottom = 0
        plot.padding_bottom = 0

        x, y, res = self.calc_residuals(plotid=plotid)

        ressplit = self._split_residual(x, res)
        resneg = ArrayDataSource(ressplit[1])
        xneg = ArrayDataSource(ressplit[0])
        respos = ArrayDataSource(ressplit[3])
        xpos = ArrayDataSource(ressplit[2])

        yrange = DataRange1D(ArrayDataSource(res))

        ymapper = LinearMapper(range=yrange)

        container = self._container_factory(type='o',
                                            padding=[50, 15, 0, 30],
                                            height=75,
                                            resizable='h')
        bar = BarPlot(
            index=xneg,
            value=resneg,
            index_mapper=scatter.index_mapper,
            value_mapper=ymapper,
            bar_width=0.2,
            line_color='blue',
            fill_color='blue',
            border_visible=True,
        )

        #        left_axis = PlotAxis(bar, orientation = 'left')
        # bottom_axis=PlotAxis(bar,orientaiton='bottom')

        kw = dict(vtitle='residuals')
        if self.xtitle:
            kw['htitle'] = self.xtitle
        add_default_axes(bar, **kw)
        hgrid = PlotGrid(mapper=ymapper,
                         component=bar,
                         orientation='horizontal',
                         line_color='lightgray',
                         line_style='dot')

        bar.underlays.append(hgrid)
        #        bar.underlays.append(left_axis)
        #        bar.underlays.append(bottom_axis)

        bar2 = BarPlot(
            index=xpos,
            value=respos,
            index_mapper=scatter.index_mapper,
            value_mapper=ymapper,
            bar_width=0.2,
            line_color='green',
            fill_color='green',
            # bgcolor = 'green',
            resizable='hv',
            border_visible=True,
            # padding = [30, 5, 0, 30]
        )
        bar2.overlays.append(GuideOverlay(bar2, value=0, color=(0, 0, 0)))
        bar2.underlays.append(hgrid)
        container.add(bar)
        container.add(bar2)

        # container.add(PlotLabel('foo'))

        self.residual_plots = [bar, bar2]
        self.plotcontainer.add(container)
def _create_plot_component():

    # Create the data and datasource objects
    numpoints = 500
    index = arange(numpoints)
    returns = random.lognormal(0.01, 0.1, size=numpoints)
    price = 100.0 * cumprod(returns)
    volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0)

    time_ds = ArrayDataSource(index)
    vol_ds = ArrayDataSource(volume, sort_order="none")
    price_ds = ArrayDataSource(price, sort_order="none")

    xmapper = LinearMapper(range=DataRange1D(time_ds))
    vol_mapper = LinearMapper(range=DataRange1D(vol_ds))
    price_mapper = LinearMapper(range=DataRange1D(price_ds))

    price_plot = FilledLinePlot(index=time_ds,
                                value=price_ds,
                                index_mapper=xmapper,
                                value_mapper=price_mapper,
                                edge_color="blue",
                                face_color="paleturquoise",
                                alpha=0.5,
                                bgcolor="white",
                                border_visible=True)
    add_default_grids(price_plot)
    price_plot.overlays.append(PlotAxis(price_plot, orientation='left'))
    price_plot.overlays.append(PlotAxis(price_plot, orientation='bottom'))
    price_plot.tools.append(
        PanTool(price_plot, constrain=True, constrain_direction="x"))
    price_plot.overlays.append(
        ZoomTool(price_plot,
                 drag_button="right",
                 always_on=True,
                 tool_mode="range",
                 axis="index"))

    vol_plot = BarPlot(index=time_ds,
                       value=vol_ds,
                       index_mapper=xmapper,
                       value_mapper=vol_mapper,
                       line_color="transparent",
                       fill_color="black",
                       bar_width=1.0,
                       bar_width_type="screen",
                       antialias=False,
                       height=100,
                       resizable="h",
                       bgcolor="white",
                       border_visible=True)

    add_default_grids(vol_plot)
    vol_plot.underlays.append(PlotAxis(vol_plot, orientation='left'))
    vol_plot.tools.append(
        PanTool(vol_plot, constrain=True, constrain_direction="x"))

    container = VPlotContainer(bgcolor="lightblue",
                               spacing=20,
                               padding=50,
                               fill_padding=False)
    container.add(vol_plot)
    container.add(price_plot)
    container.overlays.append(
        PlotLabel(
            "Financial Plot",
            component=container,
            #font="Times New Roman 24"))
            font="Arial 24"))
    return container
示例#28
0
 def _color_ds_default(self):
     return ArrayDataSource(self.dataframe[self.column].view(numpy.ndarray))
示例#29
0
    def _data_columns_default(self):
        return list(self.dataframe.columns[1:][::-1])


if __name__ == "__main__":
    populations = pandas.read_csv('state_populations.csv')

    from mapping.enable.geojson_overlay import process_raw
    polys = process_raw(file("states.geojs").read().replace('\r\n', ''))
    # generate compiled paths from polys
    paths = []
    coords = numpy.zeros((len(polys), 2))
    for poly, coord in zip(polys, coords):
        path = CompiledPath()
        total = numpy.sum((numpy.sum(p, axis=0) for p in poly), axis=0)
        coord[:] = total / sum(map(len, poly))
        for p in poly:
            path.lines(p - coord)  # recenter on origin
        paths.append(path)

    with enaml.imports():
        from choropleth_view import MapView

    view = MapView(model=Demo(title="State population from 1900 to 2010",
                              index_ds=ArrayDataSource(coords[:, 0]),
                              value_ds=ArrayDataSource(coords[:, 1]),
                              paths=paths,
                              dataframe=populations), )

    view.show()
示例#30
0
    def __init__(self, smaps, *args, **kwargs):
        super(MyPlot, self).__init__(*args, **kwargs)

        indexdata = []
        startdata = []
        stopdata = []

        lastval = 0
        for mem in smaps:
            if mem.size != 0:
                print mem.canread, mem.canwrite
                indexdata.append(mem.canread << 0 | mem.canwrite << 1
                                 | mem.isprivate << 2)
                startdata.append(lastval)
                stopdata.append(lastval + mem.size)
                lastval += mem.size
                print mem.size

        indexsrc = ArrayDataSource(data=indexdata)
        startsrc = ArrayDataSource(data=startdata)
        stopsrc = ArrayDataSource(data=stopdata)

        idxrange = [min(indexdata), max(indexdata)]
        valrange = [min(startdata), max(stopdata)]

        indexmapper = LinearMapper(
            range=DataRange1D(ArrayDataSource(idxrange)))
        valuemapper = LinearMapper(
            range=DataRange1D(ArrayDataSource(valrange)))

        barlist = []
        barlist.append(
            self.drawBar(indexsrc, indexmapper, startsrc, valuemapper,
                         0xc09090, stopsrc))
        #barlist.append(self.drawBar(indexsrc, indexmapper, rsssrc, valuemapper, 0xffa0a0))
        #barlist.append(self.drawBar(idxs, indexmapper, start, valuemapper, 0x0000ff, stop))

        bottom_axis = PlotAxis(barlist[0],
                               orientation='bottom',
                               tick_label_formatter=lambda x: str(x))
        barlist[0].underlays.append(bottom_axis)

        modelist = []
        for i in range(8):
            mstr = ""
            mstr += ['r', '-'][i & 1 == 0]
            mstr += ['w', '-'][i & 2 == 0]
            mstr += ['p', 's'][i & 4 == 0]
            modelist.append(mstr)

        vaxis1 = LabelAxis(barlist[0],
                           orientation='left',
                           title="Mode",
                           positions=range(len(modelist)),
                           labels=modelist,
                           tick_interval=1)
        #vaxis2 = LabelAxis(barlist[0], orientation='right',
        #                           title="Map Name",
        #                           positions = range(idx),
        #                           labels=["%s" % os.path.basename(x) for x in namedata])
        barlist[0].underlays.append(vaxis1)
        #barlist[0].underlays.append(vaxis2)
        barlist[0].tools.append(ZoomTool(barlist[0]))
        barlist[0].tools.append(PanTool(barlist[0]))

        #add_default_axes(plot, orientation = 'v')
        add_default_grids(barlist[0], orientation='v')

        container = OverlayPlotContainer(bgcolor="white")
        for p in barlist:
            p.padding = [200, 200, 20, 30]
            p.bgcolor = "white"
            container.add(p)

        self.plot = container