Exemplo n.º 1
0
    def from_list(name, colors, N=256, gamma=1.0):
        """
        Make a linear segmented colormap with *name* from a sequence
        of *colors* which evenly transitions from colors[0] at val=0
        to colors[-1] at val=1.  *N* is the number of rgb quantization
        levels.
        Alternatively, a list of (value, color) tuples can be given
        to divide the range unevenly.
        """

        if not cbook.iterable(colors):
            raise ValueError('colors must be iterable')

        if cbook.iterable(colors[0]) and len(colors[0]) == 2 and \
                not cbook.is_string_like(colors[0]):
            # List of value, color pairs
            vals, colors = zip(*colors)
        else:
            vals = np.linspace(0., 1., len(colors))

        cdict = dict(red=[], green=[], blue=[])
        for val, color in zip(vals, colors):
            r,g,b = colorConverter.to_rgb(color)
            cdict['red'].append((val, r, r))
            cdict['green'].append((val, g, g))
            cdict['blue'].append((val, b, b))

        return LinearSegmentedColormap(name, cdict, N, gamma)
Exemplo n.º 2
0
 def _get_color(self, c, N=1):
     if looks_like_color(c):
         return  [colorConverter.to_rgba(c)]*N
     elif iterable(c) and len(c) and iterable(c[0]) and len(c[0])==4:
         # looks like a tuple of rgba
         return c
     else:
         raise TypeError('c must be a matplotlib color arg or nonzero length sequence of rgba tuples')
Exemplo n.º 3
0
 def _process_linewidths(self):
     linewidths = self.linewidths
     Nlev = len(self.levels)
     if linewidths is None:
         tlinewidths = [rcParams['lines.linewidth']] *Nlev
     else:
         if iterable(linewidths) and len(linewidths) < Nlev:
             linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
         elif not iterable(linewidths) and type(linewidths) in [int, float]:
             linewidths = [linewidths] * Nlev
         tlinewidths = [(w,) for w in linewidths]
     return tlinewidths
Exemplo n.º 4
0
 def fixlist(args):
     ret = []
     for a in args:
         if iterable(a):
             a = tuple(a)
         ret.append(a)
     return tuple(ret)
Exemplo n.º 5
0
 def invoke_on_elem(working, current_index, previous_indices, args):
     #print 'in invoke_on_elem, args = %s' % (`args`)
     position = previous_indices + [current_index]
     value = working.get_value(position)
     lookup = working.get_lookup(position)
     # check for internal implementation
     if (hasattr(lookup, method_name)):
         #print 'in invoke_on_elem, args = %s' % (`args`)
         arg_list = args
         if (distinct_lookup):
             arg_list = (value, ) + arg_list
         value = getattr(lookup, method_name)(*arg_list)
         # copy check and replace
         working.set_value(position, value)
     else:
         conversion_class = None
         try:
             conversion_class = \
                 self._get_unit_conversion(lookup.__class__)
         except:
             pass
         if (conversion_class):
             # copy check
             arg_list = [value]
             arg_list.extend(args)
             arg_list = tuple(arg_list)
             value = getattr(conversion_class, method_name)(*arg_list)
             # copy check and replace
             working.set_value(position, value)
         elif (iterable(value)):
             for v_index in range(len(value)):
                 invoke_on_elem(working, v_index, position, args)
Exemplo n.º 6
0
    def _process_colors(self, colors, alpha, lev, cmap):
        """
        Color argument processing for contouring.

        Note that we base the color mapping on the contour levels,
        not on the actual range of the Z values.  This means we
        don't have to worry about bad values in Z, and we always have
        the full dynamic range available for the selected levels.
        """
        Nlev = len(lev)
        collections = []
        if colors is not None:

            if is_string_like(colors):
                colors = [colors] * Nlev
            elif iterable(colors) and len(colors) < Nlev:
                colors = list(colors) * Nlev
            else:
                try: gray = float(colors)
                except TypeError: pass
                else:  colors = [gray] * Nlev

            tcolors = [(colorConverter.to_rgba(c, alpha),) for c in colors]
            mappable = None
        else:
            mappable = ContourMappable(lev, collections, cmap=cmap)
            mappable.set_array(lev)
            mappable.autoscale()
            tcolors = [ (tuple(rgba),) for rgba in mappable.to_rgba(lev)]
        return tcolors, mappable, collections
Exemplo n.º 7
0
 def _contour_args(self, *args):
     if self.filled: fn = 'contourf'
     else:           fn = 'contour'
     Nargs = len(args)
     if Nargs <= 2:
         z = args[0]
         x, y = self._initialize_x_y(z)
     elif Nargs <=4:
         x,y,z = self._check_xyz(args[:3])
     else:
         raise TypeError("Too many arguments to %s; see help(%s)" % (fn,fn))
     z = ma.asarray(z)  # Convert to native masked array format if necessary.
     if Nargs == 1 or Nargs == 3:
         lev = self._autolev(z, 7)
     else:   # 2 or 4 args
         level_arg = args[-1]
         if type(level_arg) == int:
             lev = self._autolev(z, level_arg)
         elif iterable(level_arg) and len(shape(level_arg)) == 1:
             lev = array([float(fl) for fl in level_arg])
         else:
             raise TypeError("Last %s arg must give levels; see help(%s)" % (fn,fn))
     if self.filled and len(lev) < 2:
         raise ValueError("Filled contours require at least 2 levels.")
     # Workaround for cntr.c bug wrt masked interior regions:
     #if filled:
     #    z = ma.masked_array(z.filled(-1e38))
     # It's not clear this is any better than the original bug.
     self.levels = lev
     self.layers = self.levels # contour: a line is a thin layer
     if self.filled:
         self.layers = 0.5 * (self.levels[:-1] + self.levels[1:])
     return (x, y, z)
Exemplo n.º 8
0
def longest_ones(x):
    """
    return the indicies of the longest stretch of contiguous ones in x,
    assuming x is a vector of zeros and ones.

    If there are two equally long stretches, pick the first
    """
    x = asarray(x)
    if len(x) == 0: return array([])

    #print 'x', x
    ind = find(x == 0)
    if len(ind) == 0: return arange(len(x))
    if len(ind) == len(x): return array([])

    y = zeros((len(x) + 2, ), Int)
    y[1:-1] = x
    d = diff(y)
    #print 'd', d
    up = find(d == 1)
    dn = find(d == -1)

    #print 'dn', dn, 'up', up,
    ind = find(dn - up == max(dn - up))
    # pick the first
    if iterable(ind): ind = ind[0]
    ind = arange(up[ind], dn[ind])

    return ind
Exemplo n.º 9
0
def hist(y, bins=10, normed=0):
    """
    Return the histogram of y with bins equally sized bins.  If bins
    is an array, use the bins.  Return value is
    (n,x) where n is the count for each bin in x

    If normed is False, return the counts in the first element of the
    return tuple.  If normed is True, return the probability density
    n/(len(y)*dbin)

    If y has rank>1, it will be raveled
    Credits: the Numeric 22 documentation

    

    """
    y = asarray(y)
    if len(y.shape) > 1: y = ravel(y)

    if not iterable(bins):
        ymin, ymax = min(y), max(y)
        if ymin == ymax:
            ymin -= 0.5
            ymax += 0.5
        bins = linspace(ymin, ymax, bins)

    n = searchsorted(sort(y), bins)
    n = diff(concatenate([n, [len(y)]]))
    if normed:
        db = bins[1] - bins[0]
        return 1 / (len(y) * db) * n, bins
    else:
        return n, bins
Exemplo n.º 10
0
 def fixitems(items):
     ret = []
     for k, v in items:
         if iterable(v):
             v = tuple(v)
         ret.append((k, v))
     return tuple(ret)
Exemplo n.º 11
0
 def _contour_args(self, filled, badmask, origin, extent, *args):
     if filled: fn = 'contourf'
     else:      fn = 'contour'
     Nargs = len(args)
     if Nargs <= 2:
         z = args[0]
         x, y = self._initialize_x_y(z, origin, extent)
     elif Nargs <=4:
         x,y,z = self._check_xyz(args[:3])
     else:
         raise TypeError("Too many arguments to %s; see help(%s)" % (fn,fn))
     z = asarray(z)  # Convert to native array format if necessary.
     if Nargs == 1 or Nargs == 3:
         lev = self._autolev(z, 7, filled, badmask)
     else:   # 2 or 4 args
         level_arg = args[-1]
         if type(level_arg) == int:
             lev = self._autolev(z, level_arg, filled, badmask)
         elif iterable(level_arg) and len(shape(level_arg)) == 1:
             lev = array([float(fl) for fl in level_arg])
         else:
             raise TypeError("Last %s arg must give levels; see help(%s)" % (fn,fn))
     rx = ravel(x)
     ry = ravel(y)
     self.ax.set_xlim((min(rx), max(rx)))
     self.ax.set_ylim((min(ry), max(ry)))
     return (x, y, z, lev)
Exemplo n.º 12
0
def hist(y, bins=10, normed=0):
    """
    Return the histogram of y with bins equally sized bins.  If bins
    is an array, use the bins.  Return value is
    (n,x) where n is the count for each bin in x

    If normed is False, return the counts in the first element of the
    return tuple.  If normed is True, return the probability density
    n/(len(y)*dbin)

    If y has rank>1, it will be raveled
    Credits: the Numeric 22 documentation

    

    """
    y = asarray(y)
    if len(y.shape)>1: y = ravel(y)

    if not iterable(bins):       
        ymin, ymax = min(y), max(y)
        if ymin==ymax:
            ymin -= 0.5
            ymax += 0.5
        bins = linspace(ymin, ymax, bins)

    n = searchsorted(sort(y), bins)
    n = diff(concatenate([n, [len(y)]]))
    if normed:
       db = bins[1]-bins[0]
       return 1/(len(y)*db)*n, bins
    else:
       return n, bins
Exemplo n.º 13
0
def longest_ones(x):
    """
    return the indicies of the longest stretch of contiguous ones in x,
    assuming x is a vector of zeros and ones.

    If there are two equally long stretches, pick the first
    """
    x = asarray(x)
    if len(x)==0: return array([])

    #print 'x', x
    ind = find(x==0)
    if len(ind)==0:  return arange(len(x))
    if len(ind)==len(x): return array([])

    y = zeros( (len(x)+2,), Int)
    y[1:-1] = x
    d = diff(y)
    #print 'd', d
    up = find(d ==  1);
    dn = find(d == -1);

    #print 'dn', dn, 'up', up, 
    ind = find( dn-up == max(dn - up))
    # pick the first
    if iterable(ind): ind = ind[0]
    ind = arange(up[ind], dn[ind])

    return ind
Exemplo n.º 14
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        def get_tbounds(text):  #get text bounds in axes coords
            bbox = text.get_window_extent(renderer)
            bboxa = inverse_transform_bbox(self._transform, bbox)
            return bboxa.get_bounds()
            
        hpos = []
        for t, tabove in zip(self.texts[1:], self.texts[:-1]):
            x,y = t.get_position()
            l,b,w,h = get_tbounds(tabove)
            hpos.append( (b,h) )
            t.set_position( (x, b-0.1*h) )

        # now do the same for last line
        l,b,w,h = get_tbounds(self.texts[-1])
        hpos.append( (b,h) )
        
        for handle, tup in zip(self.handles, hpos):
            y,h = tup
            if isinstance(handle, Line2D):
                ydata = y*ones(self._xdata.shape, Float)            
                handle.set_ydata(ydata+h/2)
            elif isinstance(handle, Rectangle):
                handle.set_y(y+1/4*h)
                handle.set_height(h/2)

        # Set the data for the legend patch
        bbox = self._get_handle_text_bbox(renderer).deepcopy()
        bbox.scale(1 + self.pad, 1 + self.pad)
        l,b,w,h = bbox.get_bounds()
        self.legendPatch.set_bounds(l,b,w,h)

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
        ox, oy = 0, 0                           # center


        if iterable(self._loc) and len(self._loc)==2:
            xo = self.legendPatch.get_x()
            yo = self.legendPatch.get_y()
            x, y = self._loc
            ox = x-xo
            oy = y-yo
            self._offset(ox, oy)
        else:
            if self._loc in (UL, LL, CL):           # left
                ox = self.axespad - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.axespad)
            if self._loc in (BEST, UR, UL, UC):     # upper
                oy = 1 - (b + h + self.axespad)
            if self._loc in (LL, LR, LC):           # lower
                oy = self.axespad - b
            if self._loc in (LC, UC, C):            # center x
                ox = (0.5-w/2)-l
            if self._loc in (CL, CR, C):            # center y
                oy = (0.5-h/2)-b
            self._offset(ox, oy)
Exemplo n.º 15
0
 def invoke_on_elem(working, current_index, previous_indices, args):
     #print 'in invoke_on_elem, args = %s' % (`args`)
     position = previous_indices + [current_index]
     value = working.get_value(position)
     lookup = working.get_lookup(position)
     # check for internal implementation
     if (hasattr(lookup, method_name)):
         #print 'in invoke_on_elem, args = %s' % (`args`)
         arg_list = args
         if (distinct_lookup):
             arg_list = (value,) + arg_list
         value = getattr(lookup, method_name)(*arg_list)
         # copy check and replace
         working.set_value(position, value)
     else:
         conversion_class = None
         try:
             conversion_class = \
                 self._get_unit_conversion(lookup.__class__)
         except: pass
         if (conversion_class):
             # copy check
             arg_list = [value]
             arg_list.extend(args)
             arg_list = tuple(arg_list)
             value = getattr(conversion_class, method_name)(*arg_list)
             # copy check and replace
             working.set_value(position, value)
         elif (iterable(value)):
             for v_index in range(len(value)):
                 invoke_on_elem(working, v_index, position, args)
Exemplo n.º 16
0
    def draw(self, renderer):
        if self._invalid:
            self.recache()

        renderer.open_group('line2d', self.get_gid())

        if not self._visible: return
        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        gc.set_foreground(self._color)
        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)
        gc.set_alpha(self._alpha)
        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)
        gc.set_snap(self.get_snap())

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = self._transformed_path.get_transformed_path_and_affine(
            )
            self._lineFunc = getattr(self, funcname)
            funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
            drawFunc = getattr(self, funcname)
            drawFunc(renderer, gc, tpath, affine.frozen())

        if self._marker is not None:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            gc.set_foreground(self.get_markeredgecolor())
            gc.set_linewidth(self._markeredgewidth)
            gc.set_alpha(self._alpha)
            funcname = self._markers.get(self._marker, '_draw_nothing')
            if funcname != '_draw_nothing':
                tpath, affine = self._transformed_path.get_transformed_points_and_affine(
                )

                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    if iterable(markevery):
                        startind, stride = markevery
                    else:
                        startind, stride = 0, markevery
                        if tpath.codes is not None:
                            tpath.codes = tpath.codes[startind::stride]
                        tpath.vertices = tpath.vertices[startind::stride]

                markerFunc = getattr(self, funcname)
                markerFunc(renderer, gc, tpath, affine.frozen())

        renderer.close_group('line2d')
Exemplo n.º 17
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        def get_tbounds(text):  #get text bounds in axes coords
            bbox = text.get_window_extent(renderer)
            bboxa = inverse_transform_bbox(self._transform, bbox)
            return bboxa.get_bounds()

        hpos = []
        for t, tabove in zip(self.texts[1:], self.texts[:-1]):
            x, y = t.get_position()
            l, b, w, h = get_tbounds(tabove)
            hpos.append((b, h))
            t.set_position((x, b - 0.1 * h))

        # now do the same for last line
        l, b, w, h = get_tbounds(self.texts[-1])
        hpos.append((b, h))

        for handle, tup in zip(self.handles, hpos):
            y, h = tup
            if isinstance(handle, Line2D):
                ydata = y * ones(self._xdata.shape, Float)
                handle.set_ydata(ydata + h / 2)
            elif isinstance(handle, Rectangle):
                handle.set_y(y + 1 / 4 * h)
                handle.set_height(h / 2)

        # Set the data for the legend patch
        bbox = self._get_handle_text_bbox(renderer).deepcopy()
        bbox.scale(1 + self.pad, 1 + self.pad)
        l, b, w, h = bbox.get_bounds()
        self.legendPatch.set_bounds(l, b, w, h)

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
        ox, oy = 0, 0  # center

        if iterable(self._loc) and len(self._loc) == 2:
            xo = self.legendPatch.get_x()
            yo = self.legendPatch.get_y()
            x, y = self._loc
            ox = x - xo
            oy = y - yo
            self._offset(ox, oy)
        else:
            if self._loc in (UL, LL, CL):  # left
                ox = self.axespad - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.axespad)
            if self._loc in (BEST, UR, UL, UC):  # upper
                oy = 1 - (b + h + self.axespad)
            if self._loc in (LL, LR, LC):  # lower
                oy = self.axespad - b
            if self._loc in (LC, UC, C):  # center x
                ox = (0.5 - w / 2) - l
            if self._loc in (CL, CR, C):  # center y
                oy = (0.5 - h / 2) - b
            self._offset(ox, oy)
Exemplo n.º 18
0
 def fixitems(items):
     #items may have arrays and lists in them, so convert them
     # to tuples for the key
     ret = []
     for k, v in items:
         if iterable(v): v = tuple(v)
         ret.append((k,v))
     return tuple(ret)
Exemplo n.º 19
0
 def fixitems(items):
     #items may have arrays and lists in them, so convert them
     # to tuples for the key
     ret = []
     for k, v in items:
         if iterable(v): v = tuple(v)
         ret.append((k, v))
     return tuple(ret)
Exemplo n.º 20
0
    def draw(self, renderer):
        if self._invalid:
            self.recache()

        renderer.open_group('line2d', self.get_gid())

        if not self._visible: return
        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        gc.set_foreground(self._color)
        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)
        gc.set_alpha(self._alpha)
        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)
        gc.set_snap(self.get_snap())

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = self._transformed_path.get_transformed_path_and_affine()
            self._lineFunc = getattr(self, funcname)
            funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
            drawFunc = getattr(self, funcname)
            drawFunc(renderer, gc, tpath, affine.frozen())

        if self._marker is not None:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            gc.set_foreground(self.get_markeredgecolor())
            gc.set_linewidth(self._markeredgewidth)
            gc.set_alpha(self._alpha)
            funcname = self._markers.get(self._marker, '_draw_nothing')
            if funcname != '_draw_nothing':
                tpath, affine = self._transformed_path.get_transformed_points_and_affine()

                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    if iterable(markevery):
                        startind, stride = markevery
                    else:
                        startind, stride = 0, markevery
                        if tpath.codes is not None:
                            tpath.codes = tpath.codes[startind::stride]
                        tpath.vertices = tpath.vertices[startind::stride]


                markerFunc = getattr(self, funcname)
                markerFunc(renderer, gc, tpath, affine.frozen())

        renderer.close_group('line2d')
Exemplo n.º 21
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        if not len(self.legendHandles) and not len(self.texts): return

        def get_tbounds(text):  #get text bounds in axes coords
            bbox = text.get_window_extent(renderer)
            bboxa = bbox.inverse_transformed(self.get_transform())
            return bboxa.bounds

        hpos = []
        for t, tabove in safezip(self.texts[1:], self.texts[:-1]):
            x, y = t.get_position()
            l, b, w, h = get_tbounds(tabove)
            b -= self.labelsep
            h += 2 * self.labelsep
            hpos.append((b, h))
            t.set_position((x, b - 0.1 * h))

        # now do the same for last line

        l, b, w, h = get_tbounds(self.texts[-1])
        b -= self.labelsep
        h += 2 * self.labelsep
        hpos.append((b, h))

        for handle, tup in safezip(self.legendHandles, hpos):
            y, h = tup
            if isinstance(handle, Line2D):
                ydata = y * np.ones(handle.get_xdata().shape, float)
                handle.set_ydata(ydata + h / 2.)
                handle._legmarker.set_ydata(ydata + h / 2.)
            elif isinstance(handle, Rectangle):
                handle.set_y(y + 1 / 4 * h)
                handle.set_height(h / 2)

        # Set the data for the legend patch
        bbox = self._get_handle_text_bbox(renderer)

        bbox = bbox.expanded(1 + self.pad, 1 + self.pad)
        l, b, w, h = bbox.bounds
        self.legendPatch.set_bounds(l, b, w, h)

        ox, oy = 0, 0  # center

        if iterable(self._loc) and len(self._loc) == 2:
            xo = self.legendPatch.get_x()
            yo = self.legendPatch.get_y()
            x, y = self._loc
            ox, oy = x - xo, y - yo
        elif self._loc == 0:  # "best"
            ox, oy = self._find_best_position(w, h)
        else:
            x, y = self._loc_to_axes_coords(self._loc, w, h)
            ox, oy = x - l, y - b

        self._offset(ox, oy)
Exemplo n.º 22
0
    def _contour_args(self, *args):
        if self.filled: fn = 'contourf'
        else:           fn = 'contour'
        Nargs = len(args)
        if Nargs <= 2:
            z = args[0]
            x, y = self._initialize_x_y(z)
        elif Nargs <=4:
            x,y,z = self._check_xyz(args[:3])
        else:
            raise TypeError("Too many arguments to %s; see help(%s)" % (fn,fn))
        z = ma.asarray(z)  # Convert to native masked array format if necessary.
        self.zmax = ma.maximum(z)
        self.zmin = ma.minimum(z)
        self._auto = False
        if self.levels is None:
            if Nargs == 1 or Nargs == 3:
                lev = self._autolev(z, 7)
            else:   # 2 or 4 args
                level_arg = args[-1]
                if type(level_arg) == int:
                    lev = self._autolev(z, level_arg)
                elif iterable(level_arg) and len(shape(level_arg)) == 1:
                    lev = array([float(fl) for fl in level_arg])
                else:
                    raise TypeError("Last %s arg must give levels; see help(%s)" % (fn,fn))
            if self.filled and len(lev) < 2:
                raise ValueError("Filled contours require at least 2 levels.")
            # Workaround for cntr.c bug wrt masked interior regions:
            #if filled:
            #    z = ma.masked_array(z.filled(-1e38))
            # It's not clear this is any better than the original bug.
            self.levels = lev
        #if self._auto and self.extend in ('both', 'min', 'max'):
        #    raise TypeError("Auto level selection is inconsistent "
        #                             + "with use of 'extend' kwarg")
        self._levels = list(self.levels)
        if self.extend in ('both', 'min'):
            self._levels.insert(0, self.zmin - 1)
        if self.extend in ('both', 'max'):
            self._levels.append(self.zmax + 1)
        self._levels = asarray(self._levels)
        self.vmin = amin(self.levels)  # alternative would be self.layers
        self.vmax = amax(self.levels)
        if self.extend in ('both', 'min') or self.clip_ends:
            self.vmin = 2 * self.levels[0] - self.levels[1]
        if self.extend in ('both', 'max') or self.clip_ends:
            self.vmax = 2 * self.levels[-1] - self.levels[-2]
        self.layers = self._levels # contour: a line is a thin layer
        if self.filled:
            self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
            if self.extend in ('both', 'min') or self.clip_ends:
                self.layers[0] = 0.5 * (self.vmin + self._levels[1])
            if self.extend in ('both', 'max') or self.clip_ends:
                self.layers[-1] = 0.5 * (self.vmax + self._levels[-2])

        return (x, y, z)
Exemplo n.º 23
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        if not len(self.legendHandles) and not len(self.texts): return
        def get_tbounds(text):  #get text bounds in axes coords
            bbox = text.get_window_extent(renderer)
            bboxa = bbox.inverse_transformed(self.get_transform())
            return bboxa.bounds

        hpos = []
        for t, tabove in safezip(self.texts[1:], self.texts[:-1]):
            x,y = t.get_position()
            l,b,w,h = get_tbounds(tabove)
            b -= self.labelsep
            h += 2*self.labelsep
            hpos.append( (b,h) )
            t.set_position( (x, b-0.1*h) )

        # now do the same for last line

        l,b,w,h = get_tbounds(self.texts[-1])
        b -= self.labelsep
        h += 2*self.labelsep
        hpos.append( (b,h) )

        for handle, tup in safezip(self.legendHandles, hpos):
            y,h = tup
            if isinstance(handle, Line2D):
                ydata = y*np.ones(handle.get_xdata().shape, float)
                handle.set_ydata(ydata+h/2.)
                handle._legmarker.set_ydata(ydata+h/2.)
            elif isinstance(handle, Rectangle):
                handle.set_y(y+1/4*h)
                handle.set_height(h/2)

        # Set the data for the legend patch
        bbox = self._get_handle_text_bbox(renderer)

        bbox = bbox.expanded(1 + self.pad, 1 + self.pad)
        l, b, w, h = bbox.bounds
        self.legendPatch.set_bounds(l, b, w, h)

        ox, oy = 0, 0                           # center

        if iterable(self._loc) and len(self._loc)==2:
            xo = self.legendPatch.get_x()
            yo = self.legendPatch.get_y()
            x, y = self._loc
            ox, oy = x-xo, y-yo
        elif self._loc == 0:  # "best"
            ox, oy = self._find_best_position(w, h)
        else:
            x, y = self._loc_to_axes_coords(self._loc, w, h)
            ox, oy = x-l, y-b

        self._offset(ox, oy)
Exemplo n.º 24
0
    def _get_value(self, val):
        try: return (float(val), )
        except TypeError:
            if iterable(val) and len(val):
                try: float(val[0])
                except TypeError: pass # raise below
                else: return val

        raise TypeError('val must be a float or nonzero sequence of floats')
Exemplo n.º 25
0
    def _get_value(self, val):
        try: return (float(val), )
        except TypeError:
            if iterable(val) and len(val):
                try: float(val[0])
                except TypeError: pass # raise below
                else: return val

        raise TypeError('val must be a float or nonzero sequence of floats')
Exemplo n.º 26
0
def date2num(d):
    """
    d is either a datetime instance or a sequence of datetimes

    return value is a floating point number (or sequence of floats)
    which gives number of days (fraction part represents hours,
    minutes, seconds) since 0001-01-01 00:00:00 UTC
    """
    if not iterable(d): return _to_ordinalf(d)
    else: return [_to_ordinalf(val) for val in d]
Exemplo n.º 27
0
 def __init__(self, o):
     """
     Initialize the artist inspector with an artist or sequence of
     artists.  Id a sequence is used, we assume it is a homogeneous
     sequence (all Artists are of the same type) and it is your
     responsibility to make sure this is so.
     """
     if iterable(o): o = o[0]
     self.o = o
     self.aliasd = self.get_aliases()
Exemplo n.º 28
0
 def __init__(self, o):
     """
     Initialize the artist inspector with an artist or sequence of
     artists.  Id a sequence is used, we assume it is a homogeneous
     sequence (all Artists are of the same type) and it is your
     responsibility to make sure this is so.
     """
     if iterable(o) and len(o): o = o[0]
     self.o = o
     self.aliasd = self.get_aliases()
Exemplo n.º 29
0
def date2num(d):
    """
    d is either a datetime instance or a sequence of datetimes

    return value is a floating point number (or sequence of floats)
    which gives number of days (fraction part represents hours,
    minutes, seconds) since 0001-01-01 00:00:00 UTC
    """
    if not iterable(d): return _to_ordinalf(d)
    else: return [_to_ordinalf(val) for val in d]
Exemplo n.º 30
0
    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axes with key *args, *kwargs then it will
simply make that axes current and return it.  If you do not want this
behavior, eg you want to force the creation of a new axes, you must
use a unique set of args and kwargs.  The artist "label" attribute has
been exposed for this purpose.  Eg, if you want two axes that are
otherwise identical to be added to the axes, make sure you give them
unique labels:

    add_axes((l,b,w,h), label='1')
    add_axes((l,b,w,h), label='2')

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())            

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return        
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)            
                

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
Exemplo n.º 31
0
    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axes with key *args, *kwargs then it will
simply make that axes current and return it.  If you do not want this
behavior, eg you want to force the creation of a new axes, you must
use a unique set of args and kwargs.  The artist "label" attribute has
been exposed for this purpose.  Eg, if you want two axes that are
otherwise identical to be added to the axes, make sure you give them
unique labels:

    add_axes((l,b,w,h), label='1')
    add_axes((l,b,w,h), label='2')

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
Exemplo n.º 32
0
    def to_rgb(self, arg):
        """
        Returns an *RGB* tuple of three floats from 0-1.

        *arg* can be an *RGB* or *RGBA* sequence or a string in any of
        several forms:

            1) a letter from the set 'rgbcmykw'
            2) a hex color string, like '#00FFFF'
            3) a standard name, like 'aqua'
            4) a float, like '0.4', indicating gray on a 0-1 scale

        if *arg* is *RGBA*, the *A* will simply be discarded.
        """
        try: return self.cache[arg]
        except KeyError: pass
        except TypeError: # could be unhashable rgb seq
            arg = tuple(arg)
            try: return self.cache[arg]
            except KeyError: pass
            except TypeError:
                raise ValueError(
                      'to_rgb: arg "%s" is unhashable even inside a tuple'
                                    % (str(arg),))

        try:
            if cbook.is_string_like(arg):
                argl = arg.lower()
                color = self.colors.get(argl, None)
                if color is None:
                    str1 = cnames.get(argl, argl)
                    if str1.startswith('#'):
                        color = hex2color(str1)
                    else:
                        fl = float(argl)
                        if fl < 0 or fl > 1:
                            raise ValueError(
                                   'gray (string) must be in range 0-1')
                        color = tuple([fl]*3)
            elif cbook.iterable(arg):
                if len(arg) > 4 or len(arg) < 3:
                    raise ValueError(
                           'sequence length is %d; must be 3 or 4'%len(arg))
                color = tuple(arg[:3])
                if [x for x in color if (float(x) < 0) or  (x > 1)]:
                    # This will raise TypeError if x is not a number.
                    raise ValueError('number in rbg sequence outside 0-1 range')
            else:
                raise ValueError('cannot convert argument to rgb sequence')

            self.cache[arg] = color

        except (KeyError, ValueError, TypeError), exc:
            raise ValueError('to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))
Exemplo n.º 33
0
def mx2num(mxdates):
    """
    Convert mx datetime instance (or sequence of mx instances) to the
    new date format,
    """
    scalar = False
    if not iterable(mxdates):
        scalar = True
        mxdates = [mxdates]
    ret = epoch2num([m.ticks() for m in mxdates])
    if scalar: return ret[0]
    else: return ret
Exemplo n.º 34
0
 def _add_offsets(self, offsets):
     segs = self._segments
     Nsegs = len(segs)
     Noffs = len(offsets)
     if not iterable(offsets[0]):  # i.e., not a tuple but an x-offset
         xo, yo = offsets
         for i in range(Nsegs):
             segs[i] = [(x + xo * i, y + yo * i) for x, y in segs[i]]
     else:
         for i in range(Nsegs):
             xo, yo = offsets[i % Noffs]
             segs[i] = [(x + xo, y + yo) for x, y in segs[i]]
Exemplo n.º 35
0
    def set_linestyle(self, ls):
        """
Set the linestyles(s) for the collection.  
ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |  (offset, on-off-dash-seq) ]"""
        if is_string_like(ls):
            dashes = GraphicsContextBase.dashd[ls]            
        elif iterable(ls) and len(ls)==2:
            dashes = ls
        else: raise ValueError('Do not know how to convert %s to dashes'%ls)

        
        self._ls = dashes
Exemplo n.º 36
0
def mx2num(mxdates):
    """
    Convert mx datetime instance (or sequence of mx instances) to the
    new date format,
    """
    scalar = False
    if not iterable(mxdates):
        scalar = True
        mxdates = [mxdates]
    ret = epoch2num([m.ticks() for m in mxdates])
    if scalar: return ret[0]
    else: return ret
Exemplo n.º 37
0
    def set_linestyle(self, ls):
        """
Set the linestyles(s) for the collection.  
ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |  (offset, on-off-dash-seq) ]"""
        if is_string_like(ls):
            dashes = GraphicsContextBase.dashd[ls]
        elif iterable(ls) and len(ls) == 2:
            dashes = ls
        else:
            raise ValueError('Do not know how to convert %s to dashes' % ls)

        self._ls = dashes
Exemplo n.º 38
0
 def _add_offsets(self, offsets):
     segs = self._segments
     Nsegs = len(segs)
     Noffs = len(offsets)
     if not iterable(offsets[0]):  # i.e., not a tuple but an x-offset
         xo, yo = offsets
         for i in range(Nsegs):
             segs[i] = [(x+xo*i, y+yo*i) for x,y in segs[i]]
     else:
         for i in range(Nsegs):
             xo, yo = offsets[i%Noffs]
             segs[i] = [(x+xo, y+yo) for x,y in segs[i]]
    def to_rgb(self, arg, warn=True):
        """
        Returns an RGB tuple of three floats from 0-1.

        arg can be an RGB sequence or a string in any of several forms:
            1) a letter from the set 'rgbcmykw'
            2) a hex color string, like '#00FFFF'
            3) a standard name, like 'aqua'
            4) a float, like '0.4', indicating gray on a 0-1 scale
        """
        # warn kwarg will go away when float-as-grayscale does
        try: return self.cache[arg]
        except KeyError: pass
        except TypeError: # could be unhashable rgb seq
            arg = tuple(arg)
            try: self.cache[arg]
            except KeyError: pass
            except TypeError:
                raise ValueError('to_rgb: unhashable even inside a tuple')

        try:
            if is_string_like(arg):
                str1 = cnames.get(arg, arg)
                if str1.startswith('#'):
                    color = hex2color(str1)
                else:
                    try:
                        color = self.colors[arg]
                    except KeyError:
                        color = tuple([float(arg)]*3)
            elif iterable(arg):   # streamline this after removing float case
                color = tuple(arg[:3])
                if [x for x in color if (x < 0) or  (x > 1)]:
                    raise ValueError('to_rgb: Invalid rgb arg "%s"' % (str(arg)))
            elif isinstance(arg, (float,int)):
                #raise Exception('number is %s' % str(arg))
                if warn: warnings.warn(
                    "For gray use a string, '%s', not a float, %s" %
                                                (str(arg), str(arg)),
                                                DeprecationWarning)
                else: self._gray = True
                if 0 <= arg <= 1:
                    color = (arg,arg,arg)
                else:
                    raise ValueError('Floating point color arg must be between 0 and 1')
            else:
                raise ValueError('to_rgb: Invalid rgb arg "%s"' % (str(arg)))

            self.cache[arg] = color

        except (KeyError, ValueError, TypeError), exc:
            raise ValueError('to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))
Exemplo n.º 40
0
def num2date(x, tz=None):
    """
    x is a float value which gives number of days (fraction part
    represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC

    Return value is a datetime instance in timezone tz (default to
    rcparams TZ value)

    if x is a sequence, a sequence of datetimes will be returned
    """
    if tz is None: tz = _get_rc_timezone()
    if not iterable(x): return _from_ordinalf(x, tz)
    else: return [_from_ordinalf(val, tz) for val in x]
Exemplo n.º 41
0
def num2date(x, tz=None):
    """
    x is a float value which gives number of days (fraction part
    represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC

    Return value is a datetime instance in timezone tz (default to
    rcparams TZ value)

    if x is a sequence, a sequence of datetimes will be returned
    """
    if tz is None: tz = _get_rc_timezone()
    if not iterable(x): return _from_ordinalf(x, tz)
    else: return [_from_ordinalf(val, tz) for val in x]
Exemplo n.º 42
0
def looks_like_color(c):
    if is_string_like(c):
        if cnames.has_key(c): return True
        elif len(c) == 1: return True
        elif len(c) == 7 and c.startswith('#') and len(c) == 7: return True
        else: return False
    elif iterable(c) and len(c) == 3:
        try:
            rgb = [float(val) for val in c]
            return True
        except:
            return False
    else:
        return False
Exemplo n.º 43
0
def looks_like_color(c):
    if is_string_like(c):
        if cnames.has_key(c): return True
        elif len(c)==1: return True
        elif len(c)==7 and c.startswith('#') and len(c)==7: return True
        else: return False
    elif iterable(c) and len(c)==3:
        try:
            rgb = [float(val) for val in c]
            return True
        except:
            return False
    else:
        return False
def looks_like_color(c):
    warnings.warn('Use is_color_like instead!', DeprecationWarning)
    if is_string_like(c):
        if cnames.has_key(c): return True
        elif len(c)==1: return True
        elif len(c)==7 and c.startswith('#') and len(c)==7: return True
        else: return False
    elif iterable(c) and len(c)==3:
        try:
            rgb = [float(val) for val in c]
            return True
        except:
            return False
    else:
        return False
Exemplo n.º 45
0
def looks_like_color(c):
    warnings.warn('Use is_color_like instead!', DeprecationWarning)
    if is_string_like(c):
        if cnames.has_key(c): return True
        elif len(c) == 1: return True
        elif len(c) == 7 and c.startswith('#') and len(c) == 7: return True
        else: return False
    elif iterable(c) and len(c) == 3:
        try:
            rgb = [float(val) for val in c]
            return True
        except:
            return False
    else:
        return False
Exemplo n.º 46
0
def prctile(x, p = (0.0, 25.0, 50.0, 75.0, 100.0)):
    """
    Return the percentiles of x.  p can either be a sequence of
    percentil values or a scalar.  If p is a sequence the i-th element
    of the return sequence is the p(i)-th percentile of x
    """
    x = sort(ravel(x))
    Nx = len(x)

    if not iterable(p):
        return x[int(p*Nx/100.0)]

    p = multiply(array(p), Nx/100.0)
    ind = p.astype(Int)
    ind = where(ind>=Nx, Nx-1, ind)        
    return take(x, ind)
Exemplo n.º 47
0
def prctile(x, p = (0.0, 25.0, 50.0, 75.0, 100.0)):
    """
    Return the percentiles of x.  p can either be a sequence of
    percentil values or a scalar.  If p is a sequence the i-th element
    of the return sequence is the p(i)-th percentile of x
    """
    x = sort(ravel(x))
    Nx = len(x)

    if not iterable(p):
        return x[int(p*Nx/100.0)]

    p = multiply(array(p), Nx/100.0)
    ind = p.astype(Int)
    ind = where(ind>=Nx, Nx-1, ind)        
    return take(x, ind)
Exemplo n.º 48
0
    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axed with key *args, *kwargs then it
will simply make that axes current and return it

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())            

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return        
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)            
                

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
Exemplo n.º 49
0
    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axed with key *args, *kwargs then it
will simply make that axes current and return it

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
Exemplo n.º 50
0
    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the kyey
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)
                ret.append((k, v))
            return ret

        if iterable(args[0]):
            key = tuple(args[0]), tuple(fixitems(kwargs.items()))
        else:
            key = args[0], tuple(fixitems(kwargs.items()))
        return key
Exemplo n.º 51
0
    def to_rgba(self, arg, alpha=None, warn=True):
        """
        Returns an RGBA tuple of four floats from 0-1.

        For acceptable values of arg, see to_rgb.  In
        addition, arg may already be an rgba sequence, in which
        case it is returned unchanged if the alpha kwarg is None,
        or takes on the specified alpha.
        """
        if not is_string_like(arg) and iterable(arg):
            if len(arg) == 4 and alpha is None:
                return tuple(arg)
            r, g, b = arg[:3]
        else:
            r, g, b = self.to_rgb(arg, warn)
        if alpha is None:
            alpha = 1.0
        return r, g, b, alpha
Exemplo n.º 52
0
    def set_marker(self, marker):
        if (iterable(marker) and len(marker) in (2, 3) and
            marker[1] in (0, 1, 2, 3)):
            self._marker_function = self._set_tuple_marker
        elif marker in self.markers:
            self._marker_function = getattr(
                self, '_set_' + self.markers[marker])
        elif is_string_like(marker) and is_math_text(marker):
            self._marker_function = self._set_mathtext_path
        elif isinstance(marker, Path):
            self._marker_function = self._set_path_marker
        else:
            try:
                path = Path(marker)
                self._marker_function = self._set_vertices
            except:
                raise ValueError('Unrecognized marker style %s' % marker)

        self._marker = marker
        self._recache()
Exemplo n.º 53
0
    def _process_colors(self, z, colors, alpha, lev, cmap):
        """
        Color argument processing for contouring.

        Note that we base the color mapping on the contour levels,
        not on the actual range of the Z values.  This means we
        don't have to worry about bad values in Z, and we always have
        the full dynamic range available for the selected levels.

        The input argument Z is not actually being used now; if
        using the levels for autoscaling instead of Z works well,
        then it will be removed.
        """
        Nlev = len(lev)
        collections = []
        if colors is not None:

            if is_string_like(colors):
                colors = [colors] * Nlev
            elif iterable(colors) and len(colors) < Nlev:
                colors = list(colors) * Nlev
            else:
                try:
                    gray = float(colors)
                except TypeError:
                    pass
                else:
                    colors = [gray] * Nlev

            tcolors = [(colorConverter.to_rgba(c, alpha), ) for c in colors]
            mappable = None
        else:
            mappable = ContourMappable(lev, collections, cmap=cmap)
            #mappable.set_array(z)
            mappable.set_array(lev)
            mappable.autoscale()
            tcolors = [(tuple(rgba), ) for rgba in mappable.to_rgba(lev)]
        return tcolors, mappable, collections
Exemplo n.º 54
0
 def __call__(self, X, alpha=1.0):
     """
     X is either a scalar or an array (of any dimension).
     If scalar, a tuple of rgba values is returned, otherwise
     an array with the new shape = oldshape+(4,). If the X-values
     are integers, then they are used as indices into the array.
     If they are floating point, then they must be in the
     interval (0.0, 1.0).
     Alpha must be a scalar.
     """
     if not self._isinit: self._init()
     alpha = min(alpha, 1.0)  # alpha must be between 0 and 1
     alpha = max(alpha, 0.0)
     self._lut[:-3, -1] = alpha
     mask_bad = None
     if not iterable(X):
         vtype = 'scalar'
         xa = array([X])
     else:
         vtype = 'array'
         xma = ma.asarray(X)
         xa = xma.filled(0)
         mask_bad = ma.getmaskorNone(xma)
     if typecode(xa) in typecodes['Float']:
         xa = where(xa == 1.0, 0.9999999, xa)  # Tweak so 1.0 is in range.
         xa = (xa * self.N).astype(Int)
     mask_under = xa < 0
     mask_over = xa > self.N - 1
     xa = where(mask_under, self._i_under, xa)
     xa = where(mask_over, self._i_over, xa)
     if mask_bad is not None:  # and sometrue(mask_bad):
         xa = where(mask_bad, self._i_bad, xa)
     rgba = take(self._lut, xa)
     if vtype == 'scalar':
         rgba = tuple(rgba[0, :])
     return rgba
Exemplo n.º 55
0
 def _contour_args(self, *args):
     if self.filled: fn = 'contourf'
     else: fn = 'contour'
     Nargs = len(args)
     if Nargs <= 2:
         z = args[0]
         x, y = self._initialize_x_y(z)
     elif Nargs <= 4:
         x, y, z = self._check_xyz(args[:3])
     else:
         raise TypeError("Too many arguments to %s; see help(%s)" %
                         (fn, fn))
     z = ma.asarray(
         z)  # Convert to native masked array format if necessary.
     if Nargs == 1 or Nargs == 3:
         lev = self._autolev(z, 7)
     else:  # 2 or 4 args
         level_arg = args[-1]
         if type(level_arg) == int:
             lev = self._autolev(z, level_arg)
         elif iterable(level_arg) and len(shape(level_arg)) == 1:
             lev = array([float(fl) for fl in level_arg])
         else:
             raise TypeError("Last %s arg must give levels; see help(%s)" %
                             (fn, fn))
     if self.filled and len(lev) < 2:
         raise ValueError("Filled contours require at least 2 levels.")
     # Workaround for cntr.c bug wrt masked interior regions:
     #if filled:
     #    z = ma.masked_array(z.filled(-1e38))
     # It's not clear this is any better than the original bug.
     self.levels = lev
     self.layers = self.levels  # contour: a line is a thin layer
     if self.filled:
         self.layers = 0.5 * (self.levels[:-1] + self.levels[1:])
     return (x, y, z)
Exemplo n.º 56
0
    def contour(self, *args, **kwargs):
        """
        contour(self, *args, **kwargs)

        Function signatures

        contour(Z) - make a contour plot of an array Z. The level
                 values are chosen automatically.

        contour(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface

        contour(Z,N) and contour(X,Y,Z,N) - draw N contour lines overriding
                         the automatic value

        contour(Z,V) and contour(X,Y,Z,V) - draw len(V) contour lines,
                       at the values specified in V (array, list, tuple)

        contour(Z, **kwargs) - Use keyword args to control colors, linewidth,
                    origin, cmap ... see below

        [L,C] = contour(...) returns a list of levels and a silent_list of LineCollections

        Optional keywork args are shown with their defaults below (you must
        use kwargs for these):

            * colors = None: one of these:
              - a tuple of matplotlib color args (string, float, rgb, etc),
              different levels will be plotted in different colors in the order
              specified

              -  one string color, e.g. colors = 'r' or colors = 'red', all levels
              will be plotted in this color

              - if colors == None, the default colormap will be used

            * alpha=1.0 : the alpha blending value

            * cmap = None: a cm Colormap instance from matplotlib.cm.

            * origin = None: 'upper'|'lower'|'image'|None.
              If 'image', the rc value for image.origin will be used.
              If None (default), the first value of Z will correspond
              to the lower left corner, location (0,0).
              This keyword is active only if contourf is called with
              one or two arguments, that is, without explicitly
              specifying X and Y.

            * extent = None: (x0,x1,y0,y1); also active only if X and Y
              are not specified.

            * badmask = None: array with dimensions of Z, and with values
              of zero at locations corresponding to valid data, and one
              at locations where the value of Z should be ignored.
              This is experimental.  It presently works for edge regions
              for line and filled contours, but for interior regions it
              works correctly only for line contours.  The badmask kwarg
              may go away in the future, to be replaced by the use of
              NaN value in Z and/or the use of a masked array in Z.

            * linewidths = None: or one of these:
              - a number - all levels will be plotted with this linewidth,
                e.g. linewidths = 0.6

              - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different
                levels will be plotted with different linewidths in the order
                specified

              - if linewidths == None, the default width in lines.linewidth in
                .matplotlibrc is used

            * fmt = '1.3f': a format string for adding a label to each collection.
              Useful for auto-legending.

        """

        alpha = kwargs.get('alpha', 1.0)
        linewidths = kwargs.get('linewidths', None)
        fmt = kwargs.get('fmt', '%1.3f')
        origin = kwargs.get('origin', None)
        extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        colors = kwargs.get('colors', None)
        badmask = kwargs.get('badmask', None)

        if cmap is not None: assert (isinstance(cmap, Colormap))
        if origin is not None: assert (origin in ['lower', 'upper', 'image'])
        if extent is not None: assert (len(extent) == 4)
        if colors is not None and cmap is not None:
            raise RuntimeError('Either colors or cmap must be None')
        # todo: shouldn't this use the current image rather than the rc param?
        if origin == 'image': origin = rcParams['image.origin']

        x, y, z, lev = self._contour_args(False, badmask, origin, extent,
                                          *args)

        # Manipulate the plot *after* checking the input arguments.
        if not self.ax.ishold(): self.ax.cla()

        Nlev = len(lev)
        if cmap is None:
            if colors is None:
                Ncolors = Nlev
            else:
                Ncolors = len(colors)
        else:
            Ncolors = Nlev

        reg, triangle = self._initialize_reg_tri(z, badmask)

        tcolors, mappable, collections = self._process_colors(
            z, colors, alpha, lev, cmap)

        if linewidths == None:
            tlinewidths = [rcParams['lines.linewidth']] * Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(
                    ceil(Nlev / len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w, ) for w in linewidths]

        region = 0
        for level, color, width in zip(lev, tcolors, tlinewidths):
            ntotal, nparts = _contour.GcInit1(x, y, reg, triangle, region, z,
                                              level)
            np = zeros((nparts, ), typecode='l')
            xp = zeros((ntotal, ), Float64)
            yp = zeros((ntotal, ), Float64)
            nlist = _contour.GcTrace(np, xp, yp)
            col = LineCollection(nlist)
            col.set_color(color)
            col.set_linewidth(width)

            if level < 0.0 and Ncolors == 1:
                col.set_linestyle((0, (6., 6.)), )
                #print "setting dashed"
            col.set_label(fmt % level)
            self.ax.add_collection(col)
            collections.append(col)

        collections = silent_list('LineCollection', collections)
        # the mappable attr is for the pylab interface functions,
        # which maintain the current image
        collections.mappable = mappable
        return lev, collections
Exemplo n.º 57
0
    def draw(self, renderer):
        if self._invalidy or self._invalidx:
            self.recache()
        self.ind_offset = 0  # Needed for contains() method.
        if self._subslice and self.axes:
            # Need to handle monotonically decreasing case also...
            x0, x1 = self.axes.get_xbound()
            i0, = self._x.searchsorted([x0], 'left')
            i1, = self._x.searchsorted([x1], 'right')
            subslice = slice(max(i0 - 1, 0), i1 + 1)
            self.ind_offset = subslice.start
            self._transform_path(subslice)
        if self._transformed_path is None:
            self._transform_path()

        if not self.get_visible(): return

        renderer.open_group('line2d', self.get_gid())
        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        gc.set_foreground(self._color)
        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)
        gc.set_alpha(self._alpha)
        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)
        gc.set_snap(self.get_snap())

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = self._transformed_path.get_transformed_path_and_affine(
            )
            if len(tpath.vertices):
                self._lineFunc = getattr(self, funcname)
                funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
                drawFunc = getattr(self, funcname)
                drawFunc(renderer, gc, tpath, affine.frozen())

        if self._marker:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            rgbFace = self._get_rgb_face()
            rgbFaceAlt = self._get_rgb_face(alt=True)
            edgecolor = self.get_markeredgecolor()
            if is_string_like(edgecolor) and edgecolor.lower() == 'none':
                gc.set_linewidth(0)
                gc.set_foreground(rgbFace)
            else:
                gc.set_foreground(edgecolor)
                gc.set_linewidth(self._markeredgewidth)
            gc.set_alpha(self._alpha)
            marker = self._marker
            tpath, affine = self._transformed_path.get_transformed_points_and_affine(
            )
            if len(tpath.vertices):
                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    if iterable(markevery):
                        startind, stride = markevery
                    else:
                        startind, stride = 0, markevery
                    if tpath.codes is not None:
                        codes = tpath.codes[startind::stride]
                    else:
                        codes = None
                    vertices = tpath.vertices[startind::stride]
                    subsampled = Path(vertices, codes)
                else:
                    subsampled = tpath

                snap = marker.get_snap_threshold()
                if type(snap) == float:
                    snap = renderer.points_to_pixels(self._markersize) >= snap
                gc.set_snap(snap)
                gc.set_joinstyle(marker.get_joinstyle())
                gc.set_capstyle(marker.get_capstyle())
                marker_path = marker.get_path()
                marker_trans = marker.get_transform()
                w = renderer.points_to_pixels(self._markersize)
                if marker.get_marker() != ',':
                    # Don't scale for pixels, and don't stroke them
                    marker_trans = marker_trans.scale(w)
                else:
                    gc.set_linewidth(0)
                renderer.draw_markers(gc, marker_path, marker_trans,
                                      subsampled, affine.frozen(), rgbFace)
                alt_marker_path = marker.get_alt_path()
                if alt_marker_path:
                    alt_marker_trans = marker.get_alt_transform()
                    alt_marker_trans = alt_marker_trans.scale(w)
                    renderer.draw_markers(gc, alt_marker_path,
                                          alt_marker_trans, subsampled,
                                          affine.frozen(), rgbFaceAlt)

            gc.restore()

        gc.restore()
        renderer.close_group('line2d')
Exemplo n.º 58
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,
                 xunits          = None,
                 yunits          = None,
                 **kwargs
                 ):
        """
        xdata is a sequence of x data
        ydata is a sequence of y data
        linewidth is the width of the line in points
        linestyle is one of lineStyles
        marker is one of lineMarkers or None
        markersize is the size of the marker in points
        markeredgecolor  and markerfacecolor can be any color arg
        markeredgewidth is the size of the markter edge in points
        dash_capstyle set the capstyle for dashed line
        solid_capstyle set the capstyle for solid line
        dash_joinstyle set the joinstyle for dashed line
        solid_joinstyle set the joinstyle for solid line
        """
        Artist.__init__(self)

        #convert sequences to numeric 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=rcParams['lines.markeredgecolor']
        if markerfacecolor is None :
            markerfacecolor=rcParams['lines.markerfacecolor']
        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_xunits(xunits)
        self.set_yunits(yunits)

        self._linestyle = linestyle
        self._linewidth = linewidth
        self._color = color
        self._antialiased = antialiased
        self._markersize = markersize
        self._dashSeq = None


        self._markerfacecolor = markerfacecolor
        self._markeredgecolor = markeredgecolor
        self._markeredgewidth = markeredgewidth
        self._point_size_reduction = 0.5

        self.verticalOffset = None

        self.set_data(xdata, ydata)

        if not self._lineStyles.has_key(linestyle):
            raise ValueError('Unrecognized line style %s, %s' %( linestyle, type(linestyle)))
        if not self._markers.has_key(marker):
            raise ValueError('Unrecognized marker style %s, %s'%( marker, type(marker)))

        self.set_marker(marker)

        self._logcache = None

        if len(kwargs): setp(self, **kwargs)
Exemplo n.º 59
0
 def fixlist(args):
     ret = []
     for a in args:
         if iterable(a): a = tuple(a)
         ret.append(a)
     return tuple(ret)
Exemplo n.º 60
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 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)