source: sasview/guitools/PlotPanel.py @ 43bf807

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 43bf807 was 43bf807, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

Fixed labels in PlotPanel? and minor mod for sqrt units in unitConverter.

  • Property mode set to 100644
File size: 25.9 KB
Line 
1import wx.lib.newevent
2import matplotlib
3matplotlib.interactive(False)
4#Use the WxAgg back end. The Wx one takes too long to render
5matplotlib.use('WXAgg')
6from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
7from matplotlib.figure import Figure
8import os
9import fittings
10import transform
11from canvas import FigureCanvas
12from matplotlib.widgets import RectangleSelector
13from pylab import  gca, gcf
14from plottables import Theory1D
15#from plottables import Data1D
16#TODO: make the plottables interactive
17
18DEBUG = False
19
20from plottables import Graph
21#(FuncFitEvent, EVT_FUNC_FIT) = wx.lib.newevent.NewEvent()
22import math,pylab,re
23
24def show_tree(obj,d=0):
25    """Handy function for displaying a tree of graph objects"""
26    print "%s%s" % ("-"*d,obj.__class__.__name__)
27    if 'get_children' in dir(obj):
28        for a in obj.get_children(): show_tree(a,d+1)
29     
30from unitConverter import UnitConvertion as convertUnit   
31def _convertUnit(pow,unit):
32    """
33        Displays the unit with the proper convertion
34        @param pow: the user set the power of the unit
35        @param unit: the unit of the data
36    """ 
37    return unit
38    toks=re.match("^", unit)
39    if not toks==None:
40        unitValue= re.split("{",unit)
41        unitPower= re.split("}",unitValue[1])
42        power= int(unitPower[0])*pow
43        word= unitValue[0]+"{"+str(power)+"}"
44        if power==1:
45            tempUnit=re.split("\^",unitValue[0])
46            unit=tempUnit[0]
47        else:
48            unit = word
49    #print"this is unit",unit
50    return unit
51
52def _rescale(lo,hi,step,pt=None,bal=None,scale='linear'):
53        """
54        Rescale (lo,hi) by step, returning the new (lo,hi)
55        The scaling is centered on pt, with positive values of step
56        driving lo/hi away from pt and negative values pulling them in.
57        If bal is given instead of point, it is already in [0,1] coordinates.
58   
59        This is a helper function for step-based zooming.
60        """
61        # Convert values into the correct scale for a linear transformation
62        # TODO: use proper scale transformers
63        loprev = lo
64        hiprev = hi
65        ptprev = pt
66        if scale=='log':
67            assert lo >0
68            if lo > 0 :
69                lo = math.log10(lo)
70            if hi > 0 :
71                hi = math.log10(hi)
72            if pt is not None: pt = math.log10(pt)
73       
74        # Compute delta from axis range * %, or 1-% if persent is negative
75        if step > 0:
76            delta = float(hi-lo)*step/100
77        else:
78            delta = float(hi-lo)*step/(100-step)
79   
80        # Add scale factor proportionally to the lo and hi values, preserving the
81        # point under the mouse
82        if bal is None:
83            bal = float(pt-lo)/(hi-lo)
84        lo = lo - bal*delta
85        hi = hi + (1-bal)*delta
86   
87        # Convert transformed values back to the original scale
88        if scale=='log':
89            if (lo <= -250) or (hi >= 250):
90                lo=loprev
91                hi=hiprev
92                print "Not possible to scale"
93           
94            else:
95                lo,hi = math.pow(10.,lo),math.pow(10.,hi)
96                #assert lo >0,"lo = %g"%lo
97                print "possible to scale"
98           
99            print "these are low and high",lo,hi
100
101        return (lo,hi)
102
103
104class PlotPanel(wx.Panel):
105    """
106    The PlotPanel has a Figure and a Canvas. OnSize events simply set a
107    flag, and the actually redrawing of the
108    figure is triggered by an Idle event.
109    """
110    def __init__(self, parent, id = -1, color = None,\
111        dpi = None, **kwargs):
112        wx.Panel.__init__(self, parent, id = id, **kwargs)
113        self.parent = parent
114        self.figure = Figure(None, dpi)
115        #self.figure = pylab.Figure(None, dpi)
116        #self.canvas = NoRepaintCanvas(self, -1, self.figure)
117        self.canvas = FigureCanvas(self, -1, self.figure)
118        self.SetColor(color)
119        #self.Bind(wx.EVT_IDLE, self._onIdle)
120        #self.Bind(wx.EVT_SIZE, self._onSize)
121        self._resizeflag = True
122        self._SetSize()
123        self.subplot = self.figure.add_subplot(111)
124        self.figure.subplots_adjust(left=.2, bottom=.2)
125        self.yscale = 'linear'
126        self.xscale = 'linear'
127        sizer = wx.BoxSizer(wx.VERTICAL)
128        sizer.Add(self.canvas,1,wx.EXPAND)
129        self.SetSizer(sizer)
130       
131        # Graph object to manage the plottables
132        self.graph = Graph()
133        #self.Bind(EVT_FUNC_FIT, self.onFitRange)
134        self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu)
135        #self.Bind(EVT_PROPERTY, self._onEVT_FUNC_PROPERTY)
136        # Define some constants
137        self.colorlist = ['b','g','r','c','m','y']
138        self.symbollist = ['o','x','^','v','<','>','+','s','d','D','h','H','p']
139        #User scale
140        self.xLabel ="x"
141        self.yLabel ="y"
142        self.viewModel ="--"
143        # keep track if the previous transformation of x and y in Property dialog
144        self.prevXtrans ="x"
145        self.prevYtrans ="y"
146        self.canvas.mpl_connect('scroll_event',self.onWheel)
147        self.axes = [self.subplot]
148         # new data for the fit
149        self.fit_result = Theory1D(x=[], y=[], dy=None)
150        #self.fit_result = Data1D(x=[], y=[],dx=None, dy=None)
151        self.fit_result.name = "Fit"
152        # For fit Dialog initial display
153        self.xmin=0.0
154        self.xmax=0.0
155        self.xminView=0.0
156        self.xmaxView=0.0
157        self.Avalue=None
158        self.Bvalue=None
159        self.ErrAvalue=None
160        self.ErrBvalue=None
161        self.Chivalue=None
162       
163    def resetFitView(self):
164        """
165             For fit Dialog initial display
166        """
167        self.xmin=0.0
168        self.xmax=0.0
169        self.xminView=0.0
170        self.xmaxView=0.0
171        self.Avalue=None
172        self.Bvalue=None
173        self.ErrAvalue=None
174        self.ErrBvalue=None
175        self.Chivalue=None
176       
177    def onWheel(self, event):
178        """
179            Process mouse wheel as zoom events
180            @param event: Wheel event
181        """
182        ax = event.inaxes
183        step = event.step
184
185        if ax != None:
186            # Event occurred inside a plotting area
187            lo,hi = ax.get_xlim()
188            lo,hi = _rescale(lo,hi,step,pt=event.xdata,scale=ax.get_xscale())
189            if not self.xscale=='log' or lo>0:
190                ax.set_xlim((lo,hi))
191
192            lo,hi = ax.get_ylim()
193            lo,hi = _rescale(lo,hi,step,pt=event.ydata,scale=ax.get_yscale())
194            if not self.yscale=='log' or lo>0:
195                ax.set_ylim((lo,hi))
196        else:
197             # Check if zoom happens in the axes
198            xdata,ydata = None,None
199            x,y = event.x,event.y
200           
201            for ax in self.axes:
202                insidex,_ = ax.xaxis.contains(event)
203                if insidex:
204                    xdata,_ = ax.transAxes.inverse_xy_tup((x,y))
205                insidey,_ = ax.yaxis.contains(event)
206                if insidey:
207                    _,ydata = ax.transAxes.inverse_xy_tup((x,y))
208            if xdata is not None:
209                lo,hi = ax.get_xlim()
210                lo,hi = _rescale(lo,hi,step,bal=xdata,scale=ax.get_xscale())
211                if not self.xscale=='log' or lo>0:
212                    ax.set_xlim((lo,hi))
213            if ydata is not None:
214                lo,hi = ax.get_ylim()
215                lo,hi = _rescale(lo,hi,step,bal=ydata,scale=ax.get_yscale())
216                if not self.yscale=='log' or lo>0:
217                    ax.set_ylim((lo,hi))
218               
219        self.canvas.draw_idle()
220
221
222    def returnTrans(self):
223        """
224            Return values and labels used by Fit Dialog
225        """
226        return self.xLabel,self.yLabel, self.Avalue, self.Bvalue,\
227                self.ErrAvalue,self.ErrBvalue,self.Chivalue
228   
229    def setTrans(self,xtrans,ytrans): 
230        """
231            @param xtrans: set x transformation on Property dialog
232            @param ytrans: set y transformation on Property dialog
233        """
234        self.prevXtrans =xtrans
235        self.prevYtrans =ytrans
236   
237    def onFitting(self, event): 
238        """
239            when clicking on linear Fit on context menu , display Fitting Dialog
240        """
241        list =[]
242        list = self.graph.returnPlottable()
243        from fitDialog import LinearFit
244       
245        if len(list.keys())>0:
246            first_item = list.keys()[0]
247            dlg = LinearFit( None, first_item, self.onFitDisplay,self.returnTrans, -1, 'Linear Fit')
248           
249            if (self.xmin !=0.0 )and ( self.xmax !=0.0)\
250                and(self.xminView !=0.0 )and ( self.xmaxView !=0.0):
251                dlg.setFitRange(self.xminView,self.xmaxView,self.xmin,self.xmax)
252            dlg.ShowModal() 
253
254    def linear_plottable_fit(self, plot): 
255        """
256            when clicking on linear Fit on context menu , display Fitting Dialog
257        """
258        from fitDialog import LinearFit
259       
260        dlg = LinearFit( None, plot, self.onFitDisplay,self.returnTrans, -1, 'Linear Fit')
261       
262        if (self.xmin !=0.0 )and ( self.xmax !=0.0)\
263            and(self.xminView !=0.0 )and ( self.xmaxView !=0.0):
264            dlg.setFitRange(self.xminView,self.xmaxView,self.xmin,self.xmax)
265        dlg.ShowModal() 
266
267    def _onProperties(self, event):
268        """
269            when clicking on Properties on context menu ,The Property dialog is displayed
270            The user selects a transformation for x or y value and a new plot is displayed
271        """
272        list =[]
273        list = self.graph.returnPlottable()
274        if len(list.keys())>0:
275            first_item = list.keys()[0]
276            if first_item.x !=[]:
277                from PropertyDialog import Properties
278                dial = Properties(self, -1, 'Properties')
279                dial.setValues( self.prevXtrans, self.prevYtrans,self.viewModel )
280                if dial.ShowModal() == wx.ID_OK:
281                    self.xLabel, self.yLabel,self.viewModel = dial.getValues()
282                    if self.viewModel =="Guinier lny vs x^(2)":
283                        self.xLabel="x^(2)"
284                        self.yLabel="ln(y)"
285                        self.viewModel = "--"
286                        dial.setValues( self.xLabel, self.yLabel,self.viewModel )
287                    self._onEVT_FUNC_PROPERTY()
288                dial.Destroy()
289           
290 
291    def set_yscale(self, scale='linear'):
292        """
293            Set the scale on Y-axis
294            @param scale: the scale of y-axis
295        """
296        self.subplot.set_yscale(scale)
297        self.yscale = scale
298       
299    def get_yscale(self):
300        """
301             @return: Y-axis scale
302        """
303        return self.yscale
304   
305    def set_xscale(self, scale='linear'):
306        """
307            Set the scale on x-axis
308            @param scale: the scale of x-axis
309        """
310        self.subplot.set_xscale(scale)
311        self.xscale = scale
312       
313    def get_xscale(self):
314        """
315             @return: x-axis scale
316        """
317        return self.xscale
318
319    def SetColor(self, rgbtuple):
320        """Set figure and canvas colours to be the same"""
321        if not rgbtuple:
322            rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get()
323        col = [c/255.0 for c in rgbtuple]
324        self.figure.set_facecolor(col)
325        self.figure.set_edgecolor(col)
326        self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple))
327
328    def _onSize(self, event):
329        self._resizeflag = True
330
331    def _onIdle(self, evt):
332        if self._resizeflag:
333            self._resizeflag = False
334            self._SetSize()
335            self.draw()
336
337    def _SetSize(self, pixels = None):
338        """
339        This method can be called to force the Plot to be a desired size, which defaults to
340        the ClientSize of the panel
341        """
342        if not pixels:
343            pixels = self.GetClientSize()
344        self.canvas.SetSize(pixels)
345        self.figure.set_size_inches(pixels[0]/self.figure.get_dpi(),
346        pixels[1]/self.figure.get_dpi())
347
348    def draw(self):
349        """Where the actual drawing happens"""
350        self.figure.canvas.draw_idle()
351       
352
353 
354 
355       
356    def onSaveImage(self, evt):
357        #figure.savefig
358        #print "Save image not implemented"
359        path = None
360        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.png", wx.SAVE)
361        if dlg.ShowModal() == wx.ID_OK:
362            path = dlg.GetPath()
363            mypath = os.path.basename(path)
364            print path
365        dlg.Destroy()
366        if not path == None:
367            self.subplot.figure.savefig(path,dpi=300, facecolor='w', edgecolor='w',
368                                        orentation='portrait', papertype=None, format='png')
369       
370    def onContextMenu(self, event):
371        """
372            Default context menu for a plot panel
373        """
374        # Slicer plot popup menu
375        id = wx.NewId()
376        slicerpop = wx.Menu()
377        slicerpop.Append(id,'&Save image', 'Save image as PNG')
378        wx.EVT_MENU(self, id, self.onSaveImage)
379       
380        id = wx.NewId()
381        slicerpop.Append(id, '&Load 1D data file')
382        wx.EVT_MENU(self, id, self._onLoad1DData)
383       
384        id = wx.NewId()
385        slicerpop.AppendSeparator()
386        slicerpop.Append(id, '&Properties')
387        wx.EVT_MENU(self, id, self._onProperties)
388       
389        id = wx.NewId()
390        slicerpop.AppendSeparator()
391        slicerpop.Append(id, '&Linear Fit')
392        wx.EVT_MENU(self, id, self.onFitting)
393       
394        id = wx.NewId()
395        slicerpop.AppendSeparator()
396        slicerpop.Append(id, '&Reset Graph')
397        wx.EVT_MENU(self, id, self.onResetGraph)
398       
399        pos = event.GetPosition()
400        pos = self.ScreenToClient(pos)
401        self.PopupMenu(slicerpop, pos)
402   
403    ## The following is plottable functionality
404
405
406    def properties(self,prop):
407        """Set some properties of the graph.
408       
409        The set of properties is not yet determined.
410        """
411        # The particulars of how they are stored and manipulated (e.g., do
412        # we want an inventory internally) is not settled.  I've used a
413        # property dictionary for now.
414        #
415        # How these properties interact with a user defined style file is
416        # even less clear.
417
418        # Properties defined by plot
419        self.subplot.set_xlabel(r"$%s$" % prop["xlabel"])
420        self.subplot.set_ylabel(r"$%s$" % prop["ylabel"])
421        self.subplot.set_title(prop["title"])
422
423        # Properties defined by user
424        #self.axes.grid(True)
425
426    def clear(self):
427        """Reset the plot"""
428       
429        # TODO: Redraw is brutal.  Render to a backing store and swap in
430        # TODO: rather than redrawing on the fly.
431        self.subplot.clear()
432        self.subplot.hold(True)
433   
434    def render(self):
435        """Commit the plot after all objects are drawn"""
436        # TODO: this is when the backing store should be swapped in.
437        from matplotlib.font_manager import FontProperties
438        self.subplot.legend(prop=FontProperties(size=10))
439        #self.subplot.legend()
440        pass
441
442    def xaxis(self,label,units):
443        """xaxis label and units.
444       
445        Axis labels know about units.
446       
447        We need to do this so that we can detect when axes are not
448        commesurate.  Currently this is ignored other than for formatting
449        purposes.
450        """
451        if units != "": label = label + " (" + units + ")"
452        self.subplot.set_xlabel(label)
453        pass
454   
455    def yaxis(self,label,units):
456        """yaxis label and units."""
457        if units != "": label = label + " (" + units + ")"
458        self.subplot.set_ylabel(label)
459        pass
460
461    def _connect_to_xlim(self,callback):
462        """Bind the xlim change notification to the callback"""
463        def process_xlim(axes):
464            lo,hi = subplot.get_xlim()
465            callback(lo,hi)
466        self.subplot.callbacks.connect('xlim_changed',process_xlim)
467   
468    #def connect(self,trigger,callback):
469    #    print "PlotPanel.connect???"
470    #    if trigger == 'xlim': self._connect_to_xlim(callback)
471
472    def points(self,x,y,dx=None,dy=None,color=0,symbol=0,label=None):
473        """Draw markers with error bars"""
474        self.subplot.set_yscale('linear')
475        self.subplot.set_xscale('linear')
476       
477        # Convert tuple (lo,hi) to array [(x-lo),(hi-x)]
478        if dx != None and type(dx) == type(()):
479            dx = nx.vstack((x-dx[0],dx[1]-x)).transpose()
480        if dy != None and type(dy) == type(()):
481            dy = nx.vstack((y-dy[0],dy[1]-y)).transpose()
482
483        if dx==None and dy==None:
484            h = self.subplot.plot(x,y,color=self._color(color),
485                                   marker=self._symbol(symbol),linestyle='',label=label)
486        else:
487            col = self._color(color)
488            self.subplot.errorbar(x, y, yerr=dy, xerr=None,
489             ecolor=col, capsize=2,linestyle='', barsabove=False,
490             mec=col, mfc=col,
491             marker=self._symbol(symbol),
492             lolims=False, uplims=False,
493             xlolims=False, xuplims=False,label=label)
494           
495        self.subplot.set_yscale(self.yscale)
496        self.subplot.set_xscale(self.xscale)
497
498    def curve(self,x,y,dy=None,color=0,symbol=0,label=None):
499        """Draw a line on a graph, possibly with confidence intervals."""
500        c = self._color(color)
501        self.subplot.set_yscale('linear')
502        self.subplot.set_xscale('linear')
503       
504        hlist = self.subplot.plot(x,y,color=c,marker='',linestyle='-',label=label)
505       
506        self.subplot.set_yscale(self.yscale)
507        self.subplot.set_xscale(self.xscale)
508
509    def _color(self,c):
510        """Return a particular colour"""
511        return self.colorlist[c%len(self.colorlist)]
512
513    def _symbol(self,s):
514        """Return a particular symbol"""
515        return self.symbollist[s%len(self.symbollist)]
516   
517    def _replot(self):
518        """
519            Rescale the plottables according to the latest
520            user selection and update the plot
521        """
522        self.graph.reset_scale()
523        self._onEVT_FUNC_PROPERTY(remove_fit=False)
524       
525        #TODO: Why do we have to have the following line?
526        self.fit_result.reset_view()
527       
528        self.graph.render(self)
529        self.subplot.figure.canvas.draw_idle()
530   
531    def _onEVT_FUNC_PROPERTY(self, remove_fit=True):
532        """
533             Receive the x and y transformation from myDialog,Transforms x and y in View
534              and set the scale   
535        """ 
536        list =[]
537        list = self.graph.returnPlottable()
538       
539        if remove_fit:
540            self.fit_result.x =[] 
541            self.fit_result.y =[] 
542            self.fit_result.dx=None
543            self.fit_result.dy=None
544            self.graph.delete(self.fit_result)
545       
546        for item in list:
547            item.setLabel(self.xLabel,self.yLabel)
548            if ( self.xLabel=="x" ):
549                item.transformX(transform.toX,transform.errToX)
550                self.set_xscale("linear")
551                name, units = item.get_xaxis()
552                self.graph.xaxis("%s" % name,  "%s" % units)
553               
554               
555            if ( self.xLabel=="x^(2)" ):
556                item.transformX(transform.toX2,transform.errToX2)
557                self.set_xscale('linear')
558                name, units = item.get_xaxis()
559                units=convertUnit(2,units) 
560                self.graph.xaxis("%s^{2}" % name,  "%s" % units)
561               
562               
563            if (self.xLabel=="log10(x)" ):
564                item.transformX(transform.toX,transform.errToX)
565                self.set_xscale("log")
566                name, units = item.get_xaxis() 
567                self.graph.xaxis("\log_{10}\ \  (%s)" % name,  "%s" % units)
568               
569               
570            if ( self.yLabel=="ln(y)" ):
571                item.transformY(transform.toLogX,transform.errToLogX)
572                self.set_yscale("linear")
573                name, units = item.get_yaxis()
574                self.graph.yaxis("log\ \ %s" % name,  "%s" % units)
575               
576               
577            if ( self.yLabel=="y" ):
578                item.transformY(transform.toX,transform.errToX)
579                self.set_yscale("linear")
580                name, units = item.get_yaxis()
581                self.graph.yaxis("%s" % name,  "%s" % units)
582               
583               
584            if ( self.yLabel=="log10(y)" ): 
585                item.transformY(transform.toX,transform.errToX)
586                self.set_yscale("log") 
587                name, units = item.get_yaxis()
588                self.graph.yaxis("\log_{10}\ \ (%s)" % name,  "%s" % units)
589               
590               
591            if ( self.yLabel=="y^(2)" ):
592                item.transformY( transform.toX2,transform.errToX2 )   
593                self.set_yscale("linear")
594                name, units = item.get_yaxis()
595                units=convertUnit(2,units) 
596                self.graph.yaxis("%s^{2}" % name,  "%s" % units)
597               
598               
599            if ( self.yLabel =="1/y"):
600                item.transformY(transform.toOneOverX,transform.errOneOverX )
601                self.set_yscale("linear")
602                name, units = item.get_yaxis()
603                units=convertUnit(-1,units)
604                self.graph.yaxis("1/%s" % name,  "%s" % units)
605               
606            if ( self.yLabel =="1/sqrt(y)" ):
607                item.transformY(transform.toOneOverSqrtX,transform.errOneOverSqrtX )
608                self.set_yscale("linear")
609                name, units = item.get_yaxis()
610                units=convertUnit(-0.5,units)
611                self.graph.yaxis("1/\sqrt{%s}" %name,  "%s" % units)
612               
613            if ( self.yLabel =="ln(y*x)"):
614                item.transformY( transform.toLogXY,transform.errToLogXY)
615                self.set_yscale("linear")
616                yname, yunits = item.get_yaxis()
617                xname, xunits = item.get_xaxis()
618                self.graph.yaxis("log\ (%s \ \ %s)" % (yname,xname),  "%s%s" % (yunits,xunits))
619               
620               
621            if ( self.yLabel =="ln(y*x^(2))"):
622                item.transformY( transform.toLogYX2,transform.errToLogYX2)
623                self.set_yscale("linear")
624                yname, yunits = item.get_yaxis()
625                xname, xunits = item.get_xaxis() 
626                xunits = convertUnit(2,xunits) 
627                self.graph.yaxis("Log (%s \ \ %s^{2})" % (yname,xname),  "%s%s" % (yunits,xunits))
628               
629           
630            if ( self.yLabel =="ln(y*x^(4))"):
631                item.transformY(transform.toLogYX4,transform.errToLogYX4)
632                self.set_yscale("linear")
633                yname, yunits = item.get_yaxis()
634                xname, xunits = item.get_xaxis()
635                xunits = convertUnit(4,xunits) 
636                self.graph.yaxis("Log (%s \ \ %s^{4})" % (yname,xname),  "%s%s" % (yunits,xunits))
637               
638            if ( self.viewModel == "Guinier lny vs x^(2)"):
639               
640                item.transformX(transform.toX2,transform.errToX2)
641                self.set_xscale('linear')
642                name, units = item.get_xaxis()
643                units = convertUnit(2,units) 
644                self.graph.xaxis("%s^{2}" % name,  "%s" % units)
645               
646               
647                item.transformY(transform.toLogX,transform.errToLogX )
648                self.set_yscale("linear")
649                name, units = item.get_yaxis()
650                self.graph.yaxis("$Log %s$" % name,  "%s" % units)
651               
652               
653            item.transformView()
654           
655         
656        self.resetFitView()   
657        self.prevXtrans = self.xLabel
658        self.prevYtrans = self.yLabel 
659        self.graph.render(self)
660        self.subplot.figure.canvas.draw_idle()
661       
662       
663   
664    def onFitDisplay(self, tempx,tempy,xminView,xmaxView,xmin,xmax,func):
665        """
666            Add a new plottable into the graph .In this case this plottable will be used
667            to fit some data
668            @param tempx: The x data of fit line
669            @param tempy: The y data of fit line
670            @param xminView: the lower bound of fitting range
671            @param xminView: the upper bound of  fitting range
672            @param xmin: the lowest value of data to fit to the line
673            @param xmax: the highest value of data to fit to the line
674        """
675        # Saving value to redisplay in Fit Dialog when it is opened again
676        self.Avalue,self.Bvalue,self.ErrAvalue,self.ErrBvalue,self.Chivalue=func
677        self.xminView=xminView
678        self.xmaxView=xmaxView
679        self.xmin= xmin
680        self.xmax= xmax
681        #In case need to change the range of data plotted
682        list =[]
683        list = self.graph.returnPlottable()
684        for item in list:
685            #item.onFitRange(xminView,xmaxView)
686            item.onFitRange(None,None)
687       
688        # Create new data plottable with result
689        self.fit_result.x =[] 
690        self.fit_result.y =[]
691        self.fit_result.x =tempx 
692        self.fit_result.y =tempy     
693        self.fit_result.dx=None
694        self.fit_result.dy=None
695        #Load the view with the new values
696        self.fit_result.reset_view()
697        # Add the new plottable to the graph
698        self.graph.add(self.fit_result) 
699        self.graph.render(self)
700        self.subplot.figure.canvas.draw_idle()
701       
702   
703    def onResetGraph(self,event):
704        """
705            Reset the graph by plotting the full range of data
706        """
707        list =[]
708        list = self.graph.returnPlottable()
709        for item in list:
710            item.onReset()
711        self.graph.render(self)
712        self.subplot.figure.canvas.draw_idle()
713       
714class NoRepaintCanvas(FigureCanvasWxAgg):
715    """We subclass FigureCanvasWxAgg, overriding the _onPaint method, so that
716    the draw method is only called for the first two paint events. After that,
717    the canvas will only be redrawn when it is resized.
718    """
719    def __init__(self, *args, **kwargs):
720        FigureCanvasWxAgg.__init__(self, *args, **kwargs)
721        self._drawn = 0
722
723    def _onPaint(self, evt):
724        """
725        Called when wxPaintEvt is generated
726        """
727        if not self._isRealized:
728            self.realize()
729        if self._drawn < 2:
730            self.draw(repaint = False)
731            self._drawn += 1
732        self.gui_repaint(drawDC=wx.PaintDC(self))
733           
Note: See TracBrowser for help on using the repository browser.