コード例 #1
0
ファイル: embedding_in_wx.py プロジェクト: jtomase/matplotlib
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
コード例 #2
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.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 GetToolBar(self):
        # You will need to override GetToolBar if you are using an 
        # unmanaged toolbar in your frame
        return self.toolbar
コード例 #3
0
class icCanvasPanel(wx.Panel):
    def __init__(self, parent, id=-1, pos=(-1, -1), size=(-1, -1)):
        wx.Panel.__init__(self, parent, id, pos, size)
        self.count = 0

        self.SetBackgroundColour(wx.NamedColor('WHITE'))
        self.figure = Figure()

        # ---
        dd = 10

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

        self.axes1 = self.figure.add_subplot(111)

        yy = pylab.arrayrange(len(dates) * 1.0)
        majorTick = HourLocator(range(0, 25, 1), tz=tz)

        ysq = [y * y / dd for y in yy]
        line = self.axes1.plot_date(dates, ysq, tz=tz)

        self.axes1.xaxis.set_major_locator(majorTick)
        self.axes1.set_xlabel('Time (s)')
        self.axes1.set_ylabel('Price 2 ($)')

        #
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.canvas.mpl_connect('motion_notify_event', self.mouse_move)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)

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

        self.sizer.Add(self.toolbar, 0, wx.EXPAND)
        self.toolbar.update()
        self.statusBar = wx.StatusBar(self, -1)
        self.statusBar.SetFieldsCount(1)
        self.sizer.Add(self.statusBar, 0, wx.EXPAND)

        self.Fit()

        # --- Обработчики событий
        self.Bind(wx.EVT_PAINT, self.OnPaint)

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

    def mouse_move(self, event):
        self.draw_cursor(event)

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        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 OnButton(self, evt):
        """
        """
        dd = 20
        t = arange(0.0, 3.0, 1.0 / dd)
        s = [10 + y * y / dd + self.count for y in xrange(0, 3 * dd)]
        self.count += 5
        self.axes.lines.pop(0)

        line, = self.axes.plot(t, s, 'r:d')
        line.set_markersize(5)
        self.Refresh()
        evt.Skip()

    def OnPaint(self, event):
        self.erase_cursor()
        try:
            del self.lastInfo
        except AttributeError:
            pass
        self.canvas.draw()
        event.Skip()

    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
        self.statusBar.SetStatusText('Time=%f  Price=%f' % (time, price), 0)

    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
コード例 #4
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)
コード例 #5
0
ファイル: matplot.py プロジェクト: MarkusIppy/libmut
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