Beispiel #1
0
    def _ts_data_changed(self):
        """ Dataset has changed: update the plot.
        ENH: add the possibility to pass a dict to ArrayPlotData.
        """
        print "data changed: updating the plot..."
        arr_data = ArrayPlotData()
        for k, v in self.ts_data.items():
            arr_data.set_data(k, v)
        self.ts_plot = ToolbarPlot(arr_data)
        for i, k in enumerate([k for k in self.ts_data.keys()
                               if k != "index"]):
            self.ts_plot.plot(("index", k),
                              name=k,
                              color=colors[i % len(colors)])
        if self.index_is_dates:
            # Index was an array of datetime: overwrite the x axis
            self.ts_plot.x_axis = None
            x_axis = PlotAxis(self.ts_plot,
                              orientation="bottom",
                              tick_generator=ScalesTickGenerator(
                                  scale=CalendarScaleSystem()))
            self.ts_plot.overlays.append(x_axis)
            self.ts_plot.x_grid.tick_generator = x_axis.tick_generator

        if self.data_file:
            self.ts_plot.title = "Time series visualization from %s" % self.data_file
        else:
            self.ts_plot.title = "Time series visualization"
        attach_tools(self.ts_plot)
Beispiel #2
0
    def update_main_plot(self):
        """ Build main plot
        """
        self.ts_plot = ToolbarPlot(self.arr_plot_data)
        for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]):
            renderer = self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)])[0]
        if self.index_is_dates:
            # Index was an array of datetime: overwrite the x axis
            self.ts_plot.x_axis = None
            x_axis = PlotAxis(self.ts_plot, orientation="bottom",
                              tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
            self.ts_plot.overlays.append(x_axis)
            self.ts_plot.x_grid.tick_generator = x_axis.tick_generator
            
        if self.data_file:
            self.ts_plot.title = ("Time series visualization from %s" 
                                  % (os.path.split(self.data_file)[1]))
        else:
            self.ts_plot.title = "Time series visualization"
        attach_tools(self.ts_plot)

        # Attach the range selection to the last renderer; any one will do
        self.ts_plot.tools.append(RangeSelection(renderer, left_button_selects = False,
            auto_handle_event = False))
        # Attach the corresponding overlay
        self._range_selection_overlay = RangeSelectionOverlay(renderer,
                                    metadata_name="selections")
        self.ts_plot.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed)
Beispiel #3
0
    def _plot_default(self):
        plot = Plot(self.dataset)
        plot.plot(('dates', self.data_provider.code), type='line')

        # Set the plot's bottom axis to use the Scales ticking system
        ticker = ScalesTickGenerator(scale=CalendarScaleSystem())
        plot.x_axis.tick_generator = ticker

        return plot
    def setup(self, x, y, ans):
        from pychron.pipeline.plot.plotter.ticks import tick_formatter, StaticTickGenerator, TICKS

        p = self.new_plot()
        p.padding_left = 60
        p.y_axis.tick_label_formatter = tick_formatter
        p.y_axis.tick_generator = StaticTickGenerator()
        p.y_axis.title = 'Analysis Type'

        # p.y_grid.line_style='solid'
        # p.y_grid.line_color='green'
        # p.y_grid.line_weight = 1.5

        self.set_y_limits(min_=-1, max_=len(TICKS))

        p.index_range.tight_bounds = False
        p.x_axis.tick_generator = ScalesTickGenerator(
            scale=CalendarScaleSystem())
        p.x_grid.tick_generator = p.x_axis.tick_generator
        p.x_axis.title = 'Time'

        scatter, _ = self.new_series(x,
                                     y,
                                     type='scatter',
                                     marker_size=1.5,
                                     selection_color='red',
                                     selection_marker='circle',
                                     selection_marker_size=2.5)

        broadcaster = BroadcasterTool()
        scatter.tools.append(broadcaster)

        point_inspector = AnalysisPointInspector(
            scatter,
            analyses=ans,
            value_format=get_analysis_type,
            additional_info=lambda i, x, y, ai:
            ('Time={}'.format(ai.rundate), 'Project={}'.format(ai.project)))

        pinspector_overlay = PointInspectorOverlay(component=scatter,
                                                   tool=point_inspector)

        rect_tool = RectSelectionTool(scatter)
        rect_overlay = RectSelectionOverlay(component=scatter, tool=rect_tool)

        broadcaster.tools.append(rect_tool)
        broadcaster.tools.append(point_inspector)

        # range_selector = RangeSelection(scatter, left_button_selects=True)
        # broadcaster.tools.append(range_selector)

        # scatter.overlays.append(RangeSelectionOverlay(component=scatter))
        scatter.overlays.append(pinspector_overlay)
        scatter.overlays.append(rect_overlay)

        self.scatter = scatter
Beispiel #5
0
    def _set_bottom_axis(self, plota, plot, plotid, timescale=False):
        # this is a hack to hide the default plotaxis
        # since a basexyplot's axis cannot be a ScalesPlotAxis (must be instance of PlotAxis)
        # we cant remove the default axis and set the x_axis to the scaled axis
        # also we cant remove the default axis because then we cant change the axis title
        title, title_font, tick_font = self._remove_bottom(plot)
        bottom = self.plotcontainer.stack_order == 'bottom_to_top'
        if bottom:
            if plotid == 0 or timescale:
                axis = ScalesPlotAxis(
                    plota,
                    orientation="bottom",
                    title=title,
                    title_font=title_font,
                    tick_label_font=tick_font,
                    tick_generator=ScalesTickGenerator(
                        scale=CalendarScaleSystem(
                            # *HMSScales
                        )
                        # scale = TimeScale()
                    ))

                plot.underlays.append(axis)
        else:
            for pi in self.plots:
                title = self._remove_bottom(pi)

            if (plotid == 0
                    and len(self.plots) == 1) or plotid == len(self.plots) - 1:
                axis = ScalesPlotAxis(
                    plota,
                    orientation="bottom",
                    title=title,
                    title_font=title_font,
                    tick_label_font=tick_font,
                    tick_generator=ScalesTickGenerator(
                        scale=CalendarScaleSystem(
                            # *HMSScales
                        )
                        # scale = TimeScale()
                    ))

                plot.underlays.append(axis)
Beispiel #6
0
 def _figure_drift_default(self):
     plot = Plot(self.plot_data_drift, width=70, height=40, padding=8, padding_left=64, padding_bottom=32)
     plot.plot(('t','x'), type='line', color='blue', name='x')
     plot.plot(('t','y'), type='line', color='red', name='y')
     plot.plot(('t','z'), type='line', color='green', name='z')
     bottom_axis = PlotAxis(plot,
                            orientation="bottom",
                            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
     plot.index_axis=bottom_axis
     plot.index_axis.title = 'time'
     plot.value_axis.title = 'drift [um]'
     plot.legend.visible=True
     return plot        
    def _plot_default(self):
        code = self.data_provider.code
        plot = Plot(self.dataset)
        plot.plot(('dates', code), type='line', color='blue', name=code)

        # Add tools
        plot.tools.append(ZoomTool(plot))
        plot.tools.append(PanTool(plot))

        # Set the plot's bottom axis to use the Scales ticking system
        ticker = ScalesTickGenerator(scale=CalendarScaleSystem())
        plot.x_axis.tick_generator = ticker

        return plot
Beispiel #8
0
    def _create_returns_plot(self):
        plot = Plot(self.plotdata)
        plot.legend.visible = True
        #FIXME: The legend move tool doesn't seem to quite work right now
        #plot.legend.tools.append(LegendTool(plot.legend))
        plot.x_axis = None
        x_axis = PlotAxis(
            plot,
            orientation="bottom",
            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        plot.overlays.append(x_axis)
        plot.x_grid.tick_generator = x_axis.tick_generator
        for i, name in enumerate(self.plotdata.list_data()):
            if name == "times":
                continue
            renderer = plot.plot(("times", name),
                                 type="line",
                                 name=name,
                                 color=tuple(COLOR_PALETTE[i]))[0]

        # Tricky: need to set auto_handle_event on the RangeSelection
        # so that it passes left-clicks to the PanTool
        # FIXME: The range selection is still getting the initial left down
        renderer.tools.append(
            RangeSelection(renderer,
                           left_button_selects=False,
                           auto_handle_event=False))
        plot.tools.append(
            PanTool(plot,
                    drag_button="left",
                    constrain=True,
                    constrain_direction="x",
                    restrict_to_data=True))
        plot.overlays.append(
            ZoomTool(plot,
                     tool_mode="range",
                     max_zoom_out=1.0,
                     x_min_zoom_factor=float(1e-3)))
        # Attach the range selection to the last renderer; any one will do
        self._range_selection_overlay = RangeSelectionOverlay(
            renderer, metadata_name="selections")
        renderer.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed,
                                      'metadata_changed')
        self.returns_plot = plot
    def _container_default(self):
        plot = Plot(self.dataset)
        plot.plot(('dates', self.data_provider.code), type='line')

        # Add tools
        plot.tools.append(ZoomTool(plot))
        plot.tools.append(PanTool(plot))

        # Set the plot's bottom axis to use the Scales ticking system
        ticker = ScalesTickGenerator(scale=CalendarScaleSystem())
        plot.x_axis.tick_generator = ticker

        container = VPlotContainer()
        container.add(plot)

        return container
Beispiel #10
0
    def _create_returns_plot(self):
        plot = Plot(self.plotdata)
        plot.legend.visible = False
        plot.x_axis = None
        x_axis = PlotAxis(
            plot,
            orientation="bottom",
            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        plot.overlays.append(x_axis)
        plot.x_grid.tick_generator = x_axis.tick_generator
        for i, name in enumerate(self.plotdata.list_data()):
            if name == "times":
                continue
            renderer = plot.plot(("times", name),
                                 type="line",
                                 name=name,
                                 color="auto",
                                 line_width=2)[0]
        self.times_ds = renderer.index
        print('chaco: %s') % str(time.time() - tic)

        # Tricky: need to set auto_handle_event on the RangeSelection
        # so that it passes left-clicks to the PanTool
        # FIXME: The range selection is still getting the initial left down
        renderer.tools.append(
            RangeSelection(renderer,
                           left_button_selects=False,
                           auto_handle_event=False))
        plot.tools.append(
            PanTool(plot,
                    drag_button="left",
                    constrain=True,
                    constrain_direction="x"))
        plot.overlays.append(
            ZoomTool(plot, tool_mode="range", max_zoom_out=1.0))
        # Attach the range selection to the last renderer; any one will do
        self._range_selection_overlay = RangeSelectionOverlay(
            renderer, metadata_name="selections")
        renderer.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed,
                                      'metadata_changed')

        self.returns_plot = plot
Beispiel #11
0
    def _create_window(self):

        # Create the data and datasource objects
        # In order for the date axis to work, the index data points need to
        # be in units of seconds since the epoch.  This is because we are using
        # the CalendarScaleSystem, whose formatters interpret the numerical values
        # as seconds since the epoch.
        numpoints = 500
        index = create_dates(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")

        # Create the price plots
        price_plot, mini_plot = self._create_price_plots(time_ds, price_ds)
        price_plot.index_mapper.domain_limits = (index[0], index[-1])
        self.price_plot = price_plot
        self.mini_plot = mini_plot

        # Create the volume plot
        vol_plot = self._create_vol_plot(time_ds, vol_ds)
        vol_plot.index_mapper.domain_limits = (index[0], index[-1])

        # Set the plot's bottom axis to use the Scales ticking system
        ticker = ScalesTickGenerator(scale=CalendarScaleSystem())
        for plot in price_plot, mini_plot, vol_plot:
            bottom_axis = PlotAxis(plot,
                                   orientation="bottom",
                                   tick_generator=ticker)
            plot.overlays.append(bottom_axis)
            plot.overlays.append(PlotAxis(plot, orientation="left"))
            hgrid, vgrid = add_default_grids(plot)
            vgrid.tick_generator = bottom_axis.tick_generator

        container = VPlotContainer(bgcolor="lightgray",
                                   spacing=40,
                                   padding=50,
                                   fill_padding=False)
        container.add(mini_plot, vol_plot, price_plot)

        return Window(self, -1, component=container)
    def _add_new_plot(self, new_data):
        code = self.data_provider.code

        if code in self.dataset.list_data():
            create_new_plot = False
        else:
            create_new_plot = True

        self.dataset.set_data(code, new_data)

        if create_new_plot:
            new_plot = Plot(self.dataset)
            new_plot.plot(('dates', code), type='line')
            tick_generator = ScalesTickGenerator(scale=CalendarScaleSystem())
            new_plot.x_axis.tick_generator = tick_generator

            self.container.add(new_plot)
            self.container.request_redraw()
Beispiel #13
0
 def _set_scale(self, axis, system):
     p = self.component
     if axis == 'x':
         log_linear_trait = 'index_scale'
         ticks = p.x_ticks
     else:
         log_linear_trait = 'value_scale'
         ticks = p.y_ticks
     if system == 'time':
         system = CalendarScaleSystem()
     if isinstance(system, basestring):
         setattr(p, log_linear_trait, system)
     else:
         if system is None:
             system = dict(linear=p.linear_scale, log=p.log_scale).get(
                 p.get(log_linear_trait), p.linear_scale)
         ticks.scale = system
     p.request_redraw()
Beispiel #14
0
    def _rebuild_plot(self):
        container = self.plot

        value_range = DataRange1D(low=-1, high=1.)
        index_range = DataRange1D(self.index_ds,
                                  high='track',
                                  tracking_amount=24 * 3600 * 365)

        color_mapper = cmap(range=value_range)

        # Remove old plots
        container.remove(*container.components)
        for val, row in zip(self.value_ds, self.rows):
            horizon = HorizonPlot(
                index=self.index_ds,
                value=val,
                index_mapper=LinearMapper(range=index_range,
                                          stretch_data=False),
                value_mapper=BandedMapper(range=DataRange1D(val)),
                color_mapper=cmap(range=DataRange1D(val)),  #color_mapper,
                negative_bands=False,
            )
            horizon.tools.append(
                PanTool(horizon, constrain=True, constrain_direction="x"))
            horizon.overlays.append(
                PlotLabel(component=horizon,
                          hjustify='right',
                          text=row,
                          overlay_position='outside left'))
            container.add(horizon)
        bottom_axis = PlotAxis(
            horizon,
            orientation="bottom",
            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        container.overlays = [bottom_axis]

        container.request_redraw()
Beispiel #15
0
    def _add_new_plot(self, new_data):
        code = self.data_provider.code

        if code in self.dataset.list_data():
            create_new_plot = False
        else:
            create_new_plot = True

        self.dataset.set_data(code, new_data)

        if create_new_plot:
            new_plot = Plot(self.dataset)
            new_plot.plot(('dates', code), type='line')
            new_plot.tools.append(PanTool(new_plot))
            tick_generator = ScalesTickGenerator(scale=CalendarScaleSystem())
            new_plot.x_axis.tick_generator = tick_generator

            # connect the index of the first plot with the new plot
            first_plot = self.container.components[0]
            new_plot.index_range = first_plot.index_range


            self.container.add(new_plot)
            self.container.request_redraw()
Beispiel #16
0
    def update_main_plot(self):
        """ Build main plot
        """
        self.ts_plot = ToolbarPlot(self.arr_plot_data)
        for i, k in enumerate([k for k in self.ts_data.keys()
                               if k != "index"]):
            self.ts_plot.plot(("index", k),
                              name=k,
                              color=colors[i % len(colors)])
        if self.index_is_dates:
            # Index was an array of datetime: overwrite the x axis
            self.ts_plot.x_axis = None
            x_axis = PlotAxis(self.ts_plot,
                              orientation="bottom",
                              tick_generator=ScalesTickGenerator(
                                  scale=CalendarScaleSystem()))
            self.ts_plot.overlays.append(x_axis)
            self.ts_plot.x_grid.tick_generator = x_axis.tick_generator

        if self.data_file:
            self.ts_plot.title = "Time series visualization from %s" % self.data_file
        else:
            self.ts_plot.title = "Time series visualization"
        attach_tools(self.ts_plot)
Beispiel #17
0
    def _create_plot_component(self):

        # find longest date
        index_lengths = []
        for stock in self.stocks:
            if stock.stock_data_cache is not None:
                index_lengths.append(len(stock.stock_data_cache['date']))
            else:
                index_lengths.append(len(stock.stock_data['date']))

        index_lengths = np.array(index_lengths)
        lngest = index_lengths.argmax()
        shrtest = index_lengths.argmin()

        index = np.array([
            time.mktime(x.timetuple())
            for x in self.stocks[lngest].dates.tolist()
        ])

        sel_range_low = time.mktime(
            self.stocks[shrtest].dates.tolist()[0].timetuple())
        sel_range_high = time.mktime(
            self.stocks[shrtest].dates.tolist()[-1].timetuple())

        sel_range_low_idx = np.where(index == sel_range_low)[0].item()
        sel_range_high_idx = np.where(index == sel_range_high)[0].item()

        pd = ArrayPlotData()

        # Now plot the returns for each asset (cumulative sum of periodic rates of return)
        for i in range(len(self.stocks)):
            if self.stocks[i].stock_data_cache is None:
                stk = self.stocks[i].stock_data
            else:
                stk = self.stocks[i].stock_data_cache
            pd.set_data(
                "idx%s" % i,
                np.array([
                    time.mktime(x.timetuple()) for x in stk['date'].tolist()
                ]))
            pd.set_data("y%s" % i, metrics.rate_array(stk)['rate'].cumsum())

        plot = Plot(pd,
                    bgcolor="none",
                    padding=30,
                    border_visible=True,
                    overlay_border=True,
                    use_backbuffer=False)

        for i in range(len(self.stocks)):
            # hang on to a reference to the last one of these...
            plt = plot.plot(("idx%s" % i, "y%s" % i),
                            name=self.stocks[i].symbol,
                            color=self.colors[i])

        #value_range = plot.value_mapper.range
        #index_range = plot.index_mapper.range

        plt[0].active_tool = RangeSelection(plt[0], left_button_selects=True)
        plt[0].active_tool.selection = [
            index[sel_range_low_idx], index[sel_range_high_idx]
        ]
        plt[0].overlays.append(RangeSelectionOverlay(component=plt[0]))
        #plot.bgcolor = "white"
        plot.padding = 50
        add_default_grids(plot)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(
            fill_ratio=0.4,
            default_numlabels=5,
            default_numticks=10,
        )
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = PlotAxis(plot,
                               orientation="bottom",
                               tick_generator=tick_gen,
                               label_color="white",
                               line_color="white")

        # Hack to remove default axis - TODO: how do I *replace* an axis?
        del (plot.underlays[-4])

        plot.overlays.append(bottom_axis)
        plot.legend.visible = True
        return plot
Beispiel #18
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 = linspace(low, high, numpoints)

    now = time()
    timex = linspace(now, now + 7 * 24 * 3600, numpoints)

    # Plot some bessel functions
    value_mapper = None
    index_mapper = None
    plots = {}
    for i in range(10):
        y = jn(i, x)
        if i % 2 == 1:
            plot = create_line_plot(
                (timex, y), color=tuple(COLOR_PALETTE[i]), width=2.0)
            plot.index.sort_order = "ascending"
        else:
            plot = create_scatter_plot(
                (timex, y), color=tuple(COLOR_PALETTE[i]))
        plot.bgcolor = "white"
        plot.border_visible = True
        if i == 0:
            value_mapper = plot.value_mapper
            index_mapper = plot.index_mapper
            left, bottom = add_default_axes(plot)
            left.tick_generator = ScalesTickGenerator()
            bottom.tick_generator = ScalesTickGenerator(
                scale=CalendarScaleSystem())
            add_default_grids(plot, tick_gen=bottom.tick_generator)
        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 == 0:
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)
            # 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)

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

    # 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
Beispiel #19
0
    def initialize_plot(self):
        data = self.data_model

        container = self.plot_container
        self._series = []
        self._plots = {}
        index, rr = None, None
        for i, (a, title) in enumerate((
            ('water_head', 'Head'),
            ('adjusted_water_head', 'Adj. Head'),

                # ('temp', 'Temp.'),
                # ('water_level_elevation', 'Elev.')
        )):
            plot = Plot(
                data=ArrayPlotData(**{
                    'x': data.x,
                    a: getattr(data, a)
                }),
                padding=[70, 10, 10, 10],
                # resizable='h',
                # bounds=(1, 125)
            )

            if index is None:
                index = plot.index_mapper
                rr = plot.index_range
            else:
                plot.index_mapper = index
                plot.index_range = rr

            series = plot.plot(('x', a))[0]
            plot.plot(('x', a), marker_size=1.5, type='scatter')

            dt = DataTool(plot=series,
                          component=plot,
                          normalize_time=False,
                          use_date_str=True)
            dto = DataToolOverlay(component=series, tool=dt)
            series.tools.append(dt)
            series.overlays.append(dto)

            plot.y_axis.title = title
            if i != 0:
                plot.x_axis.visible = False
            else:

                zoom = ZoomTool(plot,
                                tool_mode="range",
                                axis='index',
                                color=(0, 1, 0, 0.5),
                                enable_wheel=False,
                                always_on=False)
                plot.overlays.append(zoom)

                tool = RangeSelection(series,
                                      left_button_selects=True,
                                      listeners=[self])
                self._tool = tool

                series.tools.append(tool)
                # series.active_tool = tool
                # plot.x_axis.title = 'Time'
                bottom_axis = PlotAxis(
                    plot,
                    orientation="bottom",  # mapper=xmapper,
                    tick_generator=ScalesTickGenerator(
                        scale=CalendarScaleSystem()))
                plot.x_axis = bottom_axis

                plot.padding_bottom = 50

            series.overlays.append(RangeSelectionOverlay(component=series))
            container.add(plot)
            self._series.append(series)
            self._plots[a] = plot

        container.invalidate_and_redraw()
Beispiel #20
0
    def get_plot_component(self):
        # Create the array plot data that will feed our plots
        data = self.model.data
        plot_data = ArrayPlotData(
            index=data['dates'],
            close=data['close'],
            volume=data['volume'],
        )
        self.plot_data = plot_data

        # Need to make the FilledLinePlot manually since Plot doesn't
        # support that plot type.
        times = ArrayDataSource(data['dates'])
        prices = ArrayDataSource(data['close'])
        close_plot = FilledLinePlot(
            index=times,
            value=prices,
            index_mapper=LinearMapper(range=DataRange1D(times)),
            value_mapper=LinearMapper(range=DataRange1D(prices)),
            edge_color='blue',
            face_color='paleturquoise',
            bgcolor='white',
            border_visible=True)
        close_plot.padding = [40, 15, 15, 20]
        self.close_plot = close_plot

        # The second plotter object which generates our candle plot
        plotter2 = Plot(data=plot_data)
        low_plot = plotter2.plot(('index', 'close'), )[0]
        low_plot.height = 100
        low_plot.resizable = 'h'
        low_plot.bgcolor = 'white'
        low_plot.border_visible = True
        low_plot.padding = [40, 15, 15, 20]
        low_plot.color = 'darkred'
        low_plot.line_width = 1.5
        self.low_plot = low_plot

        # The third plotter for the bar plot.
        plotter3 = Plot(data=plot_data)
        bar_plot = plotter3.plot(('index', 'volume'), type='bar')[0]
        bar_plot.height = 100
        bar_plot.resizable = 'h'
        bar_plot.bgcolor = 'white'
        bar_plot.border_visible = True
        bar_plot.padding = [40, 15, 15, 20]
        bar_plot.line_color = 'transparent'
        bar_plot.fill_color = 'black'
        bar_plot.bar_width = 3.0
        bar_plot.bar_width_type = 'screen'
        bar_plot.antialias = False
        bar_plot.index_mapper = low_plot.index_mapper
        self.bar_plot = bar_plot

        for plot in (close_plot, low_plot, bar_plot):
            ticker = ScalesTickGenerator(scale=CalendarScaleSystem())
            bottom_axis = PlotAxis(plot,
                                   orientation='bottom',
                                   tick_generator=ticker)
            plot.overlays.append(bottom_axis)
            plot.overlays.append(PlotAxis(plot, orientation='left'))
            hgrid, vgrid = add_default_grids(plot)
            vgrid.tick_generator = bottom_axis.tick_generator

        def vol_label_formatter(val):
            return '%.1E' % val

        bar_plot.overlays[-1].tick_label_formatter = vol_label_formatter

        container = VPlotContainer(
            bgcolor=(240 / 255., 240 / 255., 240 / 255., 1.0),
            spacing=20,
            padding=20,
            fill_padding=True,
            stack_order='top_to_bottom',
            use_back_buffer=True,
        )

        container.add(close_plot)
        container.add(low_plot)
        container.add(bar_plot)

        close_plot.controller = RangeSelection(close_plot)
        zoom_overlay = ZoomOverlay(source=close_plot,
                                   destination=low_plot,
                                   other=bar_plot)
        container.overlays.append(zoom_overlay)

        return container
Beispiel #21
0
# Create some data
numpoints = 100
x = linspace(-2*pi, 2*pi, numpoints)
y1 = sin(x)

# Create the dates
import time
now = time.time()
dt = 24 * 3600    # data points are spaced by 1 day
dates = linspace(now, now + numpoints*dt, numpoints)

# Create some line plots
plot(dates, y1, "b-", bgcolor="white")

# Add some titles
title("Plotting Dates")

current_plot = curplot()
# Set the plot's horizontal axis to be a time scale
current_plot.x_axis.tick_generator.scale = CalendarScaleSystem()
zoom_tool = current_plot.overlays[2]
pan_tool = current_plot.tools[0]
zoom_tool.x_min_zoom_factor = float(1e-3)
pan_tool.restrict_to_data = True


# This command is only necessary if running from command line
show()

Beispiel #22
0
    def _get_plot_overlay(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        container = OverlayPlotContainer(resizable="v",
                                         fill_padding=True,
                                         padding=30,
                                         bgcolor="transparent",
                                         use_backbuffer=True)

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index = self._create_dates(numpoints, start=self.first_day)
        else:
            index = range(numpoints)

        time_ds = ArrayDataSource(index)
        xmapper = LinearMapper(range=DataRange1D(time_ds))

        corr_mapper = None

        for (m, cDx) in enumerate(self.data):

            corr_ds = ArrayDataSource(cDx, sort_order="none")

            if corr_mapper is None:
                corr_mapper = LinearMapper(range=DataRange1D(corr_ds))

            corr_plot = LinePlot(
                index=time_ds,
                value=corr_ds,
                index_mapper=xmapper,
                value_mapper=corr_mapper,
                color=tuple(COLOR_PALETTE[m % len(COLOR_PALETTE)]),
                edge_color="blue",
                face_color="paleturquoise",
                #bgcolor="white",
                border_visible=True,
                padding_left=25)

            corr_mapper.range.add(corr_plot.value)

            if m == 0:
                ###### Y axis #####################################################

                left = PlotAxis(
                    orientation='left',
                    title=self.y_lbl,
                    title_font="modern 12",
                    #title_spacing=0,
                    tick_label_font="modern 8",
                    tick_visible=True,
                    small_axis_style=True,
                    axis_line_visible=False,
                    ensure_labels_bounded=True,
                    #tick_label_color="transparent",
                    mapper=corr_mapper,
                    component=corr_plot)

                corr_plot.overlays.append(left)

                ###### X axis #####################################################

                if self.scale_type == 'Time':
                    # Just the last axis shows tick_labels
                    bottom_axis = PlotAxis(corr_plot,
                                           orientation="bottom",
                                           title=self.x_lbl,
                                           tick_generator=ScalesTickGenerator(
                                               scale=CalendarScaleSystem()))
                else:
                    bottom_axis = PlotAxis(orientation='bottom',
                                           title=self.x_lbl,
                                           title_font="modern 12",
                                           tick_visible=True,
                                           small_axis_style=True,
                                           axis_line_visible=False,
                                           component=corr_plot)

                corr_plot.overlays.append(bottom_axis)

                ###### Grids #####################################################

                _, vgrid = add_default_grids(corr_plot)
                vgrid.tick_generator = bottom_axis.tick_generator

                ###### Tools #####################################################

                corr_plot.tools.append(
                    PanTool(corr_plot, constrain=True,
                            constrain_direction="x"))
                corr_plot.overlays.append(
                    ZoomTool(
                        corr_plot,
                        drag_button="right",
                        always_on=True,
                        tool_mode="box",
                        #axis="index",
                        max_zoom_out_factor=10.0,
                    ))
            container.add(corr_plot)

        ###### Title #####################################################
        container.overlays.append(
            PlotLabel(self.p_title,
                      component=container,
                      overlay_position="outside top",
                      font="modern 16"))

        container.padding_bottom = 50

        return container
Beispiel #23
0
    def _get_plot_vertical(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        container = VPlotContainer(resizable="v",
                                   fill_padding=True,
                                   padding=30,
                                   stack_order="top_to_bottom",
                                   bgcolor="transparent",
                                   spacing=9)

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index = self._create_dates(numpoints, start=self.first_day)
        else:
            index = range(numpoints)

        time_ds = ArrayDataSource(index)
        xmapper = LinearMapper(range=DataRange1D(time_ds))

        corr_mapper = None

        for (m, cDx) in enumerate(self.data):

            corr_ds = ArrayDataSource(cDx, sort_order="none")

            corr_mapper = LinearMapper(range=DataRange1D(corr_ds))

            if corr_mapper.range.low < self.y_low:
                self.y_low = corr_mapper.range.low
            if corr_mapper.range.high > self.y_high:
                self.y_high = corr_mapper.range.high

            corr_plot = LinePlot(index=time_ds,
                                 value=corr_ds,
                                 index_mapper=xmapper,
                                 value_mapper=corr_mapper,
                                 edge_color="blue",
                                 face_color="paleturquoise",
                                 bgcolor="white",
                                 border_visible=True,
                                 padding_left=25)

            ###### Y axis #####################################################

            if self.y_lbl_type == 'Corr':
                vtitle = ("%d" % (m + 1)) + u"\u00B0" + " t_win"
            elif self.y_lbl_type == 'Single':
                vtitle = ""  # One label for all the axis
            elif self.y_lbl_type == 'Custom' and \
                 len(self.y_labels) == self.data.shape[0] and \
                 self.y_labels[m] is not None:
                # a new value in the list defaults to None so raise an error before
                # the operator ends inputing it.
                vtitle = self.y_labels[m]
            else:
                vtitle = ""

            left = PlotAxis(
                orientation='left',
                title=vtitle,
                title_font="modern 12",
                #title_spacing=0,
                tick_label_font="modern 8",
                tick_visible=True,
                small_axis_style=True,
                axis_line_visible=False,
                ensure_labels_bounded=True,
                #tick_label_color="transparent",
                mapper=corr_mapper,
                component=corr_plot)

            corr_plot.overlays.append(left)

            ###### X axis #####################################################

            if m != (self.data.shape[0] - 1):
                if self.scale_type == 'Time':
                    # Set the plot's bottom axis to use the Scales ticking system
                    bottom_axis = PlotAxis(
                        corr_plot,
                        orientation="bottom",
                        tick_label_color="transparent",  # mapper=xmapper,
                        tick_generator=ScalesTickGenerator(
                            scale=CalendarScaleSystem()))
                else:
                    bottom_axis = PlotAxis(orientation='bottom',
                                           title="",
                                           tick_label_color="transparent",
                                           tick_visible=True,
                                           small_axis_style=True,
                                           axis_line_visible=False,
                                           component=corr_plot)
            else:
                if self.scale_type == 'Time':
                    # Just the last axis shows tick_labels
                    bottom_axis = PlotAxis(corr_plot,
                                           orientation="bottom",
                                           title=self.x_lbl,
                                           tick_generator=ScalesTickGenerator(
                                               scale=CalendarScaleSystem()))
                else:
                    bottom_axis = PlotAxis(orientation='bottom',
                                           title=self.x_lbl,
                                           title_font="modern 12",
                                           tick_visible=True,
                                           small_axis_style=True,
                                           axis_line_visible=False,
                                           component=corr_plot)

            corr_plot.overlays.append(bottom_axis)
            _, vgrid = add_default_grids(corr_plot)
            vgrid.tick_generator = bottom_axis.tick_generator

            corr_plot.tools.append(
                PanTool(corr_plot, constrain=True, constrain_direction="x"))
            corr_plot.overlays.append(
                ZoomTool(
                    corr_plot,
                    drag_button="right",
                    always_on=True,
                    tool_mode="box",
                    #axis="index",
                    max_zoom_out_factor=10.0,
                ))

            container.add(corr_plot)

        for component in container.components:
            component.y_mapper.range.set_bounds(self.y_low, self.y_high)

        container.overlays.append(
            PlotLabel(self.p_title,
                      component=container,
                      overlay_position="outside top",
                      font="modern 16"))

        if self.y_lbl_type == 'Single':
            container.overlays.append(
                PlotLabel(self.y_lbl,
                          component=container,
                          angle=90.0,
                          overlay_position="outside left",
                          font="modern 12"))

        container.padding_bottom = 50

        return container
Beispiel #24
0
def _create_plot_components():
    # Create the data and datasource objects
    # In order for the date axis to work, the index data points need to
    # be in units of seconds since the epoch.  This is because we are using
    # the CalendarScaleSystem, whose formatters interpret the numerical values
    # as seconds since the epoch.
    high = 1.
    numpoints = 5000

    random.seed(1000)

    index = create_dates(numpoints)
    price = 100 * cumprod(random.lognormal(0.0, 0.04, size=numpoints))
    changes = price / price[0] - 1.

    index_ds = ArrayDataSource(index)
    value_ds = ArrayDataSource(changes, sort_order="none")
    value_range = DataRange1D(value_ds, low=-high, high=high)

    index_mapper = LinearMapper(range=DataRange1D(index_ds),
                                stretch_data=False)

    horizon = HorizonPlot(
        bands=4,
        index=index_ds,
        value=value_ds,
        index_mapper=index_mapper,
        value_mapper=BandedMapper(range=DataRange1D(low=0, high=high)),
        color_mapper=cmap(range=value_range),
    )
    horizon.tools.append(
        PanTool(horizon, constrain=True, constrain_direction="x"))
    axis = PlotAxis(mapper=horizon.value_mapper,
                    component=horizon,
                    orientation="left",
                    tick_label_position="outside")
    horizon.overlays.append(axis)

    bottom_axis = PlotAxis(
        horizon,
        orientation="bottom",
        tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
    horizon.overlays.append(bottom_axis)

    filled = FilledLinePlot(
        index=index_ds,
        value=value_ds,
        index_mapper=index_mapper,
        value_mapper=LinearMapper(range=value_range, stretch_data=False),
        fill_color=(0.81960784, 0.89803922, 0.94117647),
        edge_color='transparent',
    )
    filled.tools.append(
        PanTool(filled, constrain=True, constrain_direction="x"))
    axis = PlotAxis(mapper=filled.value_mapper,
                    component=filled,
                    orientation="left",
                    tick_label_position="outside")
    filled.overlays.append(axis)

    grid = PlotGrid(
        mapper=filled.value_mapper,
        component=filled,
        orientation='horizontal',
        line_color='lightgray',
        line_style="dot",
    )
    filled.underlays.append(grid)

    colormap = horizon.color_mapper
    colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                        color_mapper=colormap,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=20)

    padding = (40, 20, 0, 0)
    over1 = HPlotContainer(use_backbuffer=True,
                           padding=padding,
                           padding_top=20)
    over1.add(filled)
    over1.add(colorbar)

    over2 = OverlayPlotContainer(padding=padding, padding_bottom=40)
    over2.add(horizon)

    return over1, over2
Beispiel #25
0
    def setup(self, x, y, ans, atypes, mapping):
        from pychron.pipeline.plot.plotter.ticks import StaticTickGenerator

        def get_analysis_type(x):
            x = int(math.floor(x))
            return next((k for k, v in mapping.items() if v == x))

        p = self.new_plot()
        p.padding_left = 200

        def tickformatter(x):
            return atypes[int(x)]

        p.y_axis.tick_label_rotate_angle = 60
        p.y_axis.tick_label_formatter = tickformatter
        p.y_axis.tick_generator = StaticTickGenerator(_nticks=len(atypes))
        p.y_axis.title = 'Analysis Type'
        p.y_axis.title_font = 'modern 18'
        p.y_axis.tick_label_font = 'modern 14'

        self.add_axis_tool(p, p.x_axis)
        self.add_axis_tool(p, p.y_axis)
        self.add_limit_tool(p, 'x')
        self.add_limit_tool(p, 'y')

        self.set_y_limits(min_=-1, max_=len(atypes))

        p.index_range.tight_bounds = False
        p.x_axis.tick_generator = ScalesTickGenerator(
            scale=CalendarScaleSystem())
        p.x_grid.tick_generator = p.x_axis.tick_generator
        p.x_axis.title = 'Time'
        p.x_axis.title_font = 'modern 18'
        p.x_axis.tick_label_font = 'modern 14'

        t = GroupingTool(component=p)
        p.tools.append(t)
        o = GroupingOverlay(component=p, tool=t)
        p.overlays.append(o)

        self.grouping_tool = t

        scatter, _ = self.new_series(x,
                                     y,
                                     type='scatter',
                                     marker_size=1.5,
                                     selection_color='red',
                                     selection_marker='circle',
                                     selection_marker_size=2.5)

        broadcaster = BroadcasterTool()
        scatter.tools.append(broadcaster)

        point_inspector = AnalysisPointInspector(
            scatter,
            analyses=ans,
            value_format=get_analysis_type,
            additional_info=lambda i, x, y, ai:
            ('Time={}'.format(ai.rundate), 'Project={}'.format(ai.project)))

        pinspector_overlay = PointInspectorOverlay(component=scatter,
                                                   tool=point_inspector)

        rect_tool = RectSelectionTool(scatter)
        rect_overlay = RectSelectionOverlay(component=scatter, tool=rect_tool)

        broadcaster.tools.append(rect_tool)
        broadcaster.tools.append(point_inspector)

        scatter.overlays.append(pinspector_overlay)
        scatter.overlays.append(rect_overlay)

        self.scatter = scatter
def _create_plot_component():

    # Create the data and datasource objects
    # In order for the date axis to work, the index data points need to
    # be in units of seconds since the epoch.  This is because we are using
    # the CalendarScaleSystem, whose formatters interpret the numerical values
    # as seconds since the epoch.
    numpoints = 500
    index = create_dates(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",
                                bgcolor="white",
                                border_visible=True)
    price_plot.overlays.append(PlotAxis(price_plot, orientation='left')),

    # Set the plot's bottom axis to use the Scales ticking system
    bottom_axis = PlotAxis(
        price_plot,
        orientation="bottom",  # mapper=xmapper,
        tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
    price_plot.overlays.append(bottom_axis)
    hgrid, vgrid = add_default_grids(price_plot)
    vgrid.tick_generator = bottom_axis.tick_generator

    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",
            max_zoom_out_factor=10.0,
        ))

    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)

    hgrid, vgrid = add_default_grids(vol_plot)
    # Use the same tick generator as the x-axis on the price plot
    vgrid.tick_generator = bottom_axis.tick_generator
    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=40,
                               padding=50,
                               fill_padding=False)
    container.add(vol_plot)
    container.add(price_plot)
    container.overlays.append(
        PlotLabel(
            "Financial Plot with Date Axis",
            component=container,
            #font="Times New Roman 24"))
            font="Arial 24"))

    return container
# Major library imports
from numpy import linspace, pi, sin

# Enthought library imports
from chaco.shell import show, plot, title, curplot
from chaco.scales.api import CalendarScaleSystem

# Create some data
numpoints = 100
x = linspace(-2 * pi, 2 * pi, numpoints)
y1 = sin(x)

# Create the dates
import time
now = time.time()
dt = 24 * 3600  # data points are spaced by 1 day
dates = linspace(now, now + numpoints * dt, numpoints)

# Create some line plots
plot(dates, y1, "b-", bgcolor="white")

# Add some titles
title("Plotting Dates")

# Set the plot's horizontal axis to be a time scale
curplot().x_axis.tick_generator.scale = CalendarScaleSystem()

#This command is only necessary if running from command line
show()
Beispiel #28
0
    def __init__(self, **kw):
        super(MLabChacoPlot, self).__init__(**kw)
        
        self.prices = get_data()
        x = self.prices['Date']
        pd = ArrayPlotData(index = x)
        pd.set_data("y", self.prices["Crude Supply"])

        # 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", "y"), name="Crude Price", color=(.3, .3, .8, .8))
        #plot.tools.append(PanTool(plot))

        plot.tools.append(PanTool(plot, constrain=True, drag_button="right",
                                  constrain_direction="x"))

        range_plt = plot.plots['Crude Price'][0]

        range_selection = RangeSelection(range_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, 'selection')
        range_plt.tools.append(range_selection)
        range_plt.overlays.append(RangeSelectionOverlay(range_plt))


        zoom = ZoomTool(component=plot, tool_mode="range", always_on=False,
                        axis="index", max_zoom_out_factor=1.0,)
        plot.overlays.append(zoom)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4,
                                        default_numlabels=5,
                                        default_numticks=10,)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(plot, orientation="bottom",
                                     tick_generator=tick_gen,
                                     label_color="white",
                                     line_color="white")

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del(plot.underlays[-2])

        plot.overlays.append(bottom_axis)

        # Create the mlab test mesh and get references to various parts of the
        # VTK pipeline
        f = mlab.figure(size=(700,500))
        self.m = mlab.points3d(self.prices['Gasoline Supply'], self.prices['Jet Fuel Supply'], self.prices['Distillate Supply'], self.prices['Crude Supply'])
        
        # Add another glyph module to render the full set of points
        g2 = Glyph()
        g2.glyph.glyph_source.glyph_source.glyph_type = "circle"
        g2.glyph.glyph_source.glyph_source.filled = True
        g2.actor.property.opacity = 0.75
        self.m.module_manager.source.add_module(g2)
        
        # Set a bunch of properties on the scene to make things look right
        self.m.module_manager.scalar_lut_manager.lut_mode = 'PuBuGn'
        self.m.glyph.mask_points.random_mode = False
        self.m.glyph.mask_points.on_ratio = 1
        self.m.scene.isometric_view()
        self.m.scene.background = (.9, 0.95, 1.0)
        
        scene = mlab.gcf().scene
        render_window = scene.render_window
        renderer = scene.renderer
        rwi = scene.interactor

        plot.resizable = ""
        plot.bounds = [600,120]
        plot.padding = 25
        plot.bgcolor = "white"
        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.InteractorStyleTrackballCamera, 
                bgcolor = "transparent",
                event_passthrough = True,
                )

        mlab.show()
Beispiel #29
0
    def _get_plot_cmap(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index_x = self._create_dates(numpoints, start=self.first_day)
        else:
            index_x = np.arange(numpoints)

        x_bounds = (index_x[0], index_x[-1], len(index_x))
        y_bounds = (1, self.data.shape[0], self.data.shape[0])
        # Create a plot data obect and give it this data
        pd = ArrayPlotData()
        pd.set_data("imagedata", self.data)

        plot = Plot(pd)

        plot.img_plot("imagedata",
                      name="corr_plot",
                      origin="top left",
                      xbounds=x_bounds[:2],
                      ybounds=y_bounds[:2],
                      colormap=jet,
                      padding_left=25)

        corr_plot = plot.plots['corr_plot'][0]

        if self.scale_type == 'Time':
            # Just the last axis shows tick_labels
            bottom_axis = PlotAxis(corr_plot,
                                   orientation="bottom",
                                   title=self.x_lbl,
                                   tick_generator=ScalesTickGenerator(
                                       scale=CalendarScaleSystem()))
        else:
            bottom_axis = PlotAxis(orientation='bottom',
                                   title=self.x_lbl,
                                   title_font="modern 12",
                                   tick_visible=True,
                                   small_axis_style=True,
                                   axis_line_visible=False,
                                   component=corr_plot)

        corr_plot.overlays.append(bottom_axis)

        corr_plot.tools.append(
            PanTool(corr_plot,
                    constrain=True,
                    constrain_direction="x",
                    constrain_key="shift"))
        corr_plot.overlays.append(
            ZoomTool(
                corr_plot,
                drag_button="right",
                always_on=True,
                tool_mode="range",
                axis="index",
                max_zoom_out_factor=10.0,
            ))

        # Create the colorbar, handing in the appropriate range and colormap
        colorbar = ColorBar(
            index_mapper=LinearMapper(range=corr_plot.color_mapper.range),
            color_mapper=corr_plot.color_mapper,
            plot=corr_plot,
            orientation='v',
            resizable='v',
            width=30,
            padding_top=corr_plot.padding_top,
            padding_bottom=corr_plot.padding_bottom,
            padding_left=50,
            padding_right=5)

        #colorbar.plot = corr_plot
        #colorbar.padding_top = corr_plot.padding_top
        #colorbar.padding_bottom = corr_plot.padding_bottom

        # Add pan and zoom tools to the colorbar
        pan_tool = PanTool(colorbar, constrain_direction="y", constrain=True)
        colorbar.tools.append(pan_tool)

        zoom_overlay = ZoomTool(colorbar,
                                axis="index",
                                tool_mode="range",
                                always_on=False,
                                drag_button=None)
        colorbar.overlays.append(zoom_overlay)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(corr_plot,
                                   colorbar,
                                   use_backbuffer=True,
                                   bgcolor="transparent",
                                   spacing=9,
                                   padding=30)

        container.overlays.append(
            PlotLabel(self.p_title,
                      component=container,
                      overlay_position="outside top",
                      font="modern 16"))

        container.overlays.append(
            PlotLabel(self.y_lbl,
                      component=container,
                      angle=90.0,
                      overlay_position="outside left",
                      font="modern 12"))

        container.padding_bottom = 50

        return container
Beispiel #30
0
    def _get_plot_multiline(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index_x = self._create_dates(numpoints, start=self.first_day)
        else:
            index_x = np.arange(numpoints)

        index_y = np.linspace(1, self.data.shape[0], self.data.shape[0])

        xs = ArrayDataSource(index_x)
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(index_y)
        yrange = DataRange1D()
        yrange.add(ys)

        # The data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=self.data)

        corr_plot = \
            MultiLinePlot(
                index=xs,
                yindex=ys,
                index_mapper=LinearMapper(range=xrange),
                value_mapper=LinearMapper(range=yrange),
                value=ds,
                global_max=self.data.max(),
                global_min=self.data.min())

        corr_plot.value_mapper.range.low = 0
        corr_plot.value_mapper.range.high = self.data.shape[0] + 1

        self.multi_line_plot_renderer = corr_plot

        plot = Plot(title=self.p_title)

        if self.scale_type == 'Time':
            # Just the last axis shows tick_labels
            bottom_axis = PlotAxis(component=plot,
                                   orientation="bottom",
                                   title=self.x_lbl,
                                   tick_generator=ScalesTickGenerator(
                                       scale=CalendarScaleSystem()))
        else:
            bottom_axis = PlotAxis(orientation='bottom',
                                   title=self.x_lbl,
                                   title_font="modern 12",
                                   tick_visible=True,
                                   small_axis_style=True,
                                   axis_line_visible=False,
                                   component=plot)

        if self.y_lbl_type == 'Custom' and \
            len(self.y_labels) == self.data.shape[0]:
            # a new value in the list defaults to None so raise an error before
            # the operator ends inputing it.

            left_axis = LabelAxis(component=plot,
                                  orientation='left',
                                  title=self.x_lbl,
                                  mapper=corr_plot.value_mapper,
                                  tick_interval=1.0,
                                  labels=self.y_labels,
                                  positions=index_y)
        else:
            left_axis = PlotAxis(
                component=plot,
                orientation='left',
                title=self.y_lbl,
                title_font="modern 12",
                #title_spacing=0,
                tick_label_font="modern 8",
                tick_visible=True,
                small_axis_style=True,
                axis_line_visible=False,
                ensure_labels_bounded=True,
                #tick_label_color="transparent",
                mapper=corr_plot.value_mapper)

        plot.overlays.extend([bottom_axis, left_axis])

        plot.add(corr_plot)

        plot.padding_bottom = 50

        return plot