📄 plot.py
字号:
- All methods except __init__ are private. """ def __init__(self, objects, title='', xLabel='', yLabel= ''): """Creates PlotGraphics object objects - list of PolyXXX objects to make graph title - title shown at top of graph xLabel - label shown on x-axis yLabel - label shown on y-axis """ if type(objects) not in [list,tuple]: raise TypeError, "objects argument should be list or tuple" self.objects = objects self.title= title self.xLabel= xLabel self.yLabel= yLabel def boundingBox(self): p1, p2 = self.objects[0].boundingBox() for o in self.objects[1:]: p1o, p2o = o.boundingBox() p1 = _numpy.minimum(p1, p1o) p2 = _numpy.maximum(p2, p2o) return p1, p2 def scaleAndShift(self, scale=(1,1), shift=(0,0)): for o in self.objects: o.scaleAndShift(scale, shift) def setPrinterScale(self, scale): """Thickens up lines and markers only for printing""" self.printerScale= scale def setXLabel(self, xLabel= ''): """Set the X axis label on the graph""" self.xLabel= xLabel def setYLabel(self, yLabel= ''): """Set the Y axis label on the graph""" self.yLabel= yLabel def setTitle(self, title= ''): """Set the title at the top of graph""" self.title= title def getXLabel(self): """Get x axis label string""" return self.xLabel def getYLabel(self): """Get y axis label string""" return self.yLabel def getTitle(self, title= ''): """Get the title at the top of graph""" return self.title def draw(self, dc): for o in self.objects: #t=_time.clock() # profile info o.draw(dc, self.printerScale) #dt= _time.clock()-t #print o, "time=", dt def getSymExtent(self, printerScale): """Get max width and height of lines and markers symbols for legend""" symExt = self.objects[0].getSymExtent(printerScale) for o in self.objects[1:]: oSymExt = o.getSymExtent(printerScale) symExt = _numpy.maximum(symExt, oSymExt) return symExt def getLegendNames(self): """Returns list of legend names""" lst = [None]*len(self) for i in range(len(self)): lst[i]= self.objects[i].getLegend() return lst def __len__(self): return len(self.objects) def __getitem__(self, item): return self.objects[item]#-------------------------------------------------------------------------------# Main window that you will want to import into your application.class PlotCanvas(wx.Window): """Subclass of a wx.Window to allow simple general plotting of data with zoom, labels, and automatic axis scaling.""" def __init__(self, parent, id = -1, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.DEFAULT_FRAME_STYLE, name= ""): """Constucts a window, which can be a child of a frame, dialog or any other non-control window""" wx.Window.__init__(self, parent, id, pos, size, style, name) self.border = (1,1) self.SetBackgroundColour("white") # Create some mouse events for zooming self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp) self.Bind(wx.EVT_MOTION, self.OnMotion) self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) # set curser as cross-hairs self.SetCursor(wx.CROSS_CURSOR) # Things for printing self.print_data = wx.PrintData() self.print_data.SetPaperId(wx.PAPER_LETTER) self.print_data.SetOrientation(wx.LANDSCAPE) self.pageSetupData= wx.PageSetupDialogData() self.pageSetupData.SetMarginBottomRight((25,25)) self.pageSetupData.SetMarginTopLeft((25,25)) self.pageSetupData.SetPrintData(self.print_data) self.printerScale = 1 self.parent= parent # Zooming variables self._zoomInFactor = 0.5 self._zoomOutFactor = 2 self._zoomCorner1= _numpy.array([0.0, 0.0]) # left mouse down corner self._zoomCorner2= _numpy.array([0.0, 0.0]) # left mouse up corner self._zoomEnabled= False self._hasDragged= False # Drawing Variables self.last_draw = None self._pointScale= 1 self._pointShift= 0 self._xSpec= 'auto' self._ySpec= 'auto' self._gridEnabled= False self._legendEnabled= False self._xUseScopeTicks= False # Fonts self._fontCache = {} self._fontSizeAxis= 10 self._fontSizeTitle= 15 self._fontSizeLegend= 7 # pointLabels self._pointLabelEnabled= False self.last_PointLabel= None self._pointLabelFunc= None self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) # OnSize called to make sure the buffer is initialized. # This might result in OnSize getting called twice on some # platforms at initialization, but little harm done. self.OnSize(None) # sets the initial size based on client size # UNCONDITIONAL, needed to create self._Buffer # SaveFile def SaveFile(self, fileName= ''): """Saves the file to the type specified in the extension. If no file name is specified a dialog box is provided. Returns True if sucessful, otherwise False. .bmp Save a Windows bitmap file. .xbm Save an X bitmap file. .xpm Save an XPM bitmap file. .png Save a Portable Network Graphics file. .jpg Save a Joint Photographic Experts Group file. """ if _string.lower(fileName[-3:]) not in ['bmp','xbm','xpm','png','jpg']: dlg1 = wx.FileDialog( self, "Choose a file with extension bmp, gif, xbm, xpm, png, or jpg", ".", "", "BMP files (*.bmp)|*.bmp|XBM files (*.xbm)|*.xbm|XPM file (*.xpm)|*.xpm|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg", wx.SAVE|wx.OVERWRITE_PROMPT ) try: while 1: if dlg1.ShowModal() == wx.ID_OK: fileName = dlg1.GetPath() # Check for proper exension if _string.lower(fileName[-3:]) not in ['bmp','xbm','xpm','png','jpg']: dlg2 = wx.MessageDialog(self, 'File name extension\n' 'must be one of\n' 'bmp, xbm, xpm, png, or jpg', 'File Name Error', wx.OK | wx.ICON_ERROR) try: dlg2.ShowModal() finally: dlg2.Destroy() else: break # now save file else: # exit without saving return False finally: dlg1.Destroy() # File name has required extension fType = _string.lower(fileName[-3:]) if fType == "bmp": tp= wx.BITMAP_TYPE_BMP # Save a Windows bitmap file. elif fType == "xbm": tp= wx.BITMAP_TYPE_XBM # Save an X bitmap file. elif fType == "xpm": tp= wx.BITMAP_TYPE_XPM # Save an XPM bitmap file. elif fType == "jpg": tp= wx.BITMAP_TYPE_JPEG # Save a JPG file. else: tp= wx.BITMAP_TYPE_PNG # Save a PNG file. # Save Bitmap res= self._Buffer.SaveFile(fileName, tp) return res def PageSetup(self): """Brings up the page setup dialog""" data = self.pageSetupData data.SetPrintData(self.print_data) dlg = wx.PageSetupDialog(self.parent, data) try: if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() # returns wx.PageSetupDialogData # updates page parameters from dialog self.pageSetupData.SetMarginBottomRight(data.GetMarginBottomRight()) self.pageSetupData.SetMarginTopLeft(data.GetMarginTopLeft()) self.pageSetupData.SetPrintData(data.GetPrintData()) self.print_data=data.GetPrintData() # updates print_data finally: dlg.Destroy() def Printout(self, paper=None): """Print current plot.""" if paper != None: self.print_data.SetPaperId(paper) pdd = wx.PrintDialogData() pdd.SetPrintData(self.print_data) printer = wx.Printer(pdd) out = PlotPrintout(self) print_ok = printer.Print(self.parent, out) if print_ok: self.print_data = printer.GetPrintDialogData().GetPrintData() out.Destroy() def PrintPreview(self): """Print-preview current plot.""" printout = PlotPrintout(self) printout2 = PlotPrintout(self) self.preview = wx.PrintPreview(printout, printout2, self.print_data) if not self.preview.Ok(): wx.MessageDialog(self, "Print Preview failed.\n" \ "Check that default printer is configured\n", \ "Print error", wx.OK|wx.CENTRE).ShowModal() self.preview.SetZoom(40) # search up tree to find frame instance frameInst= self while not isinstance(frameInst, wx.Frame): frameInst= frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, "Preview") frame.Initialize() frame.SetPosition(self.GetPosition()) frame.SetSize((600,550)) frame.Centre(wx.BOTH) frame.Show(True) def SetFontSizeAxis(self, point= 10): """Set the tick and axis label font size (default is 10 point)""" self._fontSizeAxis= point def GetFontSizeAxis(self): """Get current tick and axis label font size in points""" return self._fontSizeAxis def SetFontSizeTitle(self, point= 15): """Set Title font size (default is 15 point)""" self._fontSizeTitle= point def GetFontSizeTitle(self): """Get current Title font size in points""" return self._fontSizeTitle def SetFontSizeLegend(self, point= 7): """Set Legend font size (default is 7 point)""" self._fontSizeLegend= point def GetFontSizeLegend(self): """Get current Legend font size in points""" return self._fontSizeLegend def SetEnableZoom(self, value): """Set True to enable zooming.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._zoomEnabled= value def GetEnableZoom(self): """True if zooming enabled.""" return self._zoomEnabled def SetEnableGrid(self, value): """Set True to enable grid.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._gridEnabled= value self.Redraw() def GetEnableGrid(self): """True if grid enabled.""" return self._gridEnabled def SetEnableLegend(self, value): """Set True to enable legend.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._legendEnabled= value self.Redraw() def GetEnableLegend(self): """True if Legend enabled.""" return self._legendEnabled def SetEnablePointLabel(self, value): """Set True to enable pointLabel.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._pointLabelEnabled= value
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -