Esempio n. 1
0
class PlotFigure(Frame):

    def __init__(self):
        Frame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5,4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = BoxSizer(VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, LEFT|TOP|GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, GROW)
        self.SetSizer(sizer)
        self.Fit()
        EVT_TIMER(self, TIMER_ID, self.onTimer)

    def init_plot_data(self):
        a = self.fig.add_subplot(111)
        self.ind = numpy.arange(60)
        tmp = []
        for i in range(60):
            tmp.append(numpy.sin((self.ind+i)*numpy.pi/15))
        self.X = numpy.array(tmp)
        self.lines = a.plot(self.X[:,0],'o')
        self.count = 0

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar

    def onTimer(self, evt):
        self.count += 1
        if self.count >= 60: self.count = 0
        self.lines[0].set_data(self.ind, self.X[:,self.count])
        self.canvas.draw()
        self.canvas.gui_repaint()
Esempio n. 2
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        #self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def plot(ecg1, ecg2, marks=None):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        if marks == None:
            self.axes.plot(ecg1)

    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 3
0
class PlotFigure(wxFrame):
    def __init__(self):
        wxFrame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wxLEFT | wxTOP | wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wxGROW)
        self.SetSizer(sizer)
        self.Fit()

    def plot_data(self):
        # Use ths line if using a toolbar
        a = self.figmgr.add_subplot(111)

        # Or this one if there is no toolbar
        #a = Subplot(self.fig, 111)

        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, s)
        a.plot(t, c)
        self.toolbar.update()

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar
Esempio n. 4
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool = self.toolbar.FindById(self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(self.toolbar._NTB2_ZOOM)

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        ecg1 += (ecg2.max() - ecg2.min())

        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()

    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin

    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 5
0
class icPlotPanel(wx.Panel):
    """
    """
    def __init__(self,
                 parent,
                 id=-1,
                 pos=(-1, -1),
                 size=(-1, -1),
                 style=0,
                 bWxAgg=False):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)

        if bWxAgg:
            self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        else:
            self.canvas = FigureCanvasWx(self, -1, self.fig)

        self.canvas.mpl_connect('motion_notify_event', self.OnMouseMove)
        self.canvas.mpl_connect('button_press_event', self.OnMouseLeftDown)

        self.toolbar = icPloterToolbar(self.canvas)
        self.toolbar.Realize()
        self.parent = parent
        self.legendLst = []

        # --- Атрибуты курсора
        #   Положение курсора
        self._cursor = None
        #   Значение курсора
        self._cursorVal = None
        #   Статический курсор - значение обновляется только при нажантии
        #   левой кнопки мыши
        self._statCursor = None

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Описание обработчиков
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        # --- Инициализация графика
        self.init_graph()

    def draw_cursor(self, event):
        """
        event is a MplEvent.  Draw a cursor over the axes
        """
        if event.inaxes is None:
            self.erase_cursor()
            try:
                del self.lastInfo
            except AttributeError:
                pass
            return

        canvas = self.canvas
        figheight = canvas.figure.bbox.height()
        ax = event.inaxes
        left, bottom, width, height = ax.bbox.get_bounds()
        bottom = figheight - bottom
        top = bottom - height
        right = left + width
        x, y = event.x, event.y
        y = figheight - y

        dc = wx.ClientDC(canvas)
        dc.SetLogicalFunction(wx.XOR)
        wbrush = wx.Brush(wx.Colour(255, 255, 255), wx.TRANSPARENT)
        wpen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID)
        dc.SetBrush(wbrush)
        dc.SetPen(wpen)

        dc.ResetBoundingBox()
        dc.BeginDrawing()

        x, y, left, right, bottom, top = [
            int(val) for val in x, y, left, right, bottom, top
        ]

        self.erase_cursor()
        line1 = (x, bottom, x, top)
        line2 = (left, y, right, y)
        self.lastInfo = line1, line2, ax, dc
        dc.DrawLine(*line1)  # draw new
        dc.DrawLine(*line2)  # draw new
        dc.EndDrawing()

        time, price = event.xdata, event.ydata

        try:
            tm = str(num2date(time))[:16]
        except:
            tm = time

        self._cursor = (time, price)
        self._cursorVal = (tm, price)

    def erase_cursor(self):
        try:
            lastline1, lastline2, lastax, lastdc = self.lastInfo
        except AttributeError:
            pass
        else:
            lastdc.DrawLine(*lastline1)  # erase old
            lastdc.DrawLine(*lastline2)  # erase old

    def GetToolBar(self):
        """
        You will need to override GetToolBar if you are using an unmanaged toolbar in your frame.
        """
        return self.toolbar

    def GetCursorPos(self):
        """
        Возвращает положение курсора.
        """
        return self._cursor

    def GetCursorVal(self):
        """
        Возвращает значение курсора - временная координата приведена в
        читаемый вид - YYYY-MM-DD HH:MM:SS.
        """
        return self._cursorVal

    def GetStaticCursor(self):
        """
        Возвращает значение статического курсора - значение которого обновляется
        только при нажантии левой кнопки мыши.
        """
        return self._statCursor

    def init_graph(self):
        """
        Инициализация графика.
        """
        self.canvas.figure.set_facecolor('#f5f5f5')
        self.subplot = a = self.fig.add_subplot(111)

        a.grid(True)
        self.toolbar.update()

    def OnMouseMove(self, evt):
        """
        """
        self.draw_cursor(evt)

    def OnMouseLeftDown(self, evt):
        """
        """
        self._statCursor = self.GetCursorPos()

    def OnPaint(self, evt):
        """
        """
        self.erase_cursor()
        try:
            del self.lastInfo
        except AttributeError:
            pass

        self.canvas.draw()
        evt.Skip()

    def plot_data(self):
        a = self.subplot
        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, c, 'r:o')

    def add_plot_date(self,
                      dates,
                      values,
                      format=None,
                      xlabel=None,
                      ylabel=None,
                      bClear=True,
                      titlePlot='Title',
                      legend='Legend'):
        """
        Наполняет график точками.
        
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type values: C{list | tuple}
        @param values: Список значений.
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type xlabel: C{string}
        @param xlabel: Подпись оси X.
        @type ylabel: C{string}
        @param ylabel: Подпись оси Y.
        @type bClear: C{bool}
        @param bClear: Признак того, что необходимо все предыдущие точки удалить
            из графика.
        @type titlePlot: C{string}
        @param titlePlot: Заголовок.
        @type legend: C{string}
        @param legend: Легенда.
        """
        if bClear:
            self.subplot.lines = []
            self.legendLst = []

        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        majorTick = HourLocator(range(0, 25, 3), tz=tz)

        line = self.subplot.plot_date(dates, values, format, tz=tz)

        self.subplot.xaxis.set_major_locator(majorTick)

        #   Устанавливаем легенду
        self.legendLst.append(legend)
        self.subplot.legend(self.subplot.lines,
                            self.legendLst,
                            'upper right',
                            shadow=True)

    def set_date_plot2(self, date1=None, date2=None):
        """
        """
        # --- Plot2
        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        if not date1:
            date1 = datetime.datetime(2000, 3, 2, 0, tzinfo=tz)
        else:
            date1 = datetime.datetime(date1[0],
                                      date1[1],
                                      date1[2],
                                      date1[3],
                                      tzinfo=tz)

        if not date2:
            date2 = datetime.datetime(2000, 3, 2, 23, tzinfo=tz)
        else:
            date2 = datetime.datetime(date2[0],
                                      date2[1],
                                      date2[2],
                                      date2[3],
                                      tzinfo=tz)

        delta = datetime.timedelta(minutes=20)
        dates = drange(date1, date2, delta)

        dd = 10
        yy = pylab.arrayrange(len(dates) * 1.0)
        ysq = [y * y / dd for y in yy]

        self.add_plot_date(dates,
                           ysq,
                           'bo',
                           'Время',
                           'Цена',
                           legend='Скорость')
        self.add_plot_date(dates, yy, 'r-d', bClear=False)

        labels = self.subplot.get_xticklabels()
        pylab.set(labels, 'rotation', 45, size=10)
Esempio n. 6
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_menubar()

        self.add_toolbar()
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool = self.toolbar.FindById(self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(self.toolbar._NTB2_ZOOM)

        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, event):
        pub.sendMessage("VIEW CLOSED")

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def add_menubar(self):
        """
        Loading and saving will be available in the menu
        """
        menubar = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(ID_LOAD, "&Load", "Load ECG and/or annotation")
        file_menu.Append(ID_MARK, "&Annotate", "Generate new annotation")
        file_menu.Append(ID_SAVE, "&Save", "Save annotations")

        channel_menu = wx.Menu()
        channel_menu.Append(ID_CHANGE_CHANNEL, "&Change Chan 1",
                            "Change channel 1")

        menubar.Append(file_menu, "&File")
        menubar.Append(channel_menu, "&Channel")

        self.SetMenuBar(menubar)

    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        print 'Plotting'
        ecg1, ecg2 = self.remove_overlap(ecg1, ecg2)

        # if zoomed in, maintain x axis zoom
        minx, maxx = self.axes.get_xlim()

        self.axes.clear()
        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

        if maxx != 1.0:  # which is the default without a plot
            self.axes.set_xlim(minx, maxx)

        self.canvas.draw()

    def remove_overlap(self, ecg1, ecg2):
        """
        Adjust baseline of ecg1 so that it doesnt overlap
        with ecg2
        """
        ht_ecg2 = ecg2.max() - ecg2.mean()
        depth_ecg1 = ecg1.mean() - ecg1.min()
        offset = ecg1.mean() - ecg2.mean()
        min_offset = ht_ecg2 + depth_ecg1
        if offset < min_offset:
            ecg1 += min_offset

        return ecg1, ecg2

    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()

    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin

    def OnPaint(self, event):
        self.canvas.draw()
class cls_CalibGraph(wx.Frame):
    def __init__(self, *args, **kwds):

        wx.Frame.__init__(self, None, -1, "Test ReSo - Calibration graphs")

        #        self.fig = Figure((9,8), 75)
        self.fig = Figure()
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

##    def plot_data(self):
##        # Use ths line if using a toolbar
##        a = self.fig.add_subplot(111)
##
##        # Or this one if there is no toolbar
##        #a = Subplot(self.fig, 111)
##
##        t = numpy.arange(0.0,3.0,0.01)
##        s = numpy.sin(2*numpy.pi*t)
##        c = numpy.cos(2*numpy.pi*t)
##        a.plot(t,s)
##        a.plot(t,c)
##        self.toolbar.update()

    def calibGRAPH(self, DateInput, S, h, hmeas, Smeas, Sm, Sr):
        """
        calibGRAPH: GRAPH the computed data and the calibration one, that it h and S
        Use Matplotlib
        _______________________________________________________________________________

        INPUTS
                STATE VARIABLES
                    TS              Time step
                    S               Daily soil moisture
                    Smeas           Daily measured soil moisture
                    h               Daily water level
                    hmeas           Daily measured water level
        ______________________________________________________________________________
        ______________________________________________________________________________
        """

        months = MonthLocator()
        monthsFmt = DateFormatter('%y-%m')

        #__________________Create outputs plots______________________#

        #        figCalib=figure()
        #        figCalib.Title='Calibration graphs'

        ax2 = self.fig.add_subplot(212)
        setp(ax2.get_xticklabels(), fontsize=8)
        setp(ax2.get_yticklabels(), fontsize=8)
        ax2.plot_date(DateInput, h, '-')
        ax2.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))
        labels = ax2.get_yticklabels()
        setp(labels, 'rotation', 90)
        ax2.xaxis.set_major_locator(months)
        ax2.xaxis.set_major_formatter(monthsFmt)
        xlim((DateInput[0], DateInput[len(S) - 1]))
        hmax = hmin = h[0]
        labels = ax2.get_xticklabels()
        setp(labels, 'rotation', 90)
        for i in range(0, len(DateInput)):
            if h[i] > hmax:
                hmax = h[i]
            elif h[i] < hmin:
                hmin = h[i]
        ax2.plot_date(DateInput, hmeas, 'mo', markersize=4)
        if hmeas[0] == -999:
            hmmax = -999
            hmmin = 999
        else:
            hmmax = hmmin = hmeas[0]
        for i in range(0, len(DateInput)):
            if hmeas[i] != -999:
                if hmeas[i] > hmmax:
                    hmmax = h[i]
                if hmeas[i] < hmmin:
                    hmmin = h[i]
        if hmin > hmmin:
            hmin = hmmin
        if hmax < hmmax:
            hmax = hmmax
        ybuffer = 0.1 * (hmax - hmin)
        ylim((hmin - ybuffer, hmax + ybuffer))
        ax2yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
        ylabel('m')
        legend((r'h', r'hmeas'), loc=0)
        leg = gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        setp(ltext, fontsize='small')  # the legend text fontsize
        xlabel(r'Date')
        grid(True)

        ax1 = self.fig.add_subplot(211, sharex=ax2)
        setp(ax1.get_xticklabels(), visible=False)
        setp(ax1.get_yticklabels(), fontsize=8)
        ax1.plot_date(DateInput, S, '-')
        ax1.plot_date(DateInput, Smeas, 'mo', markersize=4)
        legend((r'S', r'Smeas'), loc=0)
        leg = gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        setp(ltext, fontsize='small')  # the legend text fontsize
        #        ybuffer=0.1*(float(Sm)-float(Sr))
        #        ylim((float(Sr) - ybuffer,float(Sm) + ybuffer))
        ylim(0, 1)
        ylabel('mm')
        ax1.yaxis.set_major_formatter(FormatStrFormatter('%1.2f'))
        labels = ax1.get_yticklabels()
        setp(labels, 'rotation', 90)
        grid(True)

#        subplots_adjust(left=0.05, bottom=0.1, right=0.95, top=0.95, wspace=0.1, hspace=0.05)

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar
Esempio n. 8
0
class PlotFigure(wx.Panel):
    def __init__(self, parent, id=-1, pos=(-1, -1), size=(-1, -1), style=0):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Инициализация графика
        self.init_graph()

    def GetToolBar(self):
        """
        You will need to override GetToolBar if you are using an unmanaged toolbar in your frame.
        """
        return self.toolbar

    def init_graph(self):
        """
        Инициализация графика. 
        """
        self.subplot = a = self.fig.add_subplot(111)
        a.set_ylabel(u'Цена ($)\n')
        a.set_xlabel(u'Время')
        self.toolbar.update()

    def plot_data(self):
        a = self.subplot
        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, c, 'r:o')

    def add_plot_date(self,
                      dates,
                      values,
                      format=None,
                      xlabel=None,
                      ylabel=None,
                      bClear=True):
        """
        Наполняет график точками.
        
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type values: C{list | tuple}
        @param values: Список значений.
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type xlabel: C{string}
        @param xlabel: Подпись оси X.
        @type ylabel: C{string}
        @param ylabel: Подпись оси Y.
        @type bClear: C{bool}
        @param bClear: Признак того, что необходимо все предыдущие точки удалить
            из графика.
        """
        if bClear:
            self.subplot.lines = []

        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        majorTick = HourLocator(range(0, 25, 1), tz=tz)

        line, = self.subplot.plot_date(dates, values, format, tz=tz)
        line.set_markersize(3)

        self.subplot.xaxis.set_major_locator(majorTick)
        if xlabel:
            self.subplot.set_xlabel(xlabel)

        if ylabel:
            self.subplot.set_ylabel(ylabel + '\n')

    def set_date_plot2(self, date1=None, date2=None):
        """
        """
        # --- Plot2
        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        date1 = datetime.datetime(2000, 3, 2, 10, tzinfo=tz)
        date2 = datetime.datetime(2000, 3, 2, 15, tzinfo=tz)
        delta = datetime.timedelta(minutes=5)
        dates = drange(date1, date2, delta)

        dd = 10
        yy = pylab.arrayrange(len(dates) * 1.0)
        ysq = [y * y / dd for y in yy]

        self.add_plot_date(dates, ysq, 'b-o', u'Время', u'Цена')
        self.add_plot_date(dates, yy, 'r-d', bClear=False)
Esempio n. 9
0
class Plot(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)

        self.fig = Figure((9,8), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

    def clear(self):
        a = self.fig.add_subplot(111)
        a.clear()
        
    def plot(self, data, labels = [], title = ""):
        #FIXME: what is 111?
        a = self.fig.add_subplot(111)
        a.set_title(title)
        for i in range(0, len(data)):
            d = data[i]
            if i < len(labels):
                l = labels[i]
            else:
                l = "" 
            x = map(lambda x: x[0], d)
            y = map(lambda x: x[1], d)
            a.plot(x,y, marker = None, linestyle = "-", label = l)

        if len(labels) > 0:
            a.legend(loc=2)
        a.set_xlabel("RPM")
        a.set_ylabel("Power/Torque")
        self.toolbar.update()
    def plot_sample_data(self):
        import dyno
        r = dyno.DynoRun()
        r.Load("dustin.csv")

        import smooth
        r.Smooth(smooth.NNA)
        r.Smooth(smooth.box)
        self.plot([r.torque(), r.hp()], ["Torque", "Power"])
        self.toolbar.update()

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an 
        # unmanaged toolbar in your frame
        return self.toolbar