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() EVT_TIMER(self, TIMER_ID, self.onTimer) def init_plot_data(self): a = self.figmgr.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()
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
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
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
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)
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