⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 wxpyplot.py

📁 PyChem是用Python语言编写的多元变量分析软件。它包括一个前端图形界面用于管理和保存试验数据
💻 PY
📖 第 1 页 / 共 4 页
字号:
        return ticks

    _multiples = [(2., scipy.log10(2.)), (5., scipy.log10(5.))]


#-------------------------------------------------------------------------------
#Used to layout the printer page

class plot_printout(wx.wxPrintout):
    """Controls how the plot is made in printing and previewing"""
    # Do not change method names in this class,
    # we have to override wxPrintout methods here!
    def __init__(self, graph):
        """graph is instance of plotCanvas to be printed or previewed"""
        wx.wxPrintout.__init__(self)
        self.graph = graph

    def HasPage(self, page):
        if page == 1:
            return True
        else:
            return False

    def GetPageInfo(self):
        return (0, 1, 1, 1)  #disable page numbers

    def OnPrintPage(self, page):
        dc = FloatDCWrapper(self.GetDC())  # allows using floats for certain functions
##        print "PPI Printer",self.GetPPIPrinter()
##        print "PPI Screen", self.GetPPIScreen()
##        print "DC GetSize", dc.GetSize()
##        print "GetPageSizePixels", self.GetPageSizePixels()
        #Note PPIScreen does not give the correct number
        #Calulate everything for printer and then scale for preview
        PPIPrinter= self.GetPPIPrinter()        #printer dots/inch (w,h)
        #PPIScreen= self.GetPPIScreen()          #screen dots/inch (w,h)
        dcSize= dc.GetSizeTuple()                    #DC size
        pageSize= self.GetPageSizePixels() #page size in terms of pixcels
        clientDcSize= self.graph.GetClientSizeTuple()
        
        #find what the margins are (mm)
        margLeftSize,margTopSize= self.graph.pageSetupData.GetMarginTopLeft()
        margRightSize, margBottomSize= self.graph.pageSetupData.GetMarginBottomRight()

        #calculate offset and scale for dc
        pixLeft= margLeftSize*PPIPrinter[0]/25.4  #mm*(dots/in)/(mm/in)
        pixRight= margRightSize*PPIPrinter[0]/25.4    
        pixTop= margTopSize*PPIPrinter[1]/25.4
        pixBottom= margBottomSize*PPIPrinter[1]/25.4

        plotAreaW= pageSize[0]-(pixLeft+pixRight)
        plotAreaH= pageSize[1]-(pixTop+pixBottom)

        #ratio offset and scale to screen size if preview
        if self.IsPreview():
            ratioW= float(dcSize[0])/pageSize[0]
            ratioH= float(dcSize[1])/pageSize[1]
            pixLeft *= ratioW
            pixTop *= ratioH
            plotAreaW *= ratioW
            plotAreaH *= ratioH
        
        #rescale plot to page or preview plot area
        self.graph._setSize(plotAreaW,plotAreaH)
        
        #Set offset and scale
        dc.SetDeviceOrigin(pixLeft,pixTop)

        #Thicken up pens and increase marker size for printing
        ratioW= float(plotAreaW)/clientDcSize[0]
        ratioH= float(plotAreaH)/clientDcSize[1]
        aveScale= (ratioW+ratioH)/2
        self.graph._setPrinterScale(aveScale)  #tickens up pens for printing

        self.graph._printDraw(dc)
        #rescale back to original
        self.graph._setSize()
        self.graph._setPrinterScale(1)

        return True

# Hack to allow plotting real numbers for the methods listed.
# All others passed directly to DC.
# For Drawing it is used as
# dc = FloatDCWrapper(wx.wxBufferedDC(wx.wxClientDC(self), self._Buffer))
# For printing is is used as
# dc = FloatDCWrapper(self.GetDC()) 
class FloatDCWrapper:
    def __init__(self, aDC):
        self.theDC = aDC
    def DrawLine(self, x1,y1,x2,y2):
        self.theDC.DrawLine(int(x1),int(y1),int(x2),int(y2))
    def DrawText(self, txt, x, y):
        self.theDC.DrawText(txt, int(x), int(y))
    def DrawRotatedText(self, txt, x, y, angle):
        self.theDC.DrawRotatedText(txt, int(x), int(y), angle)
    def SetClippingRegion(self, x, y, width, height):
        self.theDC.SetClippingRegion(int(x), int(y), int(width), int(height))
    def SetDeviceOrigin(self, x, y):
        self.theDC.SetDeviceOrigin(int(x), int(y))
    def __getattr__(self, name):
        return getattr(self.theDC, name)




#---------------------------------------------------------------------------
# if running standalone...
#
#     ...a sample implementation using the above
#


def __test():
    from wxPython.lib.dialogs import wxScrolledMessageDialog

    
    def _draw1Objects():
        # 100 points sin function, plotted as green circles
        data1 = 2.*scipy.pi*scipy.arange(200)/200.
        data1.shape = (100, 2)
        data1[:,1] = scipy.sin(data1[:,0])
        markers1 = PolyMarker(data1, legend='Green Markers', colour='green', marker='circle',size=1)

        # 50 points cos function, plotted as red line
        data1 = 2.*scipy.pi*scipy.arange(100)/100.
        data1.shape = (50,2)
        data1[:,1] = scipy.cos(data1[:,0])
        lines = PolyLine(data1, legend= 'Red Line', colour='red')

        # A few more points...
        pi = scipy.pi
        markers2 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.),
                              (3.*pi/4., -1)], legend='Cross Legend', colour='blue',
                              marker='cross')
        
        return PlotGraphics([markers1, lines, markers2],"Graph Title", "X Axis", "Y Axis")

    def _draw2Objects():
        # 100 points sin function, plotted as green dots
        data1 = 2.*scipy.pi*scipy.arange(200)/200.
        data1.shape = (100, 2)
        data1[:,1] = scipy.sin(data1[:,0])
        line1 = PolyLine(data1, legend='Green Line', colour='green', width=6, style=wx.wxDOT)

        # 50 points cos function, plotted as red dot-dash
        data1 = 2.*scipy.pi*scipy.arange(100)/100.
        data1.shape = (50,2)
        data1[:,1] = scipy.cos(data1[:,0])
        line2 = PolyLine(data1, legend='Red Line', colour='red', width=3, style= wx.wxDOT_DASH)

        # A few more points...
        pi = scipy.pi
        markers1 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.),
                              (3.*pi/4., -1)], legend='Cross Hatch Square', colour='blue', width= 3, size= 6,
                              fillcolour= 'red', fillstyle= wx.wxCROSSDIAG_HATCH,
                              marker='square')

        return PlotGraphics([markers1, line1, line2], "Big Markers with Different Line Styles")

    def _draw3Objects():
        markerList= ['circle', 'dot', 'square', 'triangle', 'triangle_down',
                    'cross', 'plus', 'circle']
        m=[]
        for i in range(len(markerList)):
            m.append(PolyMarker([(2*i+.5,i+.5)], legend=markerList[i], colour='blue',
                              marker=markerList[i]))
        return PlotGraphics(m, "Selection of Markers", "Minimal Axis", "No Axis")

    def _draw4Objects():
        # 25,000 point line
        data1 = scipy.arange(5e5,1e6,10)
        data1.shape = (25000, 2)
        line1 = PolyLine(data1, legend='Wide Line', colour='green', width=5)

        # A few more points...
        markers2 = PolyMarker(data1, legend='Square', colour='blue',
                              marker='square')
        return PlotGraphics([line1, markers2], "25,000 Points", "Value X", "")

    def _draw5Objects():
        # Empty graph with axis defined but no points/lines
        points=[]
        line1 = PolyLine(points, legend='Wide Line', colour='green', width=5)
        return PlotGraphics([line1], "Empty Plot With Just Axes", "Value X", "Value Y")


    class AppFrame(wx.wxFrame):
        def __init__(self, parent, id, title):
            wx.wxFrame.__init__(self, parent, id, title,
                                wx.wxPyDefaultPosition, wx.wxSize(600, 400))

            # Now Create the menu bar and items
            self.mainmenu = wx.wxMenuBar()

            menu = wx.wxMenu()
            menu.Append(200, 'Page Setup...', 'Setup the printer page')
            wx.EVT_MENU(self, 200, self.OnFilePageSetup)
            
            menu.Append(201, 'Print Preview...', 'Show the current plot on page')
            wx.EVT_MENU(self, 201, self.OnFilePrintPreview)
            
            menu.Append(202, 'Print...', 'Print the current plot')
            wx.EVT_MENU(self, 202, self.OnFilePrint)
            
            menu.Append(203, 'Save Plot...', 'Save current plot')
            wx.EVT_MENU(self, 203, self.OnSaveFile)
            
            menu.Append(205, 'E&xit', 'Enough of this already!')
            wx.EVT_MENU(self, 205, self.OnFileExit)
            self.mainmenu.Append(menu, '&File')

            menu = wx.wxMenu()
            menu.Append(206, 'Draw1', 'Draw plots1')
            wx.EVT_MENU(self,206,self.OnPlotDraw1)
            menu.Append(207, 'Draw2', 'Draw plots2')
            wx.EVT_MENU(self,207,self.OnPlotDraw2)
            menu.Append(208, 'Draw3', 'Draw plots3')
            wx.EVT_MENU(self,208,self.OnPlotDraw3)
            menu.Append(209, 'Draw4', 'Draw plots4')
            wx.EVT_MENU(self,209,self.OnPlotDraw4)
            menu.Append(210, 'Draw5', 'Draw plots5')
            wx.EVT_MENU(self,210,self.OnPlotDraw5)

             
            menu.Append(211, '&Redraw', 'Redraw plots')
            wx.EVT_MENU(self,211,self.OnPlotRedraw)
            menu.Append(212, '&Clear', 'Clear canvas')
            wx.EVT_MENU(self,212,self.OnPlotClear)
            menu.Append(213, '&Scale', 'Scale canvas')
            wx.EVT_MENU(self,213,self.OnPlotScale) 
            menu.Append(214, 'Enable &Zoom', 'Enable Mouse Zoom', kind=wx.wxITEM_CHECK)
            wx.EVT_MENU(self,214,self.OnEnableZoom) 
            menu.Append(215, 'Enable &Grid', 'Turn on Grid', kind=wx.wxITEM_CHECK)
            wx.EVT_MENU(self,215,self.OnEnableGrid)
            menu.Append(220, 'Enable &Legend', 'Turn on Legend', kind=wx.wxITEM_CHECK)
            wx.EVT_MENU(self,220,self.OnEnableLegend) 
            menu.Append(225, 'Scroll Up 1', 'Move View Up 1 Unit')
            wx.EVT_MENU(self,225,self.OnScrUp) 
            menu.Append(230, 'Scroll Rt 2', 'Move View Right 2 Units')
            wx.EVT_MENU(self,230,self.OnScrRt)
            menu.Append(235, '&Plot Reset', 'Reset to original plot')
            wx.EVT_MENU(self,235,self.OnReset)

            self.mainmenu.Append(menu, '&Plot')

            menu = wx.wxMenu()
            menu.Append(300, '&About', 'About this thing...')
            wx.EVT_MENU(self, 300, self.OnHelpAbout)
            self.mainmenu.Append(menu, '&Help')

            self.SetMenuBar(self.mainmenu)

            # A status bar to tell people what's happening
            self.CreateStatusBar(1)
            
            self.client = PlotCanvas(self)
            #Create mouse event for showing cursor coords in status bar
            wx.EVT_LEFT_DOWN(self.client, self.OnMouseLeftDown)

        def OnMouseLeftDown(self,event):
            s= "Left Mouse Down at Point: (%.4f, %.4f)" % self.client.GetXY(event)
            self.SetStatusText(s)
            event.Skip()

        def OnFilePageSetup(self, event):
            self.client.PageSetup()
            
        def OnFilePrintPreview(self, event):
            self.client.PrintPreview()
            
        def OnFilePrint(self, event):
            self.client.Printout()
            
        def OnSaveFile(self, event):
            self.client.SaveFile()

        def OnFileExit(self, event):
            self.Close()

        def OnPlotDraw1(self, event):
            self.resetDefaults()
            self.client.Draw(_draw1Objects())
        
        def OnPlotDraw2(self, event):
            self.resetDefaults()
            self.client.Draw(_draw2Objects())
        
        def OnPlotDraw3(self, event):
            self.resetDefaults()
            self.client.SetFont(wx.wxFont(10,wx.wxSCRIPT,wx.wxNORMAL,wx.wxNORMAL))
            self.client.SetFontSizeAxis(20)
            self.client.SetFontSizeLegend(12)
            self.client.SetXSpec('min')
            self.client.SetYSpec('none')
            self.client.Draw(_draw3Objects())

        def OnPlotDraw4(self, event):
            self.resetDefaults()
            drawObj= _draw4Objects()
            self.client.Draw(drawObj)
##            #profile
##            start = time.clock()            
##            for x in range(10):
##                self.client.Draw(drawObj)
##            print "10 plots of Draw4 took: %f sec."%(time.clock() - start)
##            #profile end

        def OnPlotDraw5(self, event):
            #Empty plot with just axes
            self.resetDefaults()
            drawObj= _draw5Objects()
            #make the axis X= (0,5), Y=(0,10)
            #(default with None is X= (-1,1), Y= (-1,1))
            self.client.Draw(drawObj, xAxis= (0,5), yAxis= (0,10))

        def OnPlotRedraw(self,event):
            self.client.Redraw()

        def OnPlotClear(self,event):
            self.client.Clear()
            
        def OnPlotScale(self, event):
            if self.client.last_draw != None:
                graphics, xAxis, yAxis= self.client.last_draw
                self.client.Draw(graphics,(1,3.05),(0,1))

        def OnEnableZoom(self, event):
            self.client.SetEnableZoom(event.IsChecked())
            
        def OnEnableGrid(self, event):
            self.client.SetEnableGrid(event.IsChecked())
            
        def OnEnableLegend(self, event):
            self.client.SetEnableLegend(event.IsChecked())

        def OnScrUp(self, event):
            self.client.ScrollUp(1)
            
        def OnScrRt(self,event):
            self.client.ScrollRight(2)

        def OnReset(self,event):
            self.client.Reset()

        def OnHelpAbout(self, event):
            about = wxScrolledMessageDialog(self, __doc__, "About...")
            about.ShowModal()

        def resetDefaults(self):
            """Just to reset the fonts back to the PlotCanvas defaults"""
            self.client.SetFont(wx.wxFont(10,wx.wxSWISS,wx.wxNORMAL,wx.wxNORMAL))
            self.client.SetFontSizeAxis(10)
            self.client.SetFontSizeLegend(7)
            self.client.SetXSpec('auto')
            self.client.SetYSpec('auto')
            

    class MyApp(wx.wxApp):
        def OnInit(self):
            frame = AppFrame(wx.NULL, -1, "wxPlotCanvas")
            frame.Show(True)
            self.SetTopWindow(frame)
            return True


    app = MyApp(0)
    app.MainLoop()

if __name__ == '__main__':
    __test()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -