Beispiel #1
0
    def __call__(self, value, clip=None):
        if clip is None:
            clip = self.clip

        if cbook.iterable(value):
            vtype = 'array'
            val = ma.asarray(value).astype(npy.float)
        else:
            vtype = 'scalar'
            val = ma.array([value]).astype(npy.float)

        self.autoscale_None(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin<=0:
            raise ValueError("values must all be positive")
        elif vmin==vmax:
            return 0.0 * val
        else:
            if clip:
                mask = ma.getmask(val)
                val = ma.array(npy.clip(val.filled(vmax), vmin, vmax),
                                mask=mask)
            result = (ma.log(val)-npy.log(vmin))/(npy.log(vmax)-npy.log(vmin))
        if vtype == 'scalar':
            result = result[0]
        return result
Beispiel #2
0
    def __call__(self, value, clip=None):
        if clip is None:
            clip = self.clip

        if cbook.iterable(value):
            vtype = 'array'
            val = ma.asarray(value).astype(npy.float)
        else:
            vtype = 'scalar'
            val = ma.array([value]).astype(npy.float)

        self.autoscale_None(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin <= 0:
            raise ValueError("values must all be positive")
        elif vmin == vmax:
            return 0.0 * val
        else:
            if clip:
                mask = ma.getmask(val)
                val = ma.array(npy.clip(val.filled(vmax), vmin, vmax),
                               mask=mask)
            result = (ma.log(val) - npy.log(vmin)) / (npy.log(vmax) -
                                                      npy.log(vmin))
        if vtype == 'scalar':
            result = result[0]
        return result
Beispiel #3
0
    def __init__(self, vertices, codes=None):
        """
        Create a new path with the given vertices and codes.

        vertices is an Nx2 numpy float array, masked array or Python
        sequence.

        codes is an N-length numpy array or Python sequence of type
        Path.code_type.

        See the docstring of Path for a description of the various
        codes.

        These two arrays must have the same length in the first
        dimension.

        If codes is None, vertices will be treated as a series of line
        segments.  If vertices contains masked values, the resulting
        path will be compressed, with MOVETO codes inserted in the
        correct places to jump over the masked regions.
        """
        if ma.isMaskedArray(vertices):
            mask = ma.getmask(vertices)
        else:
            vertices = npy.asarray(vertices, npy.float_)
            mask = ma.nomask

        if codes is not None:
	    codes = npy.asarray(codes, self.code_type)
            assert codes.ndim == 1
            assert len(codes) == len(vertices)

        # The path being passed in may have masked values.  However,
        # the backends (and any affine transformations in matplotlib
        # itself), are not expected to deal with masked arrays, so we
        # must remove them from the array (using compressed), and add
        # MOVETO commands to the codes array accordingly.
        if mask is not ma.nomask:
            mask1d = ma.mask_or(mask[:, 0], mask[:, 1])
            if codes is None:
                codes = self.LINETO * npy.ones(
                    len(vertices), self.code_type)
                codes[0] = self.MOVETO
            vertices = ma.compress(npy.invert(mask1d), vertices, 0)
            codes = npy.where(npy.concatenate((mask1d[-1:], mask1d[:-1])),
                              self.MOVETO, codes)
            codes = ma.masked_array(codes, mask=mask1d).compressed()
            codes = npy.asarray(codes, self.code_type)

        assert vertices.ndim == 2
        assert vertices.shape[1] == 2

        self.codes = codes
	self.vertices = vertices
Beispiel #4
0
    def __call__(self, X, alpha=1.0, bytes=False):
        """
        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 bytes is False, the rgba values will be floats on a
        0-1 scale; if True, they will be uint8, 0-255.
        """

        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 cbook.iterable(X):
            vtype = 'scalar'
            xa = npy.array([X])
        else:
            vtype = 'array'
            xma = ma.asarray(X)
            xa = xma.filled(0)
            mask_bad = ma.getmask(xma)
        if xa.dtype.char in npy.typecodes['Float']:
            npy.putmask(xa, xa == 1.0,
                        0.9999999)  #Treat 1.0 as slightly less than 1.
            xa = (xa * self.N).astype(int)
        # Set the over-range indices before the under-range;
        # otherwise the under-range values get converted to over-range.
        npy.putmask(xa, xa > self.N - 1, self._i_over)
        npy.putmask(xa, xa < 0, self._i_under)
        if mask_bad is not None and mask_bad.shape == xa.shape:
            npy.putmask(xa, mask_bad, self._i_bad)
        if bytes:
            lut = (self._lut * 255).astype(npy.uint8)
        else:
            lut = self._lut
        rgba = lut[xa]
        if vtype == 'scalar':
            rgba = tuple(rgba[0, :])
        return rgba
Beispiel #5
0
    def __call__(self, X, alpha=1.0, bytes=False):
        """
        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 bytes is False, the rgba values will be floats on a
        0-1 scale; if True, they will be uint8, 0-255.
        """

        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 cbook.iterable(X):
            vtype = 'scalar'
            xa = npy.array([X])
        else:
            vtype = 'array'
            xma = ma.asarray(X)
            xa = xma.filled(0)
            mask_bad = ma.getmask(xma)
        if xa.dtype.char in npy.typecodes['Float']:
            npy.putmask(xa, xa==1.0, 0.9999999) #Treat 1.0 as slightly less than 1.
            xa = (xa * self.N).astype(int)
        # Set the over-range indices before the under-range;
        # otherwise the under-range values get converted to over-range.
        npy.putmask(xa, xa>self.N-1, self._i_over)
        npy.putmask(xa, xa<0, self._i_under)
        if mask_bad is not None and mask_bad.shape == xa.shape:
            npy.putmask(xa, mask_bad, self._i_bad)
        if bytes:
            lut = (self._lut * 255).astype(npy.uint8)
        else:
            lut = self._lut
        rgba = lut[xa]
        if vtype == 'scalar':
            rgba = tuple(rgba[0,:])
        return rgba
Beispiel #6
0
    def __init__(self, ax, *args, **kwargs):
        """
        Draw contour lines or filled regions, depending on
        whether keyword arg 'filled' is False (default) or True.

        The first argument of the initializer must be an axes
        object.  The remaining arguments and keyword arguments
        are described in ContourSet.contour_doc.

        """
        self.ax = ax
        self.levels = kwargs.get('levels', None)
        self.filled = kwargs.get('filled', False)
        self.linewidths = kwargs.get('linewidths', None)
        self.linestyles = kwargs.get('linestyles', 'solid')
        
        self.alpha = kwargs.get('alpha', 1.0)
        self.origin = kwargs.get('origin', None)
        self.extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        self.colors = kwargs.get('colors', None)
        norm = kwargs.get('norm', None)
        self.extend = kwargs.get('extend', 'neither')
        self.antialiased = kwargs.get('antialiased', True)
        self.nchunk = kwargs.get('nchunk', 0)
        self.locator = kwargs.get('locator', None)
        if (isinstance(norm, colors.LogNorm)
                or isinstance(self.locator, ticker.LogLocator)):
            self.logscale = True
            if norm is None:
                norm = colors.LogNorm()
            if self.extend is not 'neither':
                raise ValueError('extend kwarg does not work yet with log scale')
        else:
            self.logscale = False

        if self.origin is not None: assert(self.origin in
                                            ['lower', 'upper', 'image'])
        if self.extent is not None: assert(len(self.extent) == 4)
        if cmap is not None: assert(isinstance(cmap, colors.Colormap))
        if self.colors is not None and cmap is not None:
            raise ValueError('Either colors or cmap must be None')
        if self.origin == 'image': self.origin = mpl.rcParams['image.origin']
        x, y, z = self._contour_args(*args)        # also sets self.levels,
                                                   #  self.layers
        if self.colors is not None:
            cmap = colors.ListedColormap(self.colors, N=len(self.layers))
        if self.filled:
            self.collections = cbook.silent_list('collections.PolyCollection')
        else:
            self.collections = cbook.silent_list('collections.LineCollection')
        # label lists must be initialized here
        self.cl = []
        self.cl_cvalues = []

        kw = {'cmap': cmap}
        if norm is not None:
            kw['norm'] = norm
        cm.ScalarMappable.__init__(self, **kw) # sets self.cmap;
        self._process_colors()
        _mask = ma.getmask(z)
        if _mask is ma.nomask:
            _mask = None

        if self.filled:
            if self.linewidths is not None:
                warnings.warn('linewidths is ignored by contourf')
            C = _cntr.Cntr(x, y, z.filled(), _mask)
            lowers = self._levels[:-1]
            uppers = self._levels[1:]
            for level, level_upper in zip(lowers, uppers):
                nlist = C.trace(level, level_upper, points = 0,
                        nchunk = self.nchunk)
                col = collections.PolyCollection(nlist,
                                     antialiaseds = (self.antialiased,),
                                     edgecolors= 'None')
                self.ax.add_collection(col)
                self.collections.append(col)

        else:
            tlinewidths = self._process_linewidths()
            self.tlinewidths = tlinewidths
            tlinestyles = self._process_linestyles()
            C = _cntr.Cntr(x, y, z.filled(), _mask)
            for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles):
                nlist = C.trace(level, points = 0)
                col = collections.LineCollection(nlist,
                                     linewidths = width,
                                     linestyle = lstyle)

                if level < 0.0 and self.monochrome:
                    ls = mpl.rcParams['contour.negative_linestyle']
                    col.set_linestyle(ls)
                col.set_label('_nolegend_')
                self.ax.add_collection(col)
                self.collections.append(col)
        self.changed() # set the colors
        x0 = ma.minimum(x)
        x1 = ma.maximum(x)
        y0 = ma.minimum(y)
        y1 = ma.maximum(y)
        self.ax.update_datalim([(x0,y0), (x1,y1)])
        self.ax.set_xlim((x0, x1))
        self.ax.set_ylim((y0, y1))