def __init__(self):
        # The delegates views don't work unless we caller the superclass __init__
        super(CursorTest, self).__init__()

        container = HPlotContainer(padding=0, spacing=20)
        self.plot = container
        # a subcontainer for the first plot.
        # I'm not sure why this is required. Without it, the layout doesn't work right.
        subcontainer = OverlayPlotContainer(padding=40)
        container.add(subcontainer)

        # make some data
        index = numpy.linspace(-10, 10, 512)
        value = numpy.sin(index)

        # create a LinePlot instance and add it to the subcontainer
        line = create_line_plot([index, value], add_grid=True, add_axis=True, index_sort="ascending", orientation="h")
        subcontainer.add(line)

        # here's our first cursor.
        csr = CursorTool(line, drag_button="left", color="blue")
        self.cursor1 = csr
        # and set it's initial position (in data-space units)
        csr.current_position = 0.0, 0.0

        # this is a rendered component so it goes in the overlays list
        line.overlays.append(csr)

        # some other standard tools
        line.tools.append(PanTool(line, drag_button="right"))
        line.overlays.append(ZoomTool(line))

        # make some 2D data for a colourmap plot
        xy_range = (-5, 5)
        x = numpy.linspace(xy_range[0], xy_range[1], 100)
        y = numpy.linspace(xy_range[0], xy_range[1], 100)
        X, Y = numpy.meshgrid(x, y)
        Z = numpy.sin(X) * numpy.arctan2(Y, X)

        # easiest way to get a CMapImagePlot is to use the Plot class
        ds = ArrayPlotData()
        ds.set_data("img", Z)

        img = Plot(ds, padding=40)
        cmapImgPlot = img.img_plot("img", xbounds=xy_range, ybounds=xy_range, colormap=jet)[0]

        container.add(img)

        # now make another cursor
        csr2 = CursorTool(cmapImgPlot, drag_button="left", color="white", line_width=2.0)
        self.cursor2 = csr2

        csr2.current_position = 1.0, 1.5

        cmapImgPlot.overlays.append(csr2)

        # add some standard tools. Note, I'm assigning the PanTool to the
        # right mouse-button to avoid conflicting with the cursors
        cmapImgPlot.tools.append(PanTool(cmapImgPlot, drag_button="right"))
        cmapImgPlot.overlays.append(ZoomTool(cmapImgPlot))
Exemple #2
0
    def setUp(self):
        if 'OUTPUT_TESTS' not in os.environ:
            raise SkipTest('Slow: define OUTPUT_TESTS to run')
        self.data = xye.XYEDataset.from_file(
            r'tests/testdata/si640c_low_temp_cal_p1_scan0.000000_adv0_0000.xye'
        )

        class UI(object):
            color = None
            name = ''
            active = True
            markers = False

        self.data.metadata['ui'] = UI()
        self.datasets = [self.data]
        self.plot = RawDataPlot(self.datasets)
        self.plot.plot_datasets(self.datasets, scale='log')
        self.container = OverlayPlotContainer(self.plot.get_plot(),
                                              bgcolor="white",
                                              use_backbuffer=True,
                                              border_visible=False)
        self.container.request_redraw()
        self.basedir = os.path.join('tests', 'tmp')
        try:
            os.mkdir(self.basedir)
        except OSError, e:
            assert 'exists' in str(e)
 def test_basics(self):
     container = OverlayPlotContainer(resizable='', bounds=[100.0,200.0])
     self.assert_tuple(container.get_preferred_size(), (100.0,200.0))
     self.assertEqual(container._layout_needed, True)
     container.do_layout()
     self.assertEqual(container._layout_needed, False)
     return
Exemple #4
0
class LegendWindow(HasTraits):
    
    plot = Instance(OverlayPlotContainer)
       
    traits_view = View(
                       UItem('plot', editor=ComponentEditor(bgcolor='white',
                       width=500, height=500), show_label=False, resizable=True),
                        title='Legend', scrollable=True,
               )
    
    def __init__(self,legend):
        super(LegendWindow,self).__init__()
        self.legend = self.add_legend(legend)
 
    def _plot_default(self):      
        self.container = OverlayPlotContainer(bgcolor="white", padding=10)
        self.container.add(self.legend)
        return self.container
         
    def get_legend(self):
        if self.legend:
            return self.legend
         
    def add_legend(self, legend):
        legend.set(component=None,
                                  padding=10,
                                  error_icon='blank',
                                  visible=True,
                                  resizable='hv',
                                 clip_to_component=True)
        return legend
Exemple #5
0
    def _create_window(self):
        numpoints = 50
        low = -5
        high = 15.0
        x = arange(low, high, (high-low)/numpoints)
        container = OverlayPlotContainer(bgcolor="lightgray")

        common_index = None
        index_range = None
        value_range = None
        self.animated_plots = []
        for i, color in enumerate(COLOR_PALETTE):
            if not common_index:
                animated_plot = AnimatedPlot(x, jn(i,x), color)
                common_index = animated_plot.plot.index
                index_range = animated_plot.plot.index_mapper.range
                value_range = animated_plot.plot.value_mapper.range
            else:
                animated_plot = AnimatedPlot(common_index, jn(i,x), color)
                animated_plot.plot.index_mapper.range = index_range
                animated_plot.plot.value_mapper.range = value_range
            container.add(animated_plot.plot)
            self.animated_plots.append(animated_plot)

        for i, a_plot in enumerate(self.animated_plots):
            a_plot.plot.position = [50 + (i%3)*(PLOT_SIZE+50),
                                    50 + (i//3)*(PLOT_SIZE+50)]

        self.timer = Timer(100.0, self.onTimer)
        self.container = container
        return Window(self, -1, component=container)
Exemple #6
0
    def init(self, parent):
        factory = self.factory
        container = OverlayPlotContainer(bgcolor='transparent',
                                         padding=0, spacing=0)

        window = Window(parent, component=container)

        interval = self.high - self.low
        data = ([self.low, self.high], [0.5]*2)
        plot = create_line_plot(data, color='black', bgcolor="sys_window")
        plot.x_mapper.range.low = self.low - interval*0.1
        plot.x_mapper.range.high = self.high + interval*0.1
        plot.y_mapper.range.high = 1.0
        plot.y_mapper.range.low = 0.0

        range_selection = RangeSelection(plot, left_button_selects=True)
        # Do not allow the user to reset the range
        range_selection.event_state = "selected"
        range_selection.deselect = lambda x: None
        range_selection.on_trait_change(self.update_interval, 'selection')

        plot.tools.append(range_selection)
        plot.overlays.append(RangeKnobsOverlay(plot))
        self.plot = plot
        container.add(self.plot)

        # To set the low and high, we're actually going to set the
        # 'selection' metadata on the line plot to the tuple (low,high).
        plot.index.metadata["selections"] = (0, 1.0)

        # Tell the editor what to display
        self.control = window.control
        self.control.SetSize((factory.width, factory.height))
    def _ml_plot_default(self):
        container = OverlayPlotContainer(padding=CHACO_AXES_PADDING)
        index_range = DataRange1D()
        value_range = DataRange1D(low=0, high=1)
        index_mapper = LinearMapper(range=index_range)
        value_mapper = LinearMapper(range=value_range)
        
        # Add the datasources so the psychometric function derived from the
        # maximum likelihood estimator is always shown across the full range
        # of tested values
        for sources in self.ml_track_data:
            index_range.add(sources[1])

        # Create the datasources for the psychometric function
        self.ml_index = FunctionDataSource(data_range=index_range, func=_xfunc)
        self.ml_value.data_range = index_range
        line = LinePlot(index=self.ml_index, value=self.ml_value,
                        index_mapper=index_mapper, value_mapper=value_mapper)
        ax = PlotAxis(line, orientation='left', title='Yes probability')
        line.overlays.append(ax)
        ax = PlotAxis(line, orientation='bottom', title='Parameter')
        line.overlays.append(ax)
        container.add(line)
        
        #line.tools.append(PanTool(line, constrain=True, constrain_key=None,
        #                          constrain_direction='x'))
        line.overlays.append(ZoomTool(line, axis='index', tool_mode='range'))
        return container
Exemple #8
0
def _create_plot_component():

    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)

    # Create the initial X-series of data
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high+0.001, (high-low)/numpoints)

    # Plot some bessel functions
    plots = {}
    broadcaster = BroadcasterTool()
    for i in range(4):
        y = jn(i, x)
        plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[i]), width=2.0)
        plot.index.sort_order = "ascending"
        plot.bgcolor = "white"
        plot.border_visible = True
        if i == 0:
            add_default_grids(plot)
            add_default_axes(plot)

        # Create a pan tool and give it a reference to the plot it should
        # manipulate, but don't attach it to the plot.  Instead, attach it to
        # the broadcaster.
        pan = PanTool(plot)
        broadcaster.tools.append(pan)

        container.add(plot)
        plots["Bessel j_%d"%i] = plot

    # Add an axis on the right-hand side that corresponds to the second plot.
    # Note that it uses plot.value_mapper instead of plot0.value_mapper.
    plot1 = plots["Bessel j_1"]
    axis = PlotAxis(plot1, orientation="right")
    plot1.underlays.append(axis)

    # Add the broadcast tool to the container, instead of to an
    # individual plot
    container.tools.append(broadcaster)

    legend = Legend(component=container, padding=10, align="ur")
    legend.tools.append(LegendTool(legend, drag_button="right"))
    container.overlays.append(legend)

    # Set the list of plots on the legend
    legend.plots = plots

    # Add the title at the top
    container.overlays.append(PlotLabel("Bessel functions",
                              component=container,
                              font = "swiss 16",
                              overlay_position="top"))

    # Add the traits inspector tool to the container
    container.tools.append(TraitsTool(container))

    return container
Exemple #9
0
    def _plot_default(self):
        container = OverlayPlotContainer(bgcolor="white")
        plots = self._make_curves()
        for plot in plots:
            plot.padding = 60
            container.add(plot)

        bottom_axis = PlotAxis(plot, orientation='bottom')

        label_list = [
            'var a', 'var b', 'var c', 'var d', 'var e', 'var f', 'var g',
            'var h', 'var i'
        ]
        vertical_axis = LabelAxis(plot,
                                  orientation='left',
                                  title='Categories',
                                  positions=list(range(1, 10)),
                                  labels=label_list)
        vertical2_axis = LabelAxis(plot,
                                   orientation='right',
                                   positions=list(range(1, 10)),
                                   labels=label_list)

        plot.underlays.append(vertical_axis)
        plot.underlays.append(vertical2_axis)
        plot.underlays.append(bottom_axis)

        return container
 def draw(self, gc, *args, **kw):
     with gc:
         w2 = self.width / 2
         h2 = self.height / 2
         gc.translate_ctm(w2, h2)
         gc.rotate_ctm(math.radians(self.rotation))
         gc.translate_ctm(-w2, -h2 - 100)
         OverlayPlotContainer.draw(self, gc, *args, **kw)
 def test_min_size(self):
     container = OverlayPlotContainer(resizable='', bounds=[50.0,50.0])
     component = PlotComponent(resizable='', position=[50.0,60.0],
                               bounds=[100.0, 110.0])
     container.add(component)
     container.do_layout()
     self.assert_tuple(component.position, (50.0,60.0))
     self.assert_tuple(component.bounds, (100.0,110.0))
     return
Exemple #12
0
    def _plot_default(self):

        container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                         bgcolor = "lightgray", use_backbuffer=True)

        # Create the initial X-series of data
        numpoints = self.numpoints
        low = self.low
        high = self.high
        x = arange(low, high+0.001, (high-low)/numpoints)
        y = jn(0, x)
        plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[0]), width=2.0)
        plot.index.sort_order = "ascending"
        plot.bgcolor = "white"
        plot.border_visible = True
        add_default_grids(plot)
        add_default_axes(plot)

        # Add some tools
        plot.tools.append(PanTool(plot))
        zoom = ZoomTool(plot, tool_mode="box", always_on=False)
        plot.overlays.append(zoom)

        # Add a dynamic label.  This can be dragged and moved around using the
        # right mouse button.  Note the use of padding to offset the label
        # from its data point.
        label = DataLabel(component=plot, data_point=(x[40], y[40]),
                          label_position="top left", padding=40,
                          bgcolor = "lightgray",
                          border_visible=False)
        plot.overlays.append(label)
        tool = DataLabelTool(label, drag_button="right", auto_arrow_root=True)
        label.tools.append(tool)

        # Add some static labels.
        label2 = DataLabel(component=plot, data_point=(x[20], y[20]),
                           label_position="bottom right",
                           border_visible=False,
                           bgcolor="transparent",
                           marker_color="blue",
                           marker_line_color="transparent",
                           marker = "diamond",
                           arrow_visible=False)
        plot.overlays.append(label2)

        label3 = DataLabel(component=plot, data_point=(x[80], y[80]),
                           label_position="top", padding_bottom=20,
                           marker_color="transparent",
                           marker_size=8,
                           marker="circle",
                           arrow_visible=False)
        plot.overlays.append(label3)
        container.add(plot)

        return container
Exemple #13
0
    def __init__(self, sensors = std_sensors.offset_str):
      m = MapPlot(map = themap, logger = logger)
      self.map_scale = themap.scale
      self.map_info = "%s" % themap

      self.noise_sensor = std_sensors.ultra_noise
      self.noise_move = noise_params['move']
      self.noise_turn = noise_params['turn']

      #start_pose = Pose(themap.x_inches/2, themap.y_inches/2, 0.0)
      start_pose = Pose(4, 7.75, 0.0)
      robot = SimRobot(start_pose, sensors, noise_params = noise_params)
      rplotter = RobotPlotter(robot = robot, xsize = themap.x_inches, ysize = themap.y_inches)

      localizer = ParticleLocalizer(sensors, noise_params, themap, particle_count, start_pose, logger = logger)
      pplotter = ParticlePlotter(particles = localizer.p, xsize = themap.x_inches, ysize = themap.y_inches, color = 'red')

      guessbot = Robot(start_pose)
      guessplotter = RobotPlotter(robot = guessbot, xsize = themap.x_inches, ysize = themap.y_inches, color = 'green' )

      c = OverlayPlotContainer()
      c.add(m.plot)
      c.add(pplotter.qplot)
      c.add(guessplotter.plot)
      c.add(rplotter.plot)

      self.container = c
      self.mapplot = m
      self.pplotter = pplotter
      self.rplotter = rplotter
      self.guessplotter = guessplotter

      self.localizer = localizer
def _create_plot_component(max_pop, index_ds, value_ds, color_ds, paths):

    tile_cache = HTTPTileManager(min_level=2, max_level=4,
                                 server='tile.cloudmade.com',
                                 url='/1a1b06b230af4efdbb989ea99e9841af/20760/256/%(zoom)d/%(col)d/%(row)d.png')  # noqa

    color_range = DataRange1D(color_ds, low_setting=0)

    choro = ChoroplethPlot(
              index=index_ds,
              value=value_ds,
              color_data=color_ds,
              index_mapper=LinearMapper(range=DataRange1D(index_ds)),
              value_mapper=LinearMapper(range=DataRange1D(value_ds)),
              color_mapper=colormap(range=color_range),
              outline_color='white',
              line_width=1.5,
              fill_alpha=1.,
              compiled_paths=paths,

              tile_cache=tile_cache,
              zoom_level=3,
              )

    container = OverlayPlotContainer(
        bgcolor='sys_window', padding=50, fill_padding=False,
        border_visible=True,
    )
    container.add(choro)

    for dir in ['left']:
        axis = PlotAxis(tick_label_formatter=convert_lat,
                        mapper=choro.value_mapper, component=container,
                        orientation=dir)
        container.overlays.append(axis)
    for dir in ['top', 'bottom']:
        axis = PlotAxis(tick_label_formatter=convert_lon,
                        mapper=choro.index_mapper, component=container,
                        orientation=dir)
        container.overlays.append(axis)

    choro.tools.append(PanTool(choro))
    choro.tools.append(ZoomTool(choro))

    colorbar = create_colorbar(choro)
    colorbar.padding_top = container.padding_top
    colorbar.padding_bottom = container.padding_bottom

    plt = HPlotContainer(use_backbuffer=True)
    plt.add(container)
    plt.add(colorbar)
    plt.bgcolor = "sys_window"

    return plt
Exemple #15
0
def _create_plot_component():

    # Create some x-y data series to plot
    plot_area = OverlayPlotContainer(border_visible=True)
    container = HPlotContainer(padding=50, bgcolor="transparent")
    #container.spacing = 15

    x = linspace(-2.0, 10.0, 100)
    for i in range(5):
        color = tuple(COLOR_PALETTE[i])
        y = jn(i, x)
        renderer = create_line_plot((x, y), color=color)
        plot_area.add(renderer)
        #plot_area.padding_left = 20

        axis = PlotAxis(orientation="left", resizable="v",
                    mapper = renderer.y_mapper,
                    axis_line_color=color,
                    tick_color=color,
                    tick_label_color=color,
                    title_color=color,
                    bgcolor="transparent",
                    title = "jn_%d" % i,
                    border_visible = True,)
        axis.bounds = [60,0]
        axis.padding_left = 10
        axis.padding_right = 10

        container.add(axis)

        if i == 4:
            # Use the last plot's X mapper to create an X axis and a
            # vertical grid
            x_axis = PlotAxis(orientation="bottom", component=renderer,
                        mapper=renderer.x_mapper)
            renderer.overlays.append(x_axis)
            grid = PlotGrid(mapper=renderer.x_mapper, orientation="vertical",
                    line_color="lightgray", line_style="dot")
            renderer.underlays.append(grid)

    # Add the plot_area to the horizontal container
    container.add(plot_area)

    # Attach some tools to the plot
    broadcaster = BroadcasterTool()
    for plot in plot_area.components:
        broadcaster.tools.append(PanTool(plot))

    # Attach the broadcaster to one of the plots.  The choice of which
    # plot doesn't really matter, as long as one of them has a reference
    # to the tool and will hand events to it.
    plot.tools.append(broadcaster)

    return container
Exemple #16
0
def gen_line_plot(series_one, series_two, y_axis_name=''):
    """
    Parameters
    ----------
    series_one : nd array
    series_two : nd array

    """

    size = min(series_one.shape[0],
        series_two.shape[0])

    idx = ArrayDataSource(arange(size))

    series_one_data = ArrayDataSource(series_one[:size])
    series_two_data = ArrayDataSource(series_two[:size])

    y_range = DataRange1D(series_one_data)
    y_range.tight_bounds = False
    y_range.margin = 50
    x_mapper = LinearMapper(range=DataRange1D(idx))
    y_mapper = LinearMapper(range=y_range)

    series_one_plot = LinePlot(index=idx,
        value=series_one_data, index_mapper=x_mapper,
        value_mapper=y_mapper, color='blue')

    series_two_plot = LinePlot(index=idx,
        value=series_two_data, index_mapper=x_mapper,
        value_mapper=y_mapper, color='red')

    container = OverlayPlotContainer(bgcolor='white',
        padding=25, fill_padding=False, border_visible=True)

    y_axis = PlotAxis(mapper=y_mapper, component=container,
        orientation='left')

    x_axis = PlotAxis(mapper=x_mapper, component=container,
        orientation='bottom')

    x_axis.title = 'Time'
    y_axis.title = y_axis_name

    legend = Legend(component=container, padding=10, align='ur')
    legend.plots = {
        'Predicted': series_one_plot,
        'Actual': series_two_plot,
    }

    container.add(series_one_plot)
    container.add(series_two_plot)
    container.overlays.append(y_axis)
    container.overlays.append(legend)
    return container
Exemple #17
0
class Graph(HasTraits):
    plot=None
    traits_view=View(Item('plot',editor=ComponentEditor(bgcolor="white"), show_label=False),
                     width=1200, height=1024, resizable=True, title="BacLog")
    
    def __init__(self):
        super(Graph,self).__init__()
        self.container = HPlotContainer(padding=20, bgcolor="transparent")
        self.plot_area = OverlayPlotContainer(border_visible=True)

    def add(self,series,limit=None):
        
        broadcaster = BroadcasterTool()
        
        for name,line in series._plot.line.items():
            if limit is not None and name not in limit:
                continue
            if line.time==[]:
                print "Graph.add> empty:", name
                continue
            plot=create_line_plot((seconds(line.time),line.data),color=line.color)
            self.plot_area.add(plot)

            axis = PlotAxis(orientation="left", resizable="v",
                            mapper = plot.y_mapper,
                            bgcolor="white",
                            title = name,
                            title_color = line.color,
                            title_spacing = -4.0,
                            border_visible = True,)
            ## Visual style
            axis.bounds = [60,0]
            axis.padding_left = 1
            axis.padding_right = 1
            self.container.add(axis)

            ## Tools (attach to all for now)
            plot.tools.append(broadcaster)
            broadcaster.tools.append(PanTool(plot))
            broadcaster.tools.append(DragZoom(plot,maintain_aspect_ratio=False,drag_button='right',restrict_domain=True))

        
    def run(self):

        ## Time axis (first one)
        plot=self.plot_area.components[0]
        time = PlotAxis(orientation="bottom", component=plot, mapper=plot.x_mapper)
        plot.overlays.append(time)

        ## Plot
        self.container.add(self.plot_area)
        self.plot=self.container

        self.configure_traits()
Exemple #18
0
    def create_container(self, plugin):
        index_range = ChannelDataRange(trig_delay=self.trig_delay, span=self.span)
        index_mapper = LinearMapper(range=index_range)
        container = OverlayPlotContainer(padding=[20, 20, 50, 50])
        for child in self.children:
            plot = child.create_plot(plugin, index_mapper)
            container.add(plot)

        # Add the time axis to the final plot
        add_time_axis(plot)
        add_default_grids(plot, major_index=5, minor_index=1)
        return container
  def __init__(self, link):
    super(TrackingView, self).__init__()

    self.link = link
    self.link.add_callback(MSG_TRACKING_SNRS, self.tracking_snrs_callback)

    # ======= Line Plot =======

    self.plot_data = ArrayPlotData(t=[0.0])
    self.plot = Plot(self.plot_data, auto_colors=colours_list)
    self.plot.value_range.tight_bounds = False
    self.plot.value_range.low_setting = 0.0
    for n in range(TRACK_N_CHANNELS):
      self.plot_data.set_data('ch'+str(n), [0.0])
      self.plot.plot(('t', 'ch'+str(n)), type='line', color='auto')

    # ======= Bar Plot =======

    idxs = ArrayDataSource(range(1, len(self.snrs)+1))
    self.vals = ArrayDataSource(self.snrs, sort_order='none')
    # Create the index range
    index_range = DataRange1D(idxs, low=0.4, high=TRACK_N_CHANNELS+0.6)
    index_mapper = LinearMapper(range=index_range)
    # Create the value range
    value_range = DataRange1D(low=0.0, high=25.0)
    value_mapper = LinearMapper(range=value_range)

    plot = BarPlot(index=idxs, value=self.vals, 
                   index_mapper=index_mapper, value_mapper=value_mapper, 
                   line_color='blue', fill_color='blue', bar_width=0.8)

    container = OverlayPlotContainer(bgcolor = "white")
    plot.padding = 10
    plot.padding_left = 30
    plot.padding_bottom = 30
    container.add(plot)

    left_axis = PlotAxis(plot, orientation='left')
    bottom_axis = LabelAxis(plot, orientation='bottom',
                           labels = map(str, range(1, TRACK_N_CHANNELS+1)),
                           positions = range(1, TRACK_N_CHANNELS+1),
                           small_haxis_style=True)

    plot.underlays.append(left_axis)
    plot.underlays.append(bottom_axis)

    self.snr_bars = container

    self.python_console_cmds = {
      'track': self
    }
Exemple #20
0
def _create_plot_component_overlay(signals, use_downsampling=False):

    container = OverlayPlotContainer(padding=40,
                                     bgcolor="lightgray",
                                     use_backbuffer=True,
                                     border_visible=True,
                                     fill_padding=True)

    nSignal, nSample = np.shape(signals)
    time = arange(nSample)

    value_mapper = None
    index_mapper = None
    plots = {}
    for i in range(nSignal):

        plot = create_line_plot(
            (time, signals[i]),
            color=tuple(COLOR_PALETTE[i % len(COLOR_PALETTE)]),
            width=2.0)
        plot.use_downsampling = use_downsampling

        if value_mapper is None:
            index_mapper = plot.index_mapper
            value_mapper = plot.value_mapper
            add_default_grids(plot)
            add_default_axes(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i % 2 == 1:
            plot.line_style = "dash"
        plot.bgcolor = "white"
        plots["Corr fun %d" % i] = plot
        container.add(plot)

    # Add a legend in the upper right corner, and make it relocatable
    #    legend = Legend(component=plot, padding=10, align="ur")
    #    legend.tools.append(LegendTool(legend, drag_button="right"))
    #    plot.overlays.append(legend)
    #    legend.plots = plots
    #    selection_overlay = RangeSelectionOverlay(component=plot)
    #    plot.tools.append(RangeSelection(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    # plot.overlays.append(selection_overlay)
    plot.overlays.append(zoom)

    return container
Exemple #21
0
def main():
    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 100)
    pd = ArrayPlotData(index = x)
    for i in range(5):
        pd.set_data("y" + str(i), jn(i,x))

    # Create some line plots of some of the data
    plot = Plot(pd, bgcolor="none", padding=30, border_visible=True,
                 overlay_border=True, use_backbuffer=False)
    plot.legend.visible = True
    plot.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="auto")
    plot.plot(("index", "y3"), name="j_3", color="auto")
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    # Create the mlab test mesh and get references to various parts of the
    # VTK pipeline
    f = mlab.figure(size=(600,500))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    plot.resizable = ""
    plot.bounds = [200,200]
    plot.padding = 25
    plot.bgcolor = "lightgray"
    plot.outer_position = [30,30]
    plot.tools.append(MoveTool(component=plot,drag_button="right"))

    container = OverlayPlotContainer(bgcolor = "transparent",
                    fit_window = True)
    container.add(plot)

    # Create the Enable Window
    window = EnableVTKWindow(rwi, renderer,
            component=container,
            #istyle_class = tvtk.InteractorStyleSwitch,
            #istyle_class = tvtk.InteractorStyle,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )

    mlab.show()
    return window, render_window
Exemple #22
0
class HistogramPlotHandler(HasTraits):
    """
    Class for handling the histograms.
    """

    # Index for the histogram plot
    index = Array

    # The selection handler object for the selected data
    selection_handler = Instance(SelectionHandler)

    # OVerlayPlotContainer for the histogram plot
    container = Instance(OverlayPlotContainer)

    # Number of bins of the histogram
    nbins = Int(10)

    # Whether the data is a pandas dataframe or a numpy array
    AS_PANDAS_DATAFRAME = Bool

    def __init__(self):
        self.index = range(self.nbins)
        self.selection_handler = SelectionHandler()
        self.container = OverlayPlotContainer()

    def draw_histogram(self):
        """
        Default function called when drawing the histogram.
        """
        for component in self.container.components:
            self.container.remove(component)

        self.selection_handler.create_selection()

        if len(self.selection_handler.selected_indices) == 1:
            tuple_list = self.selection_handler.selected_indices[0]
            if self.AS_PANDAS_DATAFRAME:
                column_name = self.data.columns[tuple_list[1]]
                y = self.data[column_name]
                self.index = np.arange(self.nbins)
                hist = np.histogram(y, self.nbins)[0]
                plotdata = ArrayPlotData(x=self.index, y=hist)
                plot = Plot(plotdata)
                plot.plot(("x", "y"), type="bar", bar_width=0.5)
                self.container.add(plot)
            else:
                column = tuple_list[1]
                y = self.data[:, column]
                self.index = np.arange(self.nbins)
                hist = np.histogram(y, self.nbins)[0]
                plotdata = ArrayPlotData(x=self.index, y=hist)
                plot = Plot(plotdata)
                plot.plot(("x", "y"), type="bar", bar_width=0.5)
                self.container.add(plot)

            self.container.request_redraw()

        self.selection_handler.flush()
Exemple #23
0
def _create_plot_component_overlay(signals, use_downsampling=False):

    container = OverlayPlotContainer(padding=40, bgcolor="lightgray",
                                     use_backbuffer=True,
                                     border_visible=True,
                                     fill_padding=True)

    nSignal, nSample = np.shape(signals)
    time = arange(nSample)

    value_mapper = None
    index_mapper = None
    plots = {}
    for i in range(nSignal):

        plot = create_line_plot((time, signals[i]),
                        color=tuple(COLOR_PALETTE[i % len(COLOR_PALETTE)]),
                        width=2.0)
        plot.use_downsampling = use_downsampling

        if value_mapper is None:
            index_mapper = plot.index_mapper
            value_mapper = plot.value_mapper
            add_default_grids(plot)
            add_default_axes(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i % 2 == 1:
            plot.line_style = "dash"
        plot.bgcolor = "white"
        plots["Corr fun %d" % i] = plot
        container.add(plot)

    # Add a legend in the upper right corner, and make it relocatable
    #    legend = Legend(component=plot, padding=10, align="ur")
    #    legend.tools.append(LegendTool(legend, drag_button="right"))
    #    plot.overlays.append(legend)
    #    legend.plots = plots
    #    selection_overlay = RangeSelectionOverlay(component=plot)
    #    plot.tools.append(RangeSelection(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    # plot.overlays.append(selection_overlay)
    plot.overlays.append(zoom)

    return container
Exemple #24
0
 def __init__(self):
     super(StackedPlot, self).__init__()
     self.container = OverlayPlotContainer(
         bgcolor="white", use_backbuffer=True, border_visible=True, padding=50, padding_left=110, fill_padding=True
     )
     self.data = ArrayPlotData()
     self.chaco_plot = None
     self.value_mapper = None
     self.index_mapper = None
     self.x_axis = PlotAxis(
         component=self.container,
         orientation="bottom",
         title=u"Angle (2\u0398)",
         title_font=settings.axis_title_font,
         tick_label_font=settings.tick_font,
     )
     y_axis_title = "Normalized intensity (%s)" % get_value_scale_label("linear")
     self.y_axis = PlotAxis(
         component=self.container,
         orientation="left",
         title=y_axis_title,
         title_font=settings.axis_title_font,
         tick_label_font=settings.tick_font,
     )
     self.container.overlays.extend([self.x_axis, self.y_axis])
     self.container.tools.append(TraitsTool(self.container, classes=[LinePlot, PlotAxis]))
     self.colors = []
     self.last_flip_order = self.flip_order
Exemple #25
0
def _create_plot_component():

    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)

    # Create the initial X-series of data
    numpoints = 30
    low = -5
    high = 15.0
    x = linspace(low, high, numpoints)
    y = jn(0, x)

    lineplot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[0]), width=2.0)
    lineplot.selected_color = "none"
    scatter = ScatterPlot(index = lineplot.index,
                       value = lineplot.value,
                       index_mapper = lineplot.index_mapper,
                       value_mapper = lineplot.value_mapper,
                       color = tuple(COLOR_PALETTE[0]),
                       marker_size = 5)
    scatter.index.sort_order = "ascending"

    scatter.bgcolor = "white"
    scatter.border_visible = True

    add_default_grids(scatter)
    add_default_axes(scatter)

    scatter.tools.append(PanTool(scatter, drag_button="right"))

    # The ZoomTool tool is stateful and allows drawing a zoom
    # box to select a zoom region.
    zoom = ZoomTool(scatter, tool_mode="box", always_on=False, drag_button=None)
    scatter.overlays.append(zoom)

    scatter.tools.append(PointDraggingTool(scatter))

    container.add(lineplot)
    container.add(scatter)

    # Add the title at the top
    container.overlays.append(PlotLabel("Line Editor",
                              component=container,
                              font = "swiss 16",
                              overlay_position="top"))

    return container
Exemple #26
0
 def __init__(self):
     self.selection_handler = SelectionHandler()
     self.container = OverlayPlotContainer()
     self.underlays = []
     self.add_pan_tool = False
     self.add_zoom_tool = False
     self.add_dragzoom = False
     self.show_grid = False
 def _ml_track_plot_default(self):
     container = OverlayPlotContainer(padding=CHACO_AXES_PADDING)
     index_range = DataRange1D()
     value_range = DataRange1D()
     index_mapper = LinearMapper(range=index_range)
     value_mapper = LinearMapper(range=value_range)
     
     for i, v, i_hit, v_hit, i_miss, v_miss in self.ml_track_data:
         index_range.add(i)
         value_range.add(v)
         kwargs = dict(index_mapper=index_mapper,
                       value_mapper=value_mapper)
         
         # The connecting line
         line = LinePlot(index=i, value=v, **kwargs)
         container.add(line)
         
         # Black for hit
         scatter = ScatterPlot(index=i_hit, value=v_hit, marker='circle',
                               color='black', **kwargs)
         container.add(scatter)
         
         # Red for miss
         scatter = ScatterPlot(index=i_miss, value=v_miss, marker='circle',
                               color='red', **kwargs)
         container.add(scatter)
         
     # Add the overlays to the last plot
     line.overlays.append(PlotAxis(line, orientation='left', title='Parameter'))
     line.overlays.append(PlotAxis(line, orientation='bottom', title='Trial number'))
     return container
Exemple #28
0
def _create_plot_component():
    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 100)
    pd = ArrayPlotData(index = x)
    for i in range(5):
        pd.set_data("y" + str(i), jn(i,x))

    # Create some line plots of some of the data
    plot1 = Plot(pd)
    plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")
    plot1.plot(("index", "y3"), name="j_3", color="blue")

    # Tweak some of the plot properties
    plot1.title = "Inset Plot"
    plot1.padding = 50

    # Attach some tools to the plot
    plot1.tools.append(PanTool(plot1))
    zoom = ZoomTool(component=plot1, tool_mode="box", always_on=False)
    plot1.overlays.append(zoom)

    # Create a second scatter plot of one of the datasets, linking its
    # range to the first plot
    plot2 = Plot(pd, range2d=plot1.range2d, padding=50)
    plot2.plot(('index', 'y3'), type="scatter", color="blue", marker="circle")
    plot2.set(resizable = "",
              bounds = [250, 250],
              position = [550,150],
              bgcolor = "white",
              border_visible = True,
              unified_draw = True
              )
    plot2.tools.append(PanTool(plot2))
    plot2.tools.append(MoveTool(plot2, drag_button="right"))
    zoom = ZoomTool(component=plot2, tool_mode="box", always_on=False)
    plot2.overlays.append(zoom)

    # Create a container and add our plots
    container = OverlayPlotContainer()
    container.add(plot1)
    container.add(plot2)
    return container
Exemple #29
0
class PCPlotHandler(HasTraits):
    """
    Class for handling principal component plots.
    """

    # The container for the plot.
    container = OverlayPlotContainer()

    # the sklearn.decmoposition.PCA object
    pca = PCA

    # Whether or not to normalize the data, one of the parameters of the PCA
    # object
    whiten = Bool

    # The input data.
    table = Array

    # The selection_handler instance for the tableview
    selection_handler = Instance(SelectionHandler)

    def __init__(self):
        self.pca = PCA(n_components=2)
        self.pca.whiten = True
        self.container = OverlayPlotContainer()
        self.selection_handler = SelectionHandler()

    def draw_pc_plot(self):
        """
        Called to draw the PCA plot.
        """
        self.selection_handler.create_selection()
        if len(self.selection_handler.selected_indices) == 1:
            top_left = self.selection_handler.selected_indices[0][0:2]
            bot_right = self.selection_handler.selected_indices[0][2:4]
            data = self.table[top_left[0] : bot_right[0], top_left[1] : bot_right[1]]
            pc_red = self.pca.fit_transform(data)
            plotdata = ArrayPlotData(x=pc_red[:, 0], y=pc_red[:, 1])
            plot = Plot(plotdata)
            plot.plot(("x", "y"), type="scatter")
            self.container.add(plot)
            self.container.request_redraw()
Exemple #30
0
def _create_plot_component(use_downsampling=False):

    container = OverlayPlotContainer(padding=40, bgcolor="lightgray",
                                     use_backbuffer = True,
                                     border_visible = True,
                                     fill_padding = True)

    numpoints = 100000
    low = -5
    high = 15.0
    x = arange(low, high+0.001, (high-low)/numpoints)

    # Plot some bessel functionsless ../en
    value_mapper = None
    index_mapper = None
    for i in range(1):
        y = jn(i, x)
        plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[i]), width=2.0)
        plot.use_downsampling = use_downsampling

        if value_mapper is None:
            index_mapper = plot.index_mapper
            value_mapper = plot.value_mapper
            add_default_grids(plot)
            add_default_axes(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i%2 == 1:
            plot.line_style = "dash"
        plot.bgcolor = "white"
        container.add(plot)

    selection_overlay = RangeSelectionOverlay(component = plot)
    plot.tools.append(RangeSelection(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    plot.overlays.append(selection_overlay)
    plot.overlays.append(zoom)

    return container
Exemple #31
0
def main():
    plot = create_plot()
    plot.bounds = [400,300]
    plot.outer_position = [30,30]
    plot.resizable = ""
    cmap_renderer = plot.plots["my_plot"][0]

    # Create the colorbar, handing in the appropriate range and colormap
    colorbar = create_colorbar(plot.color_mapper)
    colorbar.outer_position = [450,30]
    colorbar.plot = cmap_renderer
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

    container = OverlayPlotContainer(bgcolor = "transparent",
                    fit_window = True)
    container.add(plot)
    container.add(colorbar)

    start_vtk(container)
Exemple #32
0
def main():
    from tvtk.api import tvtk
    from mayavi import mlab
    from enable.vtk_backend.vtk_window import EnableVTKWindow
    f = mlab.figure(size=(900,850))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    # Create the plot
    timer_controller = TimerController()
    plots = create_plot_component(timer_controller)
    specplot, timeplot, spectrogram = plots

    for i, p in enumerate(plots):
        p.set(resizable = "", bounds = [200,200], outer_x = 0,
                bgcolor = "transparent",
                )
        p.outer_y = i*250
        p.tools.append(MoveTool(p, drag_button="right"))
        p.tools.append(PanTool(p))
        p.tools.append(ZoomTool(p))

    spectrogram.tools[-1].set(tool_mode="range", axis="value")
    spectrogram.tools[-2].set(constrain=True, constrain_direction="y")

    container = OverlayPlotContainer(bgcolor = "transparent",
                    fit_window = True)
    container.add(*plots)
    container.timer_callback = timer_controller.on_timer

    window = EnableVTKWindow(rwi, renderer,
            component = container,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )

    mlab.show()
Exemple #33
0
    def _plot_container_default(self):
        container = OverlayPlotContainer(padding=50,
                                         fill_padding=False,
                                         bgcolor="white",
                                         use_backbuffer=True)

        return container

        #---------------------------------------------------------------------
        #  Finishes initializing the editor by creating the underlying toolkit
        #  widget:
        #---------------------------------------------------------------------
        """ Finishes initializing the editor by creating the 
 def test_multiple_min_size(self):
     comp1 = StaticPlotComponent([200, 50])
     comp2 = StaticPlotComponent([60, 300])
     container = OverlayPlotContainer(resizable='hv', bounds=[30,30])
     container.fit_components = "hv"
     container.add(comp1, comp2)
     container.do_layout()
     self.assert_tuple(container.get_preferred_size(), (200,300))
     self.assert_tuple(comp1.bounds, (200,50))
     self.assert_tuple(comp2.bounds, (60,300))
     return
Exemple #35
0
 def __init__(self, *args, **kws):
     """
     self.datasets = [ <XYEDataset>, ..., <XYEDataset> ]
     self.dataset_pairs = set([ (<XYEDataset-p1>, <XYEDataset-p2>),
                                ...,
                                (<XYEDataset-p1>, <XYEDataset-p2>) ])
     """
     super(MainApp, self).__init__(*args, **kws)
     self.datasets = []
     self.dataset_pairs = set()
     self.undo_state = None
     self.raw_data_plot = RawDataPlot()
     self.plot = self.raw_data_plot.get_plot()
     self.container = OverlayPlotContainer(self.plot,
                                           bgcolor="white",
                                           use_backbuffer=True,
                                           border_visible=False)
     self.pan_tool = None
     # The list of all options.
     self._options = ['Show legend', 'Show gridlines', 'Show crosslines']
     # The list of currently set options, updated by the UI.
     self.options = self._options
     self.file_paths = []