예제 #1
0
 def _set_tuple_marker(self):
     marker = self._marker
     if is_numlike(marker[0]):
         if len(marker) == 2:
             numsides, rotation = marker[0], 0.0
         elif len(marker) == 3:
             numsides, rotation = marker[0], marker[2]
         symstyle = marker[1]
         if symstyle == 0:
             self._path = Path.unit_regular_polygon(numsides)
             self._joinstyle = 'miter'
         elif symstyle == 1:
             self._path = Path.unit_regular_star(numsides)
             self._joinstyle = 'bevel'
         elif symstyle == 2:
             self._path = Path.unit_regular_asterisk(numsides)
             self._filled = False
             self._joinstyle = 'bevel'
         elif symstyle == 3:
             self._path = Path.unit_circle()
         self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
     else:
         verts = np.asarray(marker[0])
         path = Path(verts)
         self._set_custom_marker(path)
예제 #2
0
 def _set_tuple_marker(self):
     marker = self._marker
     if is_numlike(marker[0]):
         if len(marker) == 2:
             numsides, rotation = marker[0], 0.0
         elif len(marker) == 3:
             numsides, rotation = marker[0], marker[2]
         symstyle = marker[1]
         if symstyle == 0:
             self._path = Path.unit_regular_polygon(numsides)
             self._joinstyle = 'miter'
         elif symstyle == 1:
             self._path = Path.unit_regular_star(numsides)
             self._joinstyle = 'bevel'
         elif symstyle == 2:
             self._path = Path.unit_regular_asterisk(numsides)
             self._filled = False
             self._joinstyle = 'bevel'
         elif symstyle == 3:
             self._path = Path.unit_circle()
         self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
     else:
         verts = np.asarray(marker[0])
         path = Path(verts)
         self._set_custom_marker(path)
예제 #3
0
    def _process_yloc(self, yloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcy to place the y coord at
        draw time
        """
        props = dict()
        if is_numlike(yloc):
            return # nothing to do

        if not is_string_like(yloc):
            raise ValueError('y location code must be a number or string')
        yloc = yloc.lower().strip()

        if yloc=='center':
            props['verticalalignment'] = 'center'
            def funcy(bottom, top):
                return 0.5*(bottom + top)
            if self._pady=='auto':
                self._pady = 0.
            
        else:
            tup = yloc.split(' ')
            if len(tup)!=2:
                raise ValueError('location code looks like "inside|outside bottom|top".  You supplied "%s"'%yloc)

            inout, bottomtop = tup
            
            if inout not in ('inside', 'outside'):
                raise ValueError('y in/out: bad location code "%s"'%yloc)
            if bottomtop not in ('bottom', 'top'):
                raise ValueError('y bottom/top: bad location code "%s"'%yloc)
            if inout=='inside' and bottomtop=='bottom':
                props['verticalalignment'] = 'bottom'
                def funcy(bottom, top):
                    return bottom
                if self._pady=='auto':
                    self._pady = self._autopad
            elif inout=='inside' and bottomtop=='top':
                props['verticalalignment'] = 'top'
                def funcy(bottom, top):
                    return top
                if self._pady=='auto':
                    self._pady = -self._autopad
            elif inout=='outside' and bottomtop=='bottom':
                props['verticalalignment'] = 'top'
                def funcy(bottom, top):
                    return bottom
                if self._pady=='auto':
                    self._pady = -self._autopad
            elif inout=='outside' and bottomtop=='top':
                props['verticalalignment'] = 'bottom'
                def funcy(bottom, top):
                    return top
                if self._pady=='auto':
                    self._pady = self._autopad
                
        self.update(props)
        self._funcy = funcy
예제 #4
0
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius`/:meth:`~matplotlib.lines.Line2D.set_pickradius`
        to view or modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains):
            return self._contains(self, mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError, "pick radius should be a distance"

        # Make sure we have data to plot
        if self._invalid:
            self.recache()
        if len(self._xy) == 0:
            return False, {}

        # Convert points to pixels
        path, affine = self._transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure == None:
            warning.warn("no figure set when check if mouse is on line")
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi / 72.0 * self.pickradius

        # Check for collision
        if self._linestyle in ["None", None]:
            # If no line, return the nearby point(s)
            d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
            ind, = np.nonzero(np.less_equal(d, pixels ** 2))
        else:
            # If line, return the nearby segment(s)
            ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)

        # Debugging message
        if False and self._label != u"":
            print "Checking line", self._label, "at", mouseevent.x, mouseevent.y
            print "xt", xt
            print "yt", yt
            # print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print "ind", ind

        # Return the point(s) within radius
        return len(ind) > 0, dict(ind=ind)
예제 #5
0
    def _process_xloc(self, xloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcx to place the x coord at
        draw time
        """

        props = dict()
        if is_numlike(xloc):
            return # nothing to do

        if not is_string_like(xloc):
            raise ValueError('x location code must be a number or string')
        xloc = xloc.lower().strip()

        if xloc=='center':
            props['horizontalalignment'] = 'center'
            def funcx(left, right):
                return 0.5*(left + right)
            if self._padx=='auto':
                self._padx = 0.
        else:
            tup = xloc.split(' ')
            if len(tup)!=2:
                raise ValueError('location code looks like "inside|outside left|right".  You supplied "%s"'%xloc)

            inout, leftright = tup
            
            if inout not in ('inside', 'outside'):
                raise ValueError('x in/out: bad location code "%s"'%xloc)
            if leftright not in ('left', 'right'):
                raise ValueError('x left/right: bad location code "%s"'%xloc)
            if inout=='inside' and leftright=='left':
                props['horizontalalignment'] = 'left'
                def funcx(left, right):
                    return left
                if self._padx=='auto':
                    self._padx = self._autopad
            elif inout=='inside' and leftright=='right':
                props['horizontalalignment'] = 'right'
                def funcx(left, right):
                    return right
                if self._padx=='auto':
                    self._padx = -self._autopad
            elif inout=='outside' and leftright=='left':
                props['horizontalalignment'] = 'right'
                def funcx(left, right):
                    return left
                if self._padx=='auto':
                    self._padx = -self._autopad
            elif inout=='outside' and leftright=='right':
                props['horizontalalignment'] = 'left'
                def funcx(left, right):
                    return right
                if self._padx=='auto':
                    self._padx = self._autopad

        self.update(props)
        self._funcx = funcx
예제 #6
0
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError,"pick radius should be a distance"

        # Make sure we have data to plot
        if self._invalid:
            self.recache()
        if len(self._xy)==0: return False,{}

        # Convert points to pixels
        path, affine = self._transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure == None:
            warning.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi/72. * self.pickradius

        # Check for collision
        if self._linestyle in ['None',None]:
            # If no line, return the nearby point(s)
            d = (xt-mouseevent.x)**2 + (yt-mouseevent.y)**2
            ind, = np.nonzero(np.less_equal(d, pixels**2))
        else:
            # If line, return the nearby segment(s)
            ind = segment_hits(mouseevent.x,mouseevent.y,xt,yt,pixels)

        # Debugging message
        if False and self._label != u'':
            print "Checking line",self._label,"at",mouseevent.x,mouseevent.y
            print 'xt', xt
            print 'yt', yt
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print 'ind',ind

        # Return the point(s) within radius
        return len(ind)>0,dict(ind=ind)
예제 #7
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius`/:meth:`~matplotlib.lines.Line2D.set_pickradius`
        to view or modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError,"pick radius should be a distance"

        # transform in backend
        if len(self._xy)==0: return False,{}

        xyt = self._transformed_path.get_fully_transformed_path().vertices
        xt = xyt[:, 0]
        yt = xyt[:, 1]

        if self.figure == None:
            print str(self),' has no figure set'
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi/72. * self.pickradius

        if self._linestyle == 'None':
            # If no line, return the nearby point(s)
            d = np.sqrt((xt-mouseevent.x)**2 + (yt-mouseevent.y)**2)
            ind, = np.nonzero(np.less_equal(d, pixels))
        else:
            # If line, return the nearby segment(s)
            ind = segment_hits(mouseevent.x,mouseevent.y,xt,yt,pixels)
        if 0:
            print 'xt', xt, mouseevent.x
            print 'yt', yt, mouseevent.y
            print 'd', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print d, pixels, ind
        return len(ind)>0,dict(ind=ind)
예제 #8
0
파일: lines.py 프로젝트: gkliska/razvoj
    def contains(self, mouseevent):
        """Test whether the mouse event occurred on the line.  The pick radius determines
        the precision of the location test (usually within five points of the value).  Use
        get/set pickradius() to view or modify it.

        Returns True if any values are within the radius along with {'ind': pointlist},
        npy.where pointlist is the set of points within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError,"pick radius should be a distance"

        if self._newstyle:
            # transform in backend
            x = self._x
            y = self._y
        else:
            x, y = self._get_plottable()
        if len(x)==0: return False,{}

        xt, yt = self.get_transform().numerix_x_y(x, y)

        if self.figure == None:
            print str(self),' has no figure set'
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi.get()/72. * self.pickradius

        if self._linestyle == 'None':
            # If no line, return the nearby point(s)
            d = npy.sqrt((xt-mouseevent.x)**2 + (yt-mouseevent.y)**2)
            ind, = npy.nonzero(npy.less_equal(d, pixels))
        else:
            # If line, return the nearby segment(s)
            ind = segment_hits(mouseevent.x,mouseevent.y,xt,yt,pixels)
        if 0:
            print 'xt', xt, mouseevent.x
            print 'yt', yt, mouseevent.y
            print 'd', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print d, pixels, ind
        return len(ind)>0,dict(ind=ind)
예제 #9
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def contains(self, mouseevent):
        """Test whether the mouse event occurred on the line.  The pick radius determines
        the precision of the location test (usually within five points of the value).  Use
        get/set pickradius() to view or modify it.

        Returns True if any values are within the radius along with {'ind': pointlist},
        npy.where pointlist is the set of points within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains): return self._contains(self, mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError, "pick radius should be a distance"

        if self._newstyle:
            # transform in backend
            x = self._x
            y = self._y
        else:
            x, y = self._get_plottable()
        if len(x) == 0: return False, {}

        xt, yt = self.get_transform().numerix_x_y(x, y)

        if self.figure == None:
            print str(self), ' has no figure set'
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi.get() / 72. * self.pickradius

        if self._linestyle == 'None':
            # If no line, return the nearby point(s)
            d = npy.sqrt((xt - mouseevent.x)**2 + (yt - mouseevent.y)**2)
            ind, = npy.nonzero(npy.less_equal(d, pixels))
        else:
            # If line, return the nearby segment(s)
            ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
        if 0:
            print 'xt', xt, mouseevent.x
            print 'yt', yt, mouseevent.y
            print 'd', (xt - mouseevent.x)**2., (yt - mouseevent.y)**2.
            print d, pixels, ind
        return len(ind) > 0, dict(ind=ind)
예제 #10
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def __init__(self, xdata, ydata,
                 linewidth       = None, # all Nones default to rc
                 linestyle       = None,
                 color           = None,
                 marker          = None,
                 markersize      = None,
                 markeredgewidth = None,
                 markeredgecolor = None,
                 markerfacecolor = None,
                 antialiased     = None,
                 dash_capstyle   = None,
                 solid_capstyle  = None,
                 dash_joinstyle  = None,
                 solid_joinstyle = None,
                 pickradius      = 5,
                 **kwargs
                 ):
        """
        Create a Line2D instance with x and y data in sequences xdata,
        ydata

        The kwargs are Line2D properties:
          alpha: float
          animated: [True | False]
          antialiased or aa: [True | False]
          clip_box: a matplotlib.transform.Bbox instance
          clip_on: [True | False]
          color or c: any matplotlib color
          dash_capstyle: ['butt' | 'round' | 'projecting']
          dash_joinstyle: ['miter' | 'round' | 'bevel']
          dashes: sequence of on/off ink in points
          data: (np.array xdata, np.array ydata)
          figure: a matplotlib.figure.Figure instance
          label: any string
          linestyle or ls: [ '-' | '--' | '-.' | ':' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' | 'None' | ' ' | '' ]
          linewidth or lw: float value in points
          lod: [True | False]
          marker: [ '+' | ',' | '.' | '1' | '2' | '3' | '4'
          markeredgecolor or mec: any matplotlib color
          markeredgewidth or mew: float value in points (default 5)
          markerfacecolor or mfc: any matplotlib color
          markersize or ms: float
          pickradius: mouse event radius for pick items in points (default 5)
          solid_capstyle: ['butt' | 'round' |  'projecting']
          solid_joinstyle: ['miter' | 'round' | 'bevel']
          transform: a matplotlib.transform transformation instance
          visible: [True | False]
          xdata: np.array
          ydata: np.array
          zorder: any number
        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None   : linewidth=rcParams['lines.linewidth']

        if linestyle is None   : linestyle=rcParams['lines.linestyle']
        if marker is None      : marker=rcParams['lines.marker']
        if color is None       : color=rcParams['lines.color']
        if markeredgecolor is None :
            markeredgecolor='auto'
        if markerfacecolor is None :
            markerfacecolor='auto'
        if markeredgewidth is None :
            markeredgewidth=rcParams['lines.markeredgewidth']

        if markersize is None  : markersize=rcParams['lines.markersize']
        if antialiased is None : antialiased=rcParams['lines.antialiased']
        if dash_capstyle is None : dash_capstyle=rcParams['lines.dash_capstyle']
        if dash_joinstyle is None : dash_joinstyle=rcParams['lines.dash_joinstyle']
        if solid_capstyle is None : solid_capstyle=rcParams['lines.solid_capstyle']
        if solid_joinstyle is None : solid_joinstyle=rcParams['lines.solid_joinstyle']

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)


        self.set_linestyle(linestyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self.set_marker(marker)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None


        self.set_markerfacecolor(markerfacecolor)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self._point_size_reduction = 0.5

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalid = True
        self.set_data(xdata, ydata)
예제 #11
0
파일: mlab.py 프로젝트: zkennedy/pbh5tools
def rec2txt(r, header=None, padding=3, precision=3, fields=None):
    """
    Returns a textual representation of a record array.

    *r*: numpy recarray

    *header*: list of column headers

    *padding*: space between each column

    *precision*: number of decimal places to use for floats.
        Set to an integer to apply to all floats.  Set to a
        list of integers to apply precision individually.
        Precision for non-floats is simply ignored.

    *fields* : if not None, a list of field names to print.  fields
    can be a list of strings like ['field1', 'field2'] or a single
    comma separated string like 'field1,field2'

    Example::

      precision=[0,2,3]

    Output::

      ID    Price   Return
      ABC   12.54    0.234
      XYZ    6.32   -0.076
    """

    if fields is not None:
        r = rec_keep_fields(r, fields)

    if cbook.is_numlike(precision):
        precision = [precision]*len(r.dtype)

    def get_type(item,atype=int):
        tdict = {None:int, int:float, float:str}
        try: atype(str(item))
        except: return get_type(item,tdict[atype])
        return atype

    def get_justify(colname, column, precision):
        ntype = type(column[0])

       

        if ntype==np.int or ntype==np.int16 or ntype==np.int32 or ntype==np.int64 or ntype==np.int8 or ntype==np.int_:
            length = max(len(colname),np.max(map(len,map(str,column))))
            return 1, length+padding, "%d" # right justify

        # JDH: my powerbook does not have np.float96 using np 1.3.0
        """
        In [2]: np.__version__
        Out[2]: '1.3.0.dev5948'

        In [3]: !uname -a
        Darwin Macintosh-5.local 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun  9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386 i386

        In [4]: np.float96
        ---------------------------------------------------------------------------
        AttributeError                            Traceback (most recent call la
        """
        if ntype==np.float or ntype==np.float32 or ntype==np.float64 or (hasattr(np, 'float96') and (ntype==np.float96)) or ntype==np.float_:
            fmt = "%." + str(precision) + "f"
            length = max(len(colname),np.max(map(len,map(lambda x:fmt%x,column))))
            return 1, length+padding, fmt   # right justify


        if ntype==np.str or ntype==np.str_ or ntype==np.string0 or ntype==np.string_:
            length = max(len(colname),column.itemsize)
            return 1, length+padding, "%s" # left justify // JHB changed the 0 to a 1

        return 0, max(len(colname),np.max(map(len,map(str,column))))+padding, "%s"

    if header is None:
        header = r.dtype.names

    justify_pad_prec = [get_justify(header[i],r.__getitem__(colname),precision[i]) for i, colname in enumerate(r.dtype.names)]

    justify_pad_prec_spacer = []
    for i in range(len(justify_pad_prec)):
        just,pad,prec = justify_pad_prec[i]
        if i == 0:
            justify_pad_prec_spacer.append((just,pad,prec,0))
        else:
            pjust,ppad,pprec = justify_pad_prec[i-1]
            if pjust == 0 and just == 1:
                justify_pad_prec_spacer.append((just,pad-padding,prec,0))
            elif pjust == 1 and just == 0:
                justify_pad_prec_spacer.append((just,pad,prec,padding))
            else:
                justify_pad_prec_spacer.append((just,pad,prec,0))

    def format(item, just_pad_prec_spacer):
        just, pad, prec, spacer = just_pad_prec_spacer
        if just == 0:
            return spacer*' ' + str(item).ljust(pad)
        else:
            if get_type(item) == float:
                item = (prec%float(item))
            elif get_type(item) == int:
                item = (prec%int(item))

            return item.rjust(pad)

    textl = []
    textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(header)]))
    for i, row in enumerate(r):
        textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(row)]))
        if i==0:
            textl[0] = textl[0].rstrip()

    text = os.linesep.join(textl)
    return text
예제 #12
0
    def __init__(
            self,
            xdata,
            ydata,
            linewidth=None,  # all Nones default to rc
            linestyle=None,
            color=None,
            marker=None,
            markersize=None,
            markeredgewidth=None,
            markeredgecolor=None,
            markerfacecolor=None,
            markerfacecoloralt='none',
            fillstyle='full',
            antialiased=None,
            dash_capstyle=None,
            solid_capstyle=None,
            dash_joinstyle=None,
            solid_joinstyle=None,
            pickradius=5,
            drawstyle=None,
            markevery=None,
            **kwargs):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None: linewidth = rcParams['lines.linewidth']

        if linestyle is None: linestyle = rcParams['lines.linestyle']
        if marker is None: marker = rcParams['lines.marker']
        if color is None: color = rcParams['lines.color']

        if markersize is None: markersize = rcParams['lines.markersize']
        if antialiased is None: antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None: drawstyle = 'default'

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)
        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)
예제 #13
0
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains):
            return self._contains(self,mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError("pick radius should be a distance")

        # Make sure we have data to plot
        if self._invalidy or self._invalidx:
            self.recache()
        if len(self._xy)==0: return False,{}

        # Convert points to pixels
        if self._transformed_path is None:
            self._transform_path()
        path, affine = self._transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure == None:
            warning.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi/72. * self.pickradius

        # the math involved in checking for containment (here and inside of segment_hits) assumes
        # that it is OK to overflow.  In case the application has set the error flags such that
        # an exception is raised on overflow, we temporarily set the appropriate error flags here
        # and set them back when we are finished. 
        olderrflags = np.seterr(all='ignore')
        try:
            # Check for collision
            if self._linestyle in ['None',None]:
                # If no line, return the nearby point(s)
                d = (xt-mouseevent.x)**2 + (yt-mouseevent.y)**2
                ind, = np.nonzero(np.less_equal(d, pixels**2))
            else:
                # If line, return the nearby segment(s)
                ind = segment_hits(mouseevent.x,mouseevent.y,xt,yt,pixels)
        finally:
            np.seterr(**olderrflags)

        ind += self.ind_offset

        # Debugging message
        if False and self._label != '':
            print("Checking line",self._label,"at",mouseevent.x,mouseevent.y)
            print('xt', xt)
            print('yt', yt)
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print('ind',ind)

        # Return the point(s) within radius
        return len(ind)>0,dict(ind=ind)
예제 #14
0
    def __init__(self, xdata, ydata,
                 linewidth       = None, # all Nones default to rc
                 linestyle       = None,
                 color           = None,
                 marker          = None,
                 markersize      = None,
                 markeredgewidth = None,
                 markeredgecolor = None,
                 markerfacecolor = None,
                 markerfacecoloralt = 'none',
                 fillstyle       = 'full',
                 antialiased     = None,
                 dash_capstyle   = None,
                 solid_capstyle  = None,
                 dash_joinstyle  = None,
                 solid_joinstyle = None,
                 pickradius      = 5,
                 drawstyle       = None,
                 markevery       = None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None   : linewidth=rcParams['lines.linewidth']

        if linestyle is None   : linestyle=rcParams['lines.linestyle']
        if marker is None      : marker=rcParams['lines.marker']
        if color is None       : color=rcParams['lines.color']

        if markersize is None  : markersize=rcParams['lines.markersize']
        if antialiased is None : antialiased=rcParams['lines.antialiased']
        if dash_capstyle is None : dash_capstyle=rcParams['lines.dash_capstyle']
        if dash_joinstyle is None : dash_joinstyle=rcParams['lines.dash_joinstyle']
        if solid_capstyle is None : solid_capstyle=rcParams['lines.solid_capstyle']
        if solid_joinstyle is None : solid_joinstyle=rcParams['lines.solid_joinstyle']

        if drawstyle is None : drawstyle='default'

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)


        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)
        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None


        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)
예제 #15
0
    def _process_yloc(self, yloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcy to place the y coord at
        draw time
        """
        props = dict()
        if is_numlike(yloc):
            return  # nothing to do

        if not is_string_like(yloc):
            raise ValueError('y location code must be a number or string')
        yloc = yloc.lower().strip()

        if yloc == 'center':
            props['verticalalignment'] = 'center'

            def funcy(bottom, top):
                return 0.5 * (bottom + top)

            if self._pady == 'auto':
                self._pady = 0.

        else:
            tup = yloc.split(' ')
            if len(tup) != 2:
                raise ValueError(
                    'location code looks like "inside|outside bottom|top".  You supplied "%s"'
                    % yloc)

            inout, bottomtop = tup

            if inout not in ('inside', 'outside'):
                raise ValueError('y in/out: bad location code "%s"' % yloc)
            if bottomtop not in ('bottom', 'top'):
                raise ValueError('y bottom/top: bad location code "%s"' % yloc)
            if inout == 'inside' and bottomtop == 'bottom':
                props['verticalalignment'] = 'bottom'

                def funcy(bottom, top):
                    return bottom

                if self._pady == 'auto':
                    self._pady = self._autopad
            elif inout == 'inside' and bottomtop == 'top':
                props['verticalalignment'] = 'top'

                def funcy(bottom, top):
                    return top

                if self._pady == 'auto':
                    self._pady = -self._autopad
            elif inout == 'outside' and bottomtop == 'bottom':
                props['verticalalignment'] = 'top'

                def funcy(bottom, top):
                    return bottom

                if self._pady == 'auto':
                    self._pady = -self._autopad
            elif inout == 'outside' and bottomtop == 'top':
                props['verticalalignment'] = 'bottom'

                def funcy(bottom, top):
                    return top

                if self._pady == 'auto':
                    self._pady = self._autopad

        self.update(props)
        self._funcy = funcy
예제 #16
0
    def _process_xloc(self, xloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcx to place the x coord at
        draw time
        """

        props = dict()
        if is_numlike(xloc):
            return  # nothing to do

        if not is_string_like(xloc):
            raise ValueError('x location code must be a number or string')
        xloc = xloc.lower().strip()

        if xloc == 'center':
            props['horizontalalignment'] = 'center'

            def funcx(left, right):
                return 0.5 * (left + right)

            if self._padx == 'auto':
                self._padx = 0.
        else:
            tup = xloc.split(' ')
            if len(tup) != 2:
                raise ValueError(
                    'location code looks like "inside|outside left|right".  You supplied "%s"'
                    % xloc)

            inout, leftright = tup

            if inout not in ('inside', 'outside'):
                raise ValueError('x in/out: bad location code "%s"' % xloc)
            if leftright not in ('left', 'right'):
                raise ValueError('x left/right: bad location code "%s"' % xloc)
            if inout == 'inside' and leftright == 'left':
                props['horizontalalignment'] = 'left'

                def funcx(left, right):
                    return left

                if self._padx == 'auto':
                    self._padx = self._autopad
            elif inout == 'inside' and leftright == 'right':
                props['horizontalalignment'] = 'right'

                def funcx(left, right):
                    return right

                if self._padx == 'auto':
                    self._padx = -self._autopad
            elif inout == 'outside' and leftright == 'left':
                props['horizontalalignment'] = 'right'

                def funcx(left, right):
                    return left

                if self._padx == 'auto':
                    self._padx = -self._autopad
            elif inout == 'outside' and leftright == 'right':
                props['horizontalalignment'] = 'left'

                def funcx(left, right):
                    return right

                if self._padx == 'auto':
                    self._padx = self._autopad

        self.update(props)
        self._funcx = funcx
예제 #17
0
    def __init__(self, xdata, ydata,
                 linewidth       = None, # all Nones default to rc
                 linestyle       = None,
                 color           = None,
                 marker          = None,
                 markersize      = None,
                 markeredgewidth = None,
                 markeredgecolor = None,
                 markerfacecolor = None,
                 antialiased     = None,
                 dash_capstyle   = None,
                 solid_capstyle  = None,
                 dash_joinstyle  = None,
                 solid_joinstyle = None,
                 pickradius      = 5,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are Line2D properties:
        %(Line2D)s
        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None   : linewidth=rcParams['lines.linewidth']

        if linestyle is None   : linestyle=rcParams['lines.linestyle']
        if marker is None      : marker=rcParams['lines.marker']
        if color is None       : color=rcParams['lines.color']

        if markersize is None  : markersize=rcParams['lines.markersize']
        if antialiased is None : antialiased=rcParams['lines.antialiased']
        if dash_capstyle is None : dash_capstyle=rcParams['lines.dash_capstyle']
        if dash_joinstyle is None : dash_joinstyle=rcParams['lines.dash_joinstyle']
        if solid_capstyle is None : solid_capstyle=rcParams['lines.solid_capstyle']
        if solid_joinstyle is None : solid_joinstyle=rcParams['lines.solid_joinstyle']

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)


        self.set_linestyle(linestyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self.set_marker(marker)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None


        self.set_markerfacecolor(markerfacecolor)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self._point_size_reduction = 0.5

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalid = True
        self.set_data(xdata, ydata)
예제 #18
0
def rec2txt(r, header=None, padding=3, precision=3, fields=None):
    """
    Returns a textual representation of a record array.

    *r*: numpy recarray

    *header*: list of column headers

    *padding*: space between each column

    *precision*: number of decimal places to use for floats.
        Set to an integer to apply to all floats.  Set to a
        list of integers to apply precision individually.
        Precision for non-floats is simply ignored.

    *fields* : if not None, a list of field names to print.  fields
    can be a list of strings like ['field1', 'field2'] or a single
    comma separated string like 'field1,field2'

    Example::

      precision=[0,2,3]

    Output::

      ID    Price   Return
      ABC   12.54    0.234
      XYZ    6.32   -0.076
    """

    if fields is not None:
        r = rec_keep_fields(r, fields)

    if cbook.is_numlike(precision):
        precision = [precision]*len(r.dtype)

    def get_type(item,atype=int):
        tdict = {None:int, int:float, float:str}
        try: atype(str(item))
        except: return get_type(item,tdict[atype])
        return atype

    def get_justify(colname, column, precision):
        ntype = type(column[0])

       

        if ntype==np.int or ntype==np.int16 or ntype==np.int32 or ntype==np.int64 or ntype==np.int8 or ntype==np.int_:
            length = max(len(colname),np.max(map(len,map(str,column))))
            return 1, length+padding, "%d" # right justify

        # JDH: my powerbook does not have np.float96 using np 1.3.0
        """
        In [2]: np.__version__
        Out[2]: '1.3.0.dev5948'

        In [3]: !uname -a
        Darwin Macintosh-5.local 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun  9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386 i386

        In [4]: np.float96
        ---------------------------------------------------------------------------
        AttributeError                            Traceback (most recent call la
        """
        if ntype==np.float or ntype==np.float32 or ntype==np.float64 or (hasattr(np, 'float96') and (ntype==np.float96)) or ntype==np.float_:
            fmt = "%." + str(precision) + "f"
            length = max(len(colname),np.max(map(len,map(lambda x:fmt%x,column))))
            return 1, length+padding, fmt   # right justify


        if ntype==np.str or ntype==np.str_ or ntype==np.string0 or ntype==np.string_:
            length = max(len(colname),column.itemsize)
            return 1, length+padding, "%s" # left justify // JHB changed the 0 to a 1

        return 0, max(len(colname),np.max(map(len,map(str,column))))+padding, "%s"

    if header is None:
        header = r.dtype.names

    justify_pad_prec = [get_justify(header[i],r.__getitem__(colname),precision[i]) for i, colname in enumerate(r.dtype.names)]

    justify_pad_prec_spacer = []
    for i in range(len(justify_pad_prec)):
        just,pad,prec = justify_pad_prec[i]
        if i == 0:
            justify_pad_prec_spacer.append((just,pad,prec,0))
        else:
            pjust,ppad,pprec = justify_pad_prec[i-1]
            if pjust == 0 and just == 1:
                justify_pad_prec_spacer.append((just,pad-padding,prec,0))
            elif pjust == 1 and just == 0:
                justify_pad_prec_spacer.append((just,pad,prec,padding))
            else:
                justify_pad_prec_spacer.append((just,pad,prec,0))

    def format(item, just_pad_prec_spacer):
        just, pad, prec, spacer = just_pad_prec_spacer
        if just == 0:
            return spacer*' ' + str(item).ljust(pad)
        else:
            if get_type(item) == float:
                item = (prec%float(item))
            elif get_type(item) == int:
                item = (prec%int(item))

            return item.rjust(pad)

    textl = []
    textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(header)]))
    for i, row in enumerate(r):
        textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(row)]))
        if i==0:
            textl[0] = textl[0].rstrip()

    text = os.linesep.join(textl)
    return text
예제 #19
0
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains):
            return self._contains(self, mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError("pick radius should be a distance")

        # Make sure we have data to plot
        if self._invalidy or self._invalidx:
            self.recache()
        if len(self._xy) == 0:
            return False, {}

        # Convert points to pixels
        transformed_path = self._get_transformed_path()
        path, affine = transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure is None:
            warnings.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi / 72. * self.pickradius

        # the math involved in checking for containment (here and inside of
        # segment_hits) assumes that it is OK to overflow.  In case the
        # application has set the error flags such that an exception is raised
        # on overflow, we temporarily set the appropriate error flags here and
        # set them back when we are finished.
        olderrflags = np.seterr(all='ignore')
        try:
            # Check for collision
            if self._linestyle in ['None', None]:
                # If no line, return the nearby point(s)
                d = (xt - mouseevent.x)**2 + (yt - mouseevent.y)**2
                ind, = np.nonzero(np.less_equal(d, pixels**2))
            else:
                # If line, return the nearby segment(s)
                ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
        finally:
            np.seterr(**olderrflags)

        ind += self.ind_offset

        # Debugging message
        if False and self._label != '':
            print("Checking line", self._label, "at", mouseevent.x,
                  mouseevent.y)
            print('xt', xt)
            print('yt', yt)
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print('ind', ind)

        # Return the point(s) within radius
        return len(ind) > 0, dict(ind=ind)
예제 #20
0
    def __init__(self, xdata, ydata,
                 linewidth       = None, # all Nones default to rc
                 linestyle       = None,
                 color           = None,
                 marker          = None,
                 markersize      = None,
                 markeredgewidth = None,
                 markeredgecolor = None,
                 markerfacecolor = None,
                 antialiased     = None,
                 dash_capstyle   = None,
                 solid_capstyle  = None,
                 dash_joinstyle  = None,
                 solid_joinstyle = None,
                 pickradius      = 5,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are Line2D properties:
        %(Line2D)s
        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None   : linewidth=rcParams['lines.linewidth']

        if linestyle is None   : linestyle=rcParams['lines.linestyle']
        if marker is None      : marker=rcParams['lines.marker']
        if color is None       : color=rcParams['lines.color']
        if markeredgecolor is None :
            markeredgecolor='auto'
        if markerfacecolor is None :
            markerfacecolor='auto'
        if markeredgewidth is None :
            markeredgewidth=rcParams['lines.markeredgewidth']

        if markersize is None  : markersize=rcParams['lines.markersize']
        if antialiased is None : antialiased=rcParams['lines.antialiased']
        if dash_capstyle is None : dash_capstyle=rcParams['lines.dash_capstyle']
        if dash_joinstyle is None : dash_joinstyle=rcParams['lines.dash_joinstyle']
        if solid_capstyle is None : solid_capstyle=rcParams['lines.solid_capstyle']
        if solid_joinstyle is None : solid_joinstyle=rcParams['lines.solid_joinstyle']

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)


        self.set_linestyle(linestyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self.set_marker(marker)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None


        self.set_markerfacecolor(markerfacecolor)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self._point_size_reduction = 0.5

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalid = True
        self.set_data(xdata, ydata)