Пример #1
0
		def __init__(self,data_q,num):
			super(PlotterWindow,self).__init__()

			self.data_q = data_q

			self.x = ArrayDataSource(zeros(num))
			self.y = ArrayDataSource(zeros(num))
			self.v = MultiArrayDataSource(zeros((num,2)))

			xrange = DataRange1D()
			xrange.add(self.x)
			yrange = DataRange1D()
			yrange.add(self.y)

			quiverplot = QuiverPlot(index=self.x,value=self.y,vectors=self.v,
				index_mapper=LinearMapper(range=xrange),
				value_mapper=LinearMapper(range=yrange),
				bgcolor='white')
			add_default_axes(quiverplot)
			add_default_grids(quiverplot)

			quiverplot.tools.append(PanTool(quiverplot,constrain_key='shift'))
			quiverplot.overlays.append(ZoomTool(quiverplot))

			self.plot = OverlayPlotContainer(quiverplot, padding=50)
			self.timer = Timer(50.0, self.onTimer)

			self.configure_traits()
Пример #2
0
def _create_plot_component():
    # Create some data
    numpts = 400
    x = sort(random(numpts))
    y = random(numpts)
    xs = ArrayDataSource(x, sort_order='ascending')
    ys = ArrayDataSource(y)
    vectorlen = 15
    vectors = array((random(numpts) * vectorlen, random(numpts) * vectorlen)).T
    vector_ds = MultiArrayDataSource(vectors)
    xrange = DataRange1D()
    xrange.add(xs)
    yrange = DataRange1D()
    yrange.add(ys)
    quiverplot = QuiverPlot(index=xs,
                            value=ys,
                            vectors=vector_ds,
                            index_mapper=LinearMapper(range=xrange),
                            value_mapper=LinearMapper(range=yrange),
                            bgcolor="white")
    add_default_axes(quiverplot)
    add_default_grids(quiverplot)
    # Attach some tools to the plot
    quiverplot.tools.append(PanTool(quiverplot, constrain_key="shift"))
    zoom = ZoomTool(quiverplot)
    quiverplot.overlays.append(zoom)
    container = OverlayPlotContainer(quiverplot, padding=50)

    return container
Пример #3
0
    def _setup_plot_tools(self, plot):
        """Sets up the background, and several tools on a plot"""
        # Make a white background with grids and axes
        plot.bgcolor = "white"
        add_default_grids(plot)
        add_default_axes(plot)

        # Allow white space around plot
        plot.index_range.tight_bounds = False
        plot.index_range.refresh()
        plot.value_range.tight_bounds = False
        plot.value_range.refresh()

        # The PanTool allows panning around the plot
        plot.tools.append(PanTool(plot))

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

        # The DragZoom tool just zooms in and out as the user drags
        # the mouse vertically.
        dragzoom = DragZoom(plot, drag_button="right")
        plot.tools.append(dragzoom)

        # 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)

        return plot.value_mapper, plot.index_mapper, legend
def _create_plot_component():
    # Create some data
    numpts = 400
    x = sort(random(numpts))
    y = random(numpts)
    xs = ArrayDataSource(x, sort_order='ascending')
    ys = ArrayDataSource(y)
    vectorlen = 15
    vectors = array((random(numpts)*vectorlen,random(numpts)*vectorlen)).T
    vector_ds = MultiArrayDataSource(vectors)
    xrange = DataRange1D()
    xrange.add(xs)
    yrange = DataRange1D()
    yrange.add(ys)
    quiverplot = QuiverPlot(index = xs, value = ys,
                    vectors = vector_ds,
                    index_mapper = LinearMapper(range=xrange),
                    value_mapper = LinearMapper(range=yrange),
                    bgcolor = "white")
    add_default_axes(quiverplot)
    add_default_grids(quiverplot)
    # Attach some tools to the plot
    quiverplot.tools.append(PanTool(quiverplot, constrain_key="shift"))
    zoom = ZoomTool(quiverplot)
    quiverplot.overlays.append(zoom)
    container = OverlayPlotContainer(quiverplot, padding=50)
   
    return container
Пример #5
0
    def plotHistogram(self, image, plot=None):
        if plot == None:
            pd = ArrayPlotData(y=np.array([0]), x=np.array([0]))
            plot = Plot(pd, padding=(70, 10, 0, 0))
            plot.plot(('x', 'y'), name='Histogram', type='bar', bar_width=5.0, color='auto')
            #plot.title = 'Histogram'
            plot.line_color = 'black'
            plot.bgcolor = "white"
            plot.fixed_preferred_size = (100, 30)
            add_default_grids(plot)
            plot.value_axis.title = "Histogram"
            self._appendHistogramTools(plot)
            '''
            plot.overlays.append(PlotAxis(plot, orientation='left'))
            plot.overlays.append(PlotAxis(plot, orientation='bottom'))
            '''
        else:
            data = np.histogram(image.data, bins=10000)
            index = np.delete(data[1], data[1].size-1)
            values = data[0]
            
            plot.index_range.low= np.min(index)
            plot.index_range.high = np.max(index)
            plot.value_range.low = 0
            plot.value_range.high = np.max(values)

            plot.data.set_data('x', index)
            plot.data.set_data('y', values)
        plot.request_redraw()
        return plot
Пример #6
0
    def plotHistogram(self, image, plot=None):
        '''Plots a histogram.

        |  image -- Image object
        |  plot  -- plot instance to be updated 
        |           if None, a plot instance will be created

        Returns the plot instance.
        '''
        if plot == None:
            pd = ArrayPlotData(y=np.array([0]), x=np.array([0]))
            plot = Plot(pd, padding=(70, 10, 0, 0))
            plot.plot(('x', 'y'), name='Histogram', type='bar', bar_width=1.0)
            plot.line_color = 'black'
            plot.bgcolor = "white"
            plot.fixed_preferred_size = (100, 30)
            add_default_grids(plot)
            plot.value_range.low = 'auto'
            plot.value_range.high = 'auto'
            plot.index_range.low = 'auto'
            plot.index_range.high = 'auto'
            plot.value_axis.title = "Histogram"
            self.appendHistogramTools(plot)
            
        else:
            data = np.histogram(image.data, bins=10000)
            index = np.delete(data[1], data[1].size-1)
            values = data[0]
            self.setData(values, index, plot)
        plot.invalidate_and_redraw()
        return plot
Пример #7
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
Пример #8
0
    def _setup_plot_tools(self, plot):
        """Sets up the background, and several tools on a plot"""
        # Make a white background with grids and axes
        plot.bgcolor = "white"
        add_default_grids(plot)
        add_default_axes(plot)

        # Allow white space around plot
        plot.index_range.tight_bounds = False
        plot.index_range.refresh()
        plot.value_range.tight_bounds = False
        plot.value_range.refresh()

        # The PanTool allows panning around the plot
        plot.tools.append(PanTool(plot))

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

        # The DragZoom tool just zooms in and out as the user drags
        # the mouse vertically.
        dragzoom = DragZoom(plot, drag_button="right")
        plot.tools.append(dragzoom)

        # 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)

        return plot.value_mapper, plot.index_mapper, legend
Пример #9
0
def _create_plot_component(title, initial_values=None, on_change_functor=None):

    #return OverlayPlotContainer()


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

    if initial_values:
        x = initial_values[0]
        y = initial_values[1]
    else:
        # 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 = 2)
    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)

    point_dragging_tool = PointDraggingTool(scatter)
    point_dragging_tool.on_change_functor = on_change_functor
    scatter.tools.append(point_dragging_tool)


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

    #container.mx = lineplot.index.get_data()
    #container.my = lineplot.value.get_data()
    container.lineplot = lineplot
    return container
Пример #10
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
Пример #11
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
Пример #12
0
    def _refresh_container(self):
        ''' rebuild the container for the current data
        '''
        broadcaster = BroadcasterTool()

        mfn_line = self.value
        #   print self.panel.GetSize()
        adapter = self.adapter
        if adapter.var_x != '':
            # Get the x-label text from the object's trait var_x
            label_x = getattr(self.object, adapter.var_x)
        else:
            # Get the x-label from the adapter
            label_x = adapter.label_x

        if adapter.var_y != '':
            label_y = getattr(self.object, adapter.var_y)
        else:
            label_y = adapter.label_y

        index = ArrayDataSource(mfn_line.xdata)
        y = ArrayDataSource(mfn_line.ydata, sort_order="none")

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

        value_range = DataRange1D(low_setting=0.0)
        value_range.add(y)
        value_mapper = LinearMapper(range=value_range)

        styles_m = list(adapter.line_style.values())
        line_style = styles_m[0]
        line_color = adapter.line_color[0]

        line_plot = self.lplot = LinePlot(index=index,
                                          value=y,
                                          index_mapper=index_mapper,
                                          value_mapper=value_mapper,
                                          color=line_color,
                                          width=25,
                                          edge_color='blue',
                                          linestyle=line_style,
                                          border_visible=False)

        add_default_grids(line_plot)
        add_default_axes(line_plot, vtitle="Y", htitle="X")

        self.plot_container.add(line_plot)
        line_plot.tools.append(PanTool(line_plot))
        line_plot.overlays.append(ZoomTool(line_plot))
Пример #13
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
Пример #14
0
    def _refresh_container(self):
        ''' rebuild the container for the current data
        '''
        broadcaster = BroadcasterTool()

        mfn_line = self.value
     #   print self.panel.GetSize()
        adapter = self.adapter
        if adapter.var_x != '':
            # Get the x-label text from the object's trait var_x
            label_x = getattr(self.object, adapter.var_x)
        else:
            # Get the x-label from the adapter
            label_x = adapter.label_x

        if adapter.var_y != '':
            label_y = getattr(self.object, adapter.var_y)
        else:
            label_y = adapter.label_y

        index = ArrayDataSource(mfn_line.xdata)
        y = ArrayDataSource(mfn_line.ydata, sort_order="none")

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

        value_range = DataRange1D(low_setting=0.0)
        value_range.add(y)
        value_mapper = LinearMapper(range=value_range)

        styles_m = adapter.line_style.values()
        line_style = styles_m[0]
        line_color = adapter.line_color[0]

        line_plot = self.lplot = LinePlot(index=index, value=y,
                                          index_mapper=index_mapper,
                                          value_mapper=value_mapper,
                                          color=line_color,
                                          width=25,
                                          edge_color='blue',
                                          linestyle=line_style,
                                          border_visible=False)

        add_default_grids(line_plot)
        add_default_axes(line_plot, vtitle="Y", htitle="X")

        self.plot_container.add(line_plot)
        line_plot.tools.append(PanTool(line_plot))
        line_plot.overlays.append(ZoomTool(line_plot))
Пример #15
0
    def _make_plot_frame(self):
        super(MainEffectsPlot, self)._make_plot_frame()
        # Update plot ranges and mappers
        self.index_labels = self.plot_data.obj_n
        index = ArrayDataSource(range(len(self.index_labels)))
        self.index_range.add(index)
        for name in ['values', 'ylow', 'yhigh']:
            value = self.mk_ads(name)
            self.value_range.add(value)

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

        add_default_grids(self)
Пример #16
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
Пример #17
0
    def _create_window(self):
        self._create_data()
        x = self.x_values[:self.current_index]
        y = self.y_values[:self.current_index]

        value_range = None
        index_range = None
        plot = create_line_plot((x, y), color="red", width=2.0)
        value_range = plot.value_mapper.range
        index_range = plot.index_mapper.range
        index_range.low = -5
        index_range.high = 15
        plot.padding = 50
        plot.fill_padding = True
        plot.bgcolor = "white"
        left, bottom = add_default_axes(plot)
        hgrid, vgrid = add_default_grids(plot)
        bottom.tick_interval = 2.0
        vgrid.grid_interval = 2.0

        self.plot = plot
        plot.tools.append(PanTool(component=plot))
        plot.overlays.append(
            ZoomTool(component=plot, tool_mode="box", always_on=False))

        # Set the timer to generate events to us
        timerId = wx.NewId()
        self.timer = wx.Timer(self, timerId)
        self.Bind(wx.EVT_TIMER, self.onTimer, id=timerId)
        self.timer.Start(50.0, wx.TIMER_CONTINUOUS)
        return Window(self, -1, component=plot)
Пример #18
0
    def _create_window(self):
        self._create_data()
        x = self.x_values[:]
        y = self.y_values[:]

        plots = []


        plot = create_line_plot((x,y), color="red", width=2.0)
        plot.padding = 50
        plot.fill_padding = True
        plot.bgcolor = "white"
        left, bottom = add_default_axes(plot)
        hgrid, vgrid = add_default_grids(plot)
        bottom.tick_interval = 2.0
        vgrid.grid_interval = 2.0


        self.plot = plot
        plot.tools.append(PanTool(component=plot))
        plot.overlays.append(ZoomTool(component=plot, tool_mode="box",
                                        always_on=False))

        self.timer = Timer(50.0, self.onTimer)
        return Window(self, -1, component=plot)
Пример #19
0
    def _create_window(self):
        self._create_data()
        x = self.x_values[:self.current_index]
        y = self.y_values[:self.current_index]

        value_range = None
        index_range = None
        plot = create_line_plot((x,y), color="red", width=2.0)
        value_range = plot.value_mapper.range
        index_range = plot.index_mapper.range
        index_range.low = -5
        index_range.high = 15
        plot.padding = 50
        plot.fill_padding = True
        plot.bgcolor = "white"
        left, bottom = add_default_axes(plot)
        hgrid, vgrid = add_default_grids(plot)
        bottom.tick_interval = 2.0
        vgrid.grid_interval = 2.0


        self.plot = plot
        plot.tools.append(PanTool(component=plot))
        plot.overlays.append(ZoomTool(component=plot, tool_mode="box",
                                        always_on=False))

        # Set the timer to generate events to us
        timerId = wx.NewId()
        self.timer = wx.Timer(self, timerId)
        self.Bind(wx.EVT_TIMER, self.onTimer, id=timerId)
        self.timer.Start(50.0, wx.TIMER_CONTINUOUS)
        return Window(self, -1, component=plot)
Пример #20
0
    def plotRRMap(self, ydata, title, plot=None):
        '''Plots an RR map.

        |  ydata -- y-data to be plotted
        |  title -- RR type, to be displayed on y-axis
        |  plot  -- plot instance to be updated 
        |           if None, a plot instance will be created

        Returns the plot instance.
        '''
        if plot == None:
            pd = ArrayPlotData()
            plot = Plot(pd, padding=(79, 5, 0, 0))
            self.setData(ydata, None, plot)
            plot.plot(('x', 'y'), name='rrplot', type="scatter", color='green',
                      marker="circle", marker_size=6)
            plot.value_axis.title = title
            plot.bgcolor = 'white'
            plot.aspect_ratio = 2.5
            plot.fixed_preferred_size = (100, 50)
            plot.y_axis.tick_label_formatter = lambda val:('%.2E'%val)
            plot.x_axis.visible = False
            hgrid, vgrid = add_default_grids(plot)
            self.appendRRTools(plot)
        else:
            self.setData(ydata, None, plot)
        plot.invalidate_and_redraw()
        return plot
Пример #21
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)
    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
Пример #22
0
def _create_plot_component(use_downsampling=True):

    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(10):
        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
Пример #23
0
def _create_plot_component():

    numpoints = 100
    low = -5
    high = 15.001
    x = arange(low, high, (high-low)/numpoints)

    # Plot a bessel function
    y = jn(0, x)
    plot = create_line_plot((x,y), color=(0,0,1,1), width=2.0, index_sort="ascending")
    value_range = plot.value_mapper.range
    plot.active_tool = RangeSelection(plot, left_button_selects = True)
    plot.overlays.append(RangeSelectionOverlay(component=plot))
    plot.bgcolor = "white"
    plot.padding = 50
    add_default_grids(plot)
    add_default_axes(plot)

    return plot
Пример #24
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
Пример #25
0
    def _create_plot_component(self):

        container = OverlayPlotContainer(padding=50,
                                         fill_padding=True,
                                         bgcolor="white",
                                         use_backbuffer=True)
        types = {"line": LinePlot, "scatter": ScatterPlot}

        # Create the initial X-series of data
        if len(self) > 0:  # Only create a plot if we ahve datat
            if self.p_type == "scatter and line":
                lineplot = self._create_plot(p_type=LinePlot)
                #lineplot.selected_color = "none"
                scatter = self._create_plot(p_type=ScatterPlot)
                scatter.bgcolor = "white"
                scatter.index_mapper = lineplot.index_mapper
                scatter.value_mapper = lineplot.value_mapper
                add_default_grids(scatter)
                add_default_axes(scatter)
                container.add(lineplot)
                container.add(scatter)
            else:
                plot = self._create_plot(p_type=types[self.p_type])
                add_default_grids(plot)
                add_default_axes(plot)
                container.add(plot)
                scatter = plot
            scatter.tools.append(PanTool(scatter, drag_button="left"))

            # The ZoomTool tool is stateful and allows drawing a zoom
            # box to select a zoom region.
            zoom = ZoomTool(scatter,
                            tool_mode="box",
                            always_on=True,
                            drag_button="right")
            scatter.overlays.append(zoom)
            csr = CursorTool(scatter, color="black", drag_button="left")
            scatter.overlays.append(csr)

        self.plot = container
        return container
Пример #26
0
def _create_plot_component():

    numpoints = 100
    low = -5
    high = 15.001
    x = arange(low, high, (high - low) / numpoints)

    # Plot a bessel function
    y = jn(0, x)
    plot = create_line_plot((x, y),
                            color=(0, 0, 1, 1),
                            width=2.0,
                            index_sort="ascending")
    value_range = plot.value_mapper.range
    plot.active_tool = RangeSelection(plot, left_button_selects=True)
    plot.overlays.append(RangeSelectionOverlay(component=plot))
    plot.bgcolor = "white"
    plot.padding = 50
    add_default_grids(plot)
    add_default_axes(plot)

    return plot
Пример #27
0
    def _plot_default(self):
        # Create starting points for the vectors.
        numpts = self.numpts
        x = sort(random(numpts))
        y = random(numpts)

        # Create vectors.
        vectorlen = self.vectorlen
        vectors = array((random(numpts)*vectorlen, random(numpts)*vectorlen)).T

        # Create an array data sources to plot all vectors at once
        xs = ArrayDataSource(x, sort_order='ascending')
        ys = ArrayDataSource(y)
        vector_ds = MultiArrayDataSource(vectors)

        # Set up the Plot
        xrange = DataRange1D()
        xrange.add(xs)
        yrange = DataRange1D()
        yrange.add(ys)

        quiverplot = QuiverPlot(index = xs, value = ys,
                        vectors = vector_ds,
                        index_mapper = LinearMapper(range=xrange),
                        value_mapper = LinearMapper(range=yrange),
                        bgcolor = "white")

        add_default_axes(quiverplot)
        add_default_grids(quiverplot)

        # Attach some tools to the plot
        quiverplot.tools.append(PanTool(quiverplot, constrain_key="shift"))
        zoom = ZoomTool(quiverplot)
        quiverplot.overlays.append(zoom)

        container = OverlayPlotContainer(quiverplot, padding=50)

        return container
Пример #28
0
	def init_plot(self):
		x = arange(100)
		y = arange(100)
		self.plothandle = create_line_plot((x,y), color="red", width=2.0, 
						index_bounds=(-5,100), value_bounds=(-100,100))
		self.plothandle.padding = 50
		self.plothandle.fill_padding = True
		self.plothandle.bgcolor = "white"
		left, bottom = add_default_axes(self.plothandle, 
							vtitle=self.ytitle, htitle="Time (s)")
		hgrid, vgrid = add_default_grids(self.plothandle)
		bottom.tick_interval = 20.0
		vgrid.grid_interval = 10.0

		return self.plothandle
Пример #29
0
    def _create_plot_component(self):

        container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                         bgcolor = "white", use_backbuffer=True)
        types={"line":LinePlot, "scatter":ScatterPlot}

        # Create the initial X-series of data
        if len(self)>0: # Only create a plot if we ahve datat
            if self.p_type=="scatter and line":
                lineplot = self._create_plot(p_type=LinePlot)
                #lineplot.selected_color = "none"
                scatter=self._create_plot(p_type=ScatterPlot)
                scatter.bgcolor = "white"
                scatter.index_mapper=lineplot.index_mapper
                scatter.value_mapper=lineplot.value_mapper
                add_default_grids(scatter)
                add_default_axes(scatter)
                container.add(lineplot)
                container.add(scatter)
            else:
                plot= self._create_plot(p_type=types[self.p_type])
                add_default_grids(plot)
                add_default_axes(plot)
                container.add(plot)
                scatter=plot
            scatter.tools.append(PanTool(scatter, drag_button="left"))

            # The ZoomTool tool is stateful and allows drawing a zoom
            # box to select a zoom region.
            zoom = ZoomTool(scatter, tool_mode="box", always_on=True, drag_button="right")
            scatter.overlays.append(zoom)
            csr=CursorTool(scatter, color="black", drag_button="left")
            scatter.overlays.append(csr)

        self.plot=container
        return container
Пример #30
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)
Пример #31
0
    def __init__(self):
        # list of allready added data
        # self.data[name] = [timeData,yData]
        self.data = {}

        # next color index from map
        self.colNr = 0

        self.plotdata = ArrayPlotData()

        self.plot = Plot(self.plotdata)
        self.plot.legend.visible = True

        self.__existingData = []  ## legenLabels

        # time axis
        time_axis = PlotAxis(self.plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        #self.plot.overlays.append(time_axis)
        self.plot.x_axis = time_axis

        hgrid, vgrid = add_default_grids(self.plot)
        self.plot.x_grid = None
        vgrid.tick_generator = time_axis.tick_generator

        # drag tool only time dir
        self.plot.tools.append(PanTool(self.plot, constrain=False,
                                #    constrain_direction="x"
                                      )
                                )

        # zoom tool only y dir
        self.plot.overlays.append(
        	#ZoomTool(self.plot, drag_button="right", always_on=True, tool_mode="range", axis="value" )
        	ZoomTool(self.plot, tool_mode="box", always_on=False)
        	)

        # init plot
        self.plot.plot(
            (
                self.plotdata.set_data(name = None, new_data = [time.mktime(testTime[i].timetuple()) for i in xrange(len(testTime))], generate_name=True),
                self.plotdata.set_data(name = None, new_data = testData, generate_name=True)
            ),
            name = 'temp')
        self.plot.request_redraw()
        self.plot.delplot('temp')
Пример #32
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)
Пример #33
0
 def plotRRMap(self, rr, rrchoice, plot=None):
     if plot == None:
         pd = ArrayPlotData(y=np.array([0]), x=np.array([0]))
         plot = Plot(pd, padding=(70, 5, 0, 0))
         self._setData(rr, plot)
         plot.plot(('x', 'y'), name='rrplot', type="scatter", color='green',
                   marker="circle", marker_size=6)
         #plot.title = 'rrplot'
         plot.value_axis.title = rrchoice
         #plot.y_axis.visible = False
         plot.bgcolor = 'white'
         plot.aspect_ratio = 2.5
         plot.fixed_preferred_size = (100, 50)
         #left, bottom = add_default_axes(plot)
         hgrid, vgrid = add_default_grids(plot)
         self._appendCMapTools(plot)
     else:
         self._setData(rr, plot)
     plot.request_redraw()
     return plot
Пример #34
0
    def _create_window(self):
        self._create_data()
        x = self.x_values[:self.current_index]
        y = self.y_values[:self.current_index]

        plot = create_line_plot((x, y), color="red", width=2.0)
        plot.padding = 50
        plot.fill_padding = True
        plot.bgcolor = "white"
        left, bottom = add_default_axes(plot)
        hgrid, vgrid = add_default_grids(plot)
        bottom.tick_interval = 2.0
        vgrid.grid_interval = 2.0

        self.plot = plot
        plot.tools.append(PanTool(component=plot))
        plot.overlays.append(
            ZoomTool(component=plot, tool_mode="box", always_on=False))

        self.timer = Timer(50.0, self.onTimer)
        return Window(self, -1, component=plot)
Пример #35
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 = linspace(low, high, numpoints + 1)
        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",
                           font='modern 14',
                           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)

        # This label uses label_style='bubble'.
        label4 = DataLabel(component=plot, data_point=(x[60], y[60]),
                           border_padding=10,
                           marker_color="red",
                           marker_size=3,
                           label_position=(20, 50),
                           label_style='bubble',
                           label_text="Something interesting",
                           label_format="at x=%(x).2f, y=%(y).2f",
                           font='modern 18',
                           bgcolor=(1, 1, 0.75, 1),
                          )
        plot.overlays.append(label4)
        tool4 = DataLabelTool(label4, drag_button="right",
                              auto_arrow_root=True)
        label4.tools.append(tool4)

        # Another 'bubble' label.  This one sets arrow_min_length=20, so
        # the arrow is not drawn when the label is close to the data point.
        label5 = DataLabel(component=plot, data_point=(x[65], y[65]),
                           border_padding=10,
                           marker_color="green",
                           marker_size=4,
                           show_label_coords=False,
                           label_style='bubble',
                           label_position=(25, 5),
                           label_text="Label with\narrow_min_length=20",
                           border_visible=False,
                           arrow_min_length=20,
                           font='modern 14',
                           bgcolor=(0.75, 0.75, 0.75, 1),
                          )
        plot.overlays.append(label5)
        tool5 = DataLabelTool(label5, drag_button="right",
                              auto_arrow_root=True)
        label5.tools.append(tool5)

        container.add(plot)

        return container
Пример #36
0
    def __init__(self, smaps, *args, **kwargs):
        super(MyPlot, self).__init__(*args, **kwargs)

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

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

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

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

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

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

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

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

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

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

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

        self.plot = container
Пример #37
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
Пример #38
0
    def _create_Container(self):

        #creating dict of plots and the broadcaster
        plots = {}
        broadcaster = BroadcasterTool()

        #=====================first container===========================

        #first plot
        #index = linspace(-2*pi,2*pi,1000)
        plot = create_line_plot((self.timestamp, self.e), color = "black", index_bounds=(self.xmin, self.xmax), value_bounds = (self.ymin, self.ymax))
        plot.bgcolor = "white"
        plot.border_visible = True
        value_mapper = plot.value_mapper
        index_mapper = plot.index_mapper
        add_default_grids(plot)
        add_default_axes(plot)

        self.sync_trait("xmin", index_mapper.range, "_low_value")
        self.sync_trait("xmax", index_mapper.range, "_high_value")
        self.sync_trait("ymin", value_mapper.range, "_low_value")
        self.sync_trait("ymax", value_mapper.range, "_high_value")
        
       
        # range selection
        self.rangeselect = RangeSelection(plot, left_button_selects = False, auto_handle_event = False)
        plot.active_tool = self.rangeselect
        plot.overlays.append(RangeSelectionOverlay(component=plot))
        self.rangeselect.on_trait_change(self.on_selection_changed, "selection")

        #adds plot to the container
        self.container.add(plot)

        # second plot
        index2 = linspace(-5*pi,4*pi,1000)
        plot = create_line_plot((self.timestamp, self.a2), color = "red", index_bounds=(self.xmin, self.xmax), value_bounds = (self.ymin, self.ymax))
        print plot
        plot.value_mapper = value_mapper
        value_mapper.range.add(plot.value)
        plot.index_mapper = index_mapper
        index_mapper.range.add(plot.index)

        # Create a pan tool and give it a reference to the plot
        pan = PanTool(plot, drag_button="left")
        broadcaster.tools.append(pan)

        # allows to zoom
        zoom = ZoomTool(plot, tool_mode="box", always_on = False, visible = True)
        plot.overlays.append(zoom)


        #adds plot to the container
        self.container.add(plot)

        # appends broadcaster to the container
        self.container.tools.append(broadcaster)

        # title of the container
        self.container.overlays.append(PlotLabel("Plotting of the Normalized SkinTemp and CGM Timeseries ", component=self.container, overlay_position = "top"))

        #==============end of first container===========================

        #====================second container===========================

        #first plot2
        
        plot2 = create_line_plot((self.c, self.d), color = "blue", index_bounds=(self.rangeXMin, self.rangeXMax), value_bounds = (self.y3, self.y4))
        plot2.bgcolor = "white"
        plot2.border_visible = True
        #plot2.value_mapper = value_mapper # the plot uses the same index and
        #plot2.index_mapper = index_mapper # value like the plots of container1
        self.sync_trait("rangeXMin", plot2.index_mapper.range, "low", False)
        self.sync_trait("rangeXMax", plot2.index_mapper.range, "high", False)


        plot2.index_mapper.range.low = 0
        plot2.index_mapper.range.high = 10000

        plot2.value_mapper.range.low = 0
        plot2.value_mapper.range.high = 1
    
        value_mapper.range.add(plot2.value)
        index_mapper.range.add(plot2.index)
        add_default_grids(plot2)
        add_default_axes(plot2)

        #adds plot to the container
        self.container2.add(plot2)

        # title of the container
        self.container2.overlays.append(PlotLabel("R-Squared Correlation", component=self.container, overlay_position = "top"))

        index_mapper.on_trait_change(self.on_mapper_updated, "updated")
Пример #39
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
Пример #40
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
Пример #41
0
def _create_plot_component():

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

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

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

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

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

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

    container = VPlotContainer(bgcolor = "lightblue",
                               spacing = 20,
                               padding = 50,
                               fill_padding=False)
    container.add(vol_plot)
    container.add(price_plot)
    container.overlays.append(PlotLabel("Financial Plot",
                                        component=container,
                                        #font="Times New Roman 24"))
                                       font="Arial 24"
                                        ))
    return container
Пример #42
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
Пример #43
0
    def _create_plot(self):

        # count data
        if len(self.df) > 0:
            self.indexes = np.arange(len(self.df.date_time))
            time_ds = ArrayDataSource(self.indexes)
            vol_ds = ArrayDataSource(self.df.volumn.values, sort_order="none")
            xmapper = LinearMapper(range=DataRange1D(time_ds))
            vol_mapper = LinearMapper(range=DataRange1D(vol_ds))

            ####################################################################
            # create volumn plot
            vol_plot = BarPlot(index=time_ds, value=vol_ds,
                               index_mapper=xmapper,
                               value_mapper=vol_mapper,
                               line_color="transparent",
                               fill_color="blue",
                               bar_width=0.6,
                               antialias=False,
                               height=100,
                               resizable="h",
                               origin="bottom left",
                               bgcolor="white",
                               border_visible=True
                               )

            vol_plot.padding = 30
            vol_plot.padding_left = 40
            vol_plot.tools.append(
                PanTool(vol_plot, constrain=True, constrain_direction="x"))
            add_default_grids(vol_plot)
            add_default_axes(vol_plot)

            #print vol_plot.index_mapper.range.high
            #print vol_plot.value_mapper.range.low, vol_plot.value_mapper.range.high
            self.vol_plot = vol_plot
            self.container.add(vol_plot)

            ####################################################################
            ## Create price plot

            sorted_vals = np.vstack(
                (self.df.open, self.df.high, self.df.low, self.df.close))
            sorted_vals.sort(0)
            __bool = self.df.close.values - self.df.open.values
            self.up_boolean = __bool >= 0
            self.down_boolean = np.invert(self.up_boolean)

            pd = ArrayPlotData(
                up_index=self.indexes[self.up_boolean],
                up_min=sorted_vals[0][self.up_boolean],
                up_bar_min=sorted_vals[1][self.up_boolean],
                up_bar_max=sorted_vals[2][self.up_boolean],
                up_max=sorted_vals[3][self.up_boolean],
                down_index=self.indexes[self.down_boolean],
                down_min=sorted_vals[0][self.down_boolean],
                down_bar_min=sorted_vals[1][self.down_boolean],
                down_bar_max=sorted_vals[2][self.down_boolean],
                down_max=sorted_vals[3][self.down_boolean],
                volumn=self.df.volumn.values,
                index=self.indexes
            )

            price_plot = Plot(pd)

            up_plot = price_plot.candle_plot(
                ("up_index", "up_min", "up_bar_min", "up_bar_max", "up_max"),
                color=color_red,
                bgcolor="azure",
                bar_line_color="black",
                stem_color="black",
                end_cap=False)[0]

            down_plot = price_plot.candle_plot(
                ("down_index", "down_min", "down_bar_min",
                 "down_bar_max", "down_max"),
                color=color_green,
                bar_line_color="black",
                stem_color="black",
                end_cap=False)[0]

            price_plot.fill_padding = True
            price_plot.padding = 30
            price_plot.padding_left = 40

            price_plot.tools.append(ZoomTool(component=price_plot, tool_mode="box", zoom_factor=1.2, always_on=False))
            price_plot.tools.append(PanTool(price_plot, drag_button="left"))
            price_plot.tools.append(
                XYTool(price_plot, callback=self._update_ohlc))  # get data
            self._add_line_tool(up_plot)
            self._add_line_tool(down_plot)
            price_plot.range2d = self._compute_range2d()

            price_plot.index_mapper = vol_plot.index_mapper  # maper vol_plot and price_plot
            self.price_plot = price_plot

            self.container.add(price_plot)
Пример #44
0
def _create_plot_component():

    container = OverlayPlotContainer(padding=60,
                                     fill_padding=True,
                                     use_backbuffer=True,
                                     border_visible=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)
        if i == 0:
            add_default_grids(plot)
            left_axis, _ = add_default_axes(plot)
            left_axis.title = "Bessel j0, j2, j3"
        elif i != 1:
            # Map correctly j2 and j3 on the first plot's axis:
            plot0 = plots["Bessel j_0"]
            plot.index_mapper = plot0.index_mapper
            plot.value_mapper = plot0.value_mapper
            plot0.value_mapper.range.add(plot.value)

        # Create a pan/zoom 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. Do it only for each independent set of axis_mappers:
        if i in [0, 1]:
            pan = PanTool(component=plot)
            broadcaster.tools.append(pan)

            zoom = ZoomTool(component=plot)
            broadcaster.tools.append(zoom)

        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)
    axis.title = "Bessel j1"

    # Add the broadcast tool to one of the renderers: adding it to the
    # container instead breaks the box mode of the ZoomTool:
    plot0 = plots["Bessel j_0"]
    plot0.tools.append(broadcaster)

    # Create a legend, with tools to move it around and highlight renderers:
    legend = Legend(component=container, padding=10, align="ur")
    legend.tools.append(LegendTool(legend, drag_button="right"))
    legend.tools.append(LegendHighlighter(legend))
    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
Пример #45
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
Пример #46
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 = linspace(low, high, numpoints + 1)
        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",
                           font='modern 14',
                           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)

        # This label uses label_style='bubble'.
        label4 = DataLabel(
            component=plot,
            data_point=(x[60], y[60]),
            border_padding=10,
            marker_color="red",
            marker_size=3,
            label_position=(20, 50),
            label_style='bubble',
            label_text="Something interesting",
            label_format="at x=%(x).2f, y=%(y).2f",
            font='modern 18',
            bgcolor=(1, 1, 0.75, 1),
        )
        plot.overlays.append(label4)
        tool4 = DataLabelTool(label4,
                              drag_button="right",
                              auto_arrow_root=True)
        label4.tools.append(tool4)

        # Another 'bubble' label.  This one sets arrow_min_length=20, so
        # the arrow is not drawn when the label is close to the data point.
        label5 = DataLabel(
            component=plot,
            data_point=(x[65], y[65]),
            border_padding=10,
            marker_color="green",
            marker_size=4,
            show_label_coords=False,
            label_style='bubble',
            label_position=(25, 5),
            label_text="Label with\narrow_min_length=20",
            border_visible=False,
            arrow_min_length=20,
            font='modern 14',
            bgcolor=(0.75, 0.75, 0.75, 1),
        )
        plot.overlays.append(label5)
        tool5 = DataLabelTool(label5,
                              drag_button="right",
                              auto_arrow_root=True)
        label5.tools.append(tool5)

        container.add(plot)

        return container
def _create_plot_component():

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

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

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

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

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

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

    container = VPlotContainer(bgcolor="lightblue",
                               spacing=20,
                               padding=50,
                               fill_padding=False)
    container.add(vol_plot)
    container.add(price_plot)
    container.overlays.append(
        PlotLabel(
            "Financial Plot",
            component=container,
            #font="Times New Roman 24"))
            font="Arial 24"))
    return container
Пример #48
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
Пример #49
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
Пример #50
0
def _create_plot_component():
    container = OverlayPlotContainer(padding = 50, fill_padding = True,
        bgcolor = "lightgray", use_backbuffer=True)

    fprefix = './test_data/CEN184/'

    filename1 = fprefix + 'THL_2012-03-21_18-40-42_000.dat'
    filename2  = fprefix + 'THL_2012-03-21_18-44-42_000.dat'
    fprefix = './test_data/CEN111/'
    filename3 = fprefix + 'THL_2011-07-09_15-02-54_000.dat'
    ioreader = HekaIO(filename3)

    #read a block
    blo = ioreader.read_block(group = 2)

    #protocol stuff
    f = open(filename1)
    head = BundleHeader(f)
    head.load(f)
    bi = head.oBundleItems[2]
    pgf = PGFFile(f,bi)

    value_mapper = None
    index_mapper = None
    plots = {}

    firstplot = True
    for seg in blo.segments:
        #prococol building
        for a_sig in seg.analogsignals:
            x = array(a_sig.times)
            y = array(a_sig)
            ch = int(a_sig.annotations['trSourceChannel'])
            plot = create_line_plot((x,y), width=0.5,color=tuple(COLOR_PALETTE[ch]))
            plot.index.sort_order = "ascending"
            plot.bgcolor = "white"
            plot.border_visible = True

            #code for protocols

            print "###########################"
            st_rec = pgf.tree['children'][a_sig.annotations['pgf_index']]['contents']
            se_rec = pgf.tree['children'][a_sig.annotations['pgf_index']]['children'][0]['children'][1]['contents']
            for key in ['stMark','stDataStartSegment','stDataStartTime']:
                print key+ ' ' +str(st_rec.__dict__[key])
            for key in ['seVoltageIncMode','seDuration','seDurationIncMode','seVoltage',]:
                print key+' '+str(se_rec.__dict__[key])
            for key in ['pgf_index','trTraceCount','trAdcChannel','trSourceChannel','swStimCount']:

                print "%s:%s"%(key,a_sig.annotations[key])
                #se_index = int(seg.annotations['seSeriesCount']) -1
                #sw_index = int(a_sig.annotations['swSweepCount']) -1
                #st_index = int(a_sig.annotations['swStimCount']) -1
            #print pgf.tree['children'][se_index]['children'][st_index]['children'][1]['contents'].seVoltage
            if not firstplot:
                plot.value_mapper = value_mapper
                value_mapper.range.add(plot.value)
                plot.index_mapper = index_mapper
                index_mapper.range.add(plot.index)
            else:
                value_mapper = plot.value_mapper
                index_mapper = plot.index_mapper
                add_default_grids(plot)
                add_default_axes(plot)
                plot.index_range.tight_bounds = False
                plot.index_range.refresh()
                plot.value_range.tight_bounds = False
                plot.value_range.refresh()
                plot.tools.append(PanTool(plot))
                # The ZoomTool tool is stateful and allows drawing a zoom
                # box to select a zoom region.
                zoom = ZoomTool(plot, tool_mode="box", always_on=False)
                plot.overlays.append(zoom)
                # The DragZoom tool just zooms in and out as the user drags
                # the mouse vertically.
                dragzoom = DragZoom(plot, drag_button="right")
                plot.tools.append(dragzoom)
                # 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"))
                #print a_sig.annotations
                plot.overlays.append(legend)
                firstplot = False
            container.add(plot)
            plots["sweep %s"%a_sig.annotations['trLabel'][:4]] = plot
            # Set the list of plots on the legend
    legend.plots = plots
    # Add the title at the top
    container.overlays.append(PlotLabel(blo.annotations['grLabel'],
        component=container,
        font = "swiss 16",
        overlay_position="top"))
    # Add the traits inspector tool to the container
    container.tools.append(TraitsTool(container))

    return container
Пример #51
0
def _create_plot_component():
	container = GridContainer(padding=40, fill_padding=True,
		bgcolor="lightgray", use_backbuffer=True,
		shape=(3,3), spacing=(10,10))

	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-5,90))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Roll (degrees)", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-5,90))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Pitch (degrees)", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-5,365))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Yaw (degrees)", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-100,100))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Gyro X", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-100,100))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Gyro Y", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-100,100))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Gyro Z", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)
	
	x = arange(100)
	y = arange(100)
	plot = create_line_plot((x,y), color="red", width=2.0, index_bounds=(-5,100), value_bounds=(-1,35))
	plot.padding = 50
	plot.fill_padding = True
	plot.bgcolor = "white"
	left, bottom = add_default_axes(plot, vtitle="Battery Voltage (V)", htitle="Time (s)")
	hgrid, vgrid = add_default_grids(plot)
	bottom.tick_interval = 20.0
	vgrid.grid_interval = 10.0
	container.add(plot)

	return container
Пример #52
0
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
Пример #53
0
    def change_plot(self, indices, x_scale=None, y_scale=None):
        global XY_DATA
        self.plot_indices = indices
        self.container = self.create_container()
        self.high_step = 1  #float(max(self.plot_data[0][:, 0]))
        self.low_step = 0
        self.container.data = capi.ArrayPlotData()
        self.time_data_labels = {}
        if len(indices) == 0:
            return
        self._refresh = 1
        XY_DATA = []
        x_scale, y_scale = self.get_axis_scales(x_scale, y_scale)

        # loop through plot data and plot it
        overlays_plotted = False
        fnams = []
        for d in range(len(self.plot_data)):

            if not self.runs_shown[d]:
                continue

            # The legend entry for each file is one of the following forms:
            #   1) [file basename] VAR
            #   2) [file basename:] VAR variables
            # depending on if variabes were perturbed for this run.
            variables = self.variables[d]
            if len(variables) > 30:
                variables = ", ".join(variables.split(",")[:-1])
            if variables:
                variables = ": {0}".format(variables)

            self.time_data_labels[d] = []
            ti = self.find_time_index()
            mheader = self._mheader()
            xname = mheader[self.x_idx]
            self.y_idx = getidx(mheader, mheader[indices[0]])

            # indices is an integer list containing the columns of the data to
            # be plotted. The indices are wrt to the FIRST file in parsed, not
            # necessarily the same for every file. Here, we loop through the
            # indices, determine the name from the first file's header and
            # find the x and y index in the file of interest
            fnam, header = self.get_info(d)
            if fnam in fnams:
                fnam += "-{0}".format(len(fnams))
            fnams.append(fnam)
            for i, idx in enumerate(indices):
                yname = mheader[idx]

                # get the indices for this file
                xp_idx = getidx(header, xname)
                yp_idx = getidx(header, yname)
                if xp_idx is None or yp_idx is None:
                    continue

                # tjfulle: x and y should always be x and disp, z is the color
                x = self.plot_data[d][:, xp_idx] * x_scale
                y = self.plot_data[d][:, yp_idx] * y_scale
                z = self.plot_data[d][:, yp_idx]
                if self.nfiles() - 1 or self.overlay_plot_data:
                    entry = "({0}) {1}{2}".format(fnam, yname, variables)
                else:
                    entry = "{0} {1}".format(yname, variables)
                self.create_plot(x, y, z, entry)
                XY_DATA.append(
                    Namespace(key=fnam,
                              xname=xname,
                              x=x,
                              yname=yname,
                              y=y,
                              lw=1))

                # create point marker
                xp = self.plot_data[d][ti, xp_idx] * x_scale
                yp = self.plot_data[d][ti, yp_idx] * y_scale
                #self.create_data_label(xp, yp, d, yp_idx)

                if not overlays_plotted:
                    # plot the overlay data
                    overlays_plotted = True
                    ii = i + 1
                    for fnam, head in self.overlay_headers.items():
                        # get the x and y indeces corresponding to what is
                        # being plotted
                        xo_idx = getidx(head, xname)
                        yo_idx = getidx(head, yname)
                        if xo_idx is None or yo_idx is None:
                            continue
                        xo = self.overlay_plot_data[fnam][:, xo_idx] * x_scale
                        zo = self.overlay_plot_data[fnam][:, yo_idx] * y_scale
                        # legend entry
                        entry = "({0}) {1}".format(fnam, head[yo_idx])
                        _i = d + len(self.plot_data) + 3
                        self.create_plot(xo, y, zo, entry)
                        XY_DATA.append(
                            Namespace(key=fnam,
                                      xname=xname,
                                      x=xo,
                                      yname=yname,
                                      y=yo,
                                      lw=3))
                        ii += 1
                        continue

        capi.add_default_grids(self.container)
        capi.add_default_axes(self.container, htitle=mheader[self.x_idx])

        self.container.index_range.tight_bounds = False
        self.container.index_range.refresh()
        self.container.value_range.tight_bounds = False
        self.container.value_range.refresh()

        self.container.tools.append(ctapi.PanTool(self.container))

        zoom = ctapi.ZoomTool(self.container, tool_mode="box", always_on=False)
        self.container.overlays.append(zoom)

        dragzoom = ctapi.DragZoom(self.container, drag_button="right")
        self.container.tools.append(dragzoom)

        self.container.legend.visible = True

        self.container.invalidate_and_redraw()
        return
Пример #54
0
    def _create_plot(self):

        # count data
        if len(self.df) > 0:
            self.indexes = np.arange(len(self.df.date_time))
            time_ds = ArrayDataSource(self.indexes)
            vol_ds = ArrayDataSource(self.df.volumn.values, sort_order="none")
            xmapper = LinearMapper(range=DataRange1D(time_ds))
            vol_mapper = LinearMapper(range=DataRange1D(vol_ds))

            ####################################################################
            # create volumn plot
            vol_plot = BarPlot(
                index=time_ds,
                value=vol_ds,
                index_mapper=xmapper,
                value_mapper=vol_mapper,
                line_color="transparent",
                fill_color="blue",
                bar_width=0.6,
                antialias=False,
                height=100,
                resizable="h",
                origin="bottom left",
                bgcolor="white",
                border_visible=True,
            )

            vol_plot.padding = 30
            vol_plot.padding_left = 40
            vol_plot.tools.append(PanTool(vol_plot, constrain=True, constrain_direction="x"))
            add_default_grids(vol_plot)
            add_default_axes(vol_plot)

            # print vol_plot.index_mapper.range.high
            # print vol_plot.value_mapper.range.low, vol_plot.value_mapper.range.high
            self.vol_plot = vol_plot
            self.container.add(vol_plot)

            ####################################################################
            ## Create price plot

            sorted_vals = np.vstack((self.df.open, self.df.high, self.df.low, self.df.close))
            sorted_vals.sort(0)
            __bool = self.df.close.values - self.df.open.values
            self.up_boolean = __bool >= 0
            self.down_boolean = np.invert(self.up_boolean)

            pd = ArrayPlotData(
                up_index=self.indexes[self.up_boolean],
                up_min=sorted_vals[0][self.up_boolean],
                up_bar_min=sorted_vals[1][self.up_boolean],
                up_bar_max=sorted_vals[2][self.up_boolean],
                up_max=sorted_vals[3][self.up_boolean],
                down_index=self.indexes[self.down_boolean],
                down_min=sorted_vals[0][self.down_boolean],
                down_bar_min=sorted_vals[1][self.down_boolean],
                down_bar_max=sorted_vals[2][self.down_boolean],
                down_max=sorted_vals[3][self.down_boolean],
                volumn=self.df.volumn.values,
                index=self.indexes,
            )

            price_plot = Plot(pd)

            up_plot = price_plot.candle_plot(
                ("up_index", "up_min", "up_bar_min", "up_bar_max", "up_max"),
                color=color_red,
                bgcolor="azure",
                bar_line_color="black",
                stem_color="black",
                end_cap=False,
            )[0]

            down_plot = price_plot.candle_plot(
                ("down_index", "down_min", "down_bar_min", "down_bar_max", "down_max"),
                color=color_green,
                bar_line_color="black",
                stem_color="black",
                end_cap=False,
            )[0]

            price_plot.fill_padding = True
            price_plot.padding = 30
            price_plot.padding_left = 40

            price_plot.tools.append(ZoomTool(component=price_plot, tool_mode="box", zoom_factor=1.2, always_on=False))
            price_plot.tools.append(PanTool(price_plot, drag_button="left"))
            price_plot.tools.append(XYTool(price_plot, callback=self._update_ohlc))  # get data
            self._add_line_tool(up_plot)
            self._add_line_tool(down_plot)
            price_plot.range2d = self._compute_range2d()

            price_plot.index_mapper = vol_plot.index_mapper  # maper vol_plot and price_plot
            self.price_plot = price_plot

            self.container.add(price_plot)