Python matplotlib.cbook.iterable() Examples

The following are 30 code examples of matplotlib.cbook.iterable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.cbook , or try the search function .
Example #1
Source File: cm.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def set_clim(self, vmin=None, vmax=None):
        """
        set the norm limits for image scaling; if *vmin* is a length2
        sequence, interpret it as ``(vmin, vmax)`` which is used to
        support setp

        ACCEPTS: a length 2 sequence of floats
        """
        if (vmin is not None and vmax is None and
                cbook.iterable(vmin) and len(vmin) == 2):
            vmin, vmax = vmin

        if vmin is not None:
            self.norm.vmin = vmin
        if vmax is not None:
            self.norm.vmax = vmax
        self.changed() 
Example #2
Source File: figure.py    From Computable with MIT License 6 votes vote down vote up
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 key
            ret = []
            for k, v in items:
                if iterable(v):
                    v = tuple(v)
                ret.append((k, v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a):
                    a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.iteritems())
        return key 
Example #3
Source File: artist.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, o):
        """
        Initialize the artist inspector with an
        :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`.
        If a sequence is used, we assume it is a homogeneous sequence (all
        :class:`Artists` are of the same type) and it is your responsibility
        to make sure this is so.
        """
        if cbook.iterable(o) and len(o):
            o = o[0]

        self.oorig = o
        if not isinstance(o, type):
            o = type(o)
        self.o = o

        self.aliasd = self.get_aliases() 
Example #4
Source File: artist.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, o):
        """
        Initialize the artist inspector with an
        :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`.
        If a sequence is used, we assume it is a homogeneous sequence (all
        :class:`Artists` are of the same type) and it is your responsibility
        to make sure this is so.
        """
        if cbook.iterable(o) and len(o):
            o = o[0]

        self.oorig = o
        if not isinstance(o, type):
            o = type(o)
        self.o = o

        self.aliasd = self.get_aliases() 
Example #5
Source File: contour.py    From Computable with MIT License 6 votes vote down vote up
def _process_linestyles(self):
        linestyles = self.linestyles
        Nlev = len(self.levels)
        if linestyles is None:
            tlinestyles = ['solid'] * Nlev
            if self.monochrome:
                neg_ls = mpl.rcParams['contour.negative_linestyle']
                eps = - (self.zmax - self.zmin) * 1e-15
                for i, lev in enumerate(self.levels):
                    if lev < eps:
                        tlinestyles[i] = neg_ls
        else:
            if cbook.is_string_like(linestyles):
                tlinestyles = [linestyles] * Nlev
            elif cbook.iterable(linestyles):
                tlinestyles = list(linestyles)
                if len(tlinestyles) < Nlev:
                    nreps = int(np.ceil(Nlev / len(linestyles)))
                    tlinestyles = tlinestyles * nreps
                if len(tlinestyles) > Nlev:
                    tlinestyles = tlinestyles[:Nlev]
            else:
                raise ValueError("Unrecognized type for linestyles kwarg")
        return tlinestyles 
Example #6
Source File: contour.py    From Computable with MIT License 6 votes vote down vote up
def _process_linewidths(self):
        linewidths = self.linewidths
        Nlev = len(self.levels)
        if linewidths is None:
            tlinewidths = [(mpl.rcParams['lines.linewidth'],)] * Nlev
        else:
            if not cbook.iterable(linewidths):
                linewidths = [linewidths] * Nlev
            else:
                linewidths = list(linewidths)
                if len(linewidths) < Nlev:
                    nreps = int(np.ceil(Nlev / len(linewidths)))
                    linewidths = linewidths * nreps
                if len(linewidths) > Nlev:
                    linewidths = linewidths[:Nlev]
            tlinewidths = [(w,) for w in linewidths]
        return tlinewidths 
Example #7
Source File: contour.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _process_linestyles(self):
        linestyles = self.linestyles
        Nlev = len(self.levels)
        if linestyles is None:
            tlinestyles = ['solid'] * Nlev
            if self.monochrome:
                neg_ls = mpl.rcParams['contour.negative_linestyle']
                eps = - (self.zmax - self.zmin) * 1e-15
                for i, lev in enumerate(self.levels):
                    if lev < eps:
                        tlinestyles[i] = neg_ls
        else:
            if cbook.is_string_like(linestyles):
                tlinestyles = [linestyles] * Nlev
            elif cbook.iterable(linestyles):
                tlinestyles = list(linestyles)
                if len(tlinestyles) < Nlev:
                    nreps = int(np.ceil(Nlev / len(linestyles)))
                    tlinestyles = tlinestyles * nreps
                if len(tlinestyles) > Nlev:
                    tlinestyles = tlinestyles[:Nlev]
            else:
                raise ValueError("Unrecognized type for linestyles kwarg")
        return tlinestyles 
Example #8
Source File: contour.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _process_linewidths(self):
        linewidths = self.linewidths
        Nlev = len(self.levels)
        if linewidths is None:
            tlinewidths = [(mpl.rcParams['lines.linewidth'],)] * Nlev
        else:
            if not cbook.iterable(linewidths):
                linewidths = [linewidths] * Nlev
            else:
                linewidths = list(linewidths)
                if len(linewidths) < Nlev:
                    nreps = int(np.ceil(Nlev / len(linewidths)))
                    linewidths = linewidths * nreps
                if len(linewidths) > Nlev:
                    linewidths = linewidths[:Nlev]
            tlinewidths = [(w,) for w in linewidths]
        return tlinewidths 
Example #9
Source File: dates.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def num2date(x, tz=None):
    """
    *x* is a float value which gives the number of days
    (fraction part represents hours, minutes, seconds) since
    0001-01-01 00:00:00 UTC *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.

    Return value is a :class:`datetime` instance in timezone *tz* (default to
    rcparams TZ value).

    If *x* is a sequence, a sequence of :class:`datetime` objects will
    be returned.
    """
    if tz is None:
        tz = _get_rc_timezone()
    if not cbook.iterable(x):
        return _from_ordinalf(x, tz)
    else:
        return [_from_ordinalf(val, tz) for val in x] 
Example #10
Source File: mlab.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def poly_between(x, ylower, yupper):
    """
    Given a sequence of *x*, *ylower* and *yupper*, return the polygon
    that fills the regions between them.  *ylower* or *yupper* can be
    scalar or iterable.  If they are iterable, they must be equal in
    length to *x*.

    Return value is *x*, *y* arrays for use with
    :meth:`matplotlib.axes.Axes.fill`.
    """
    if ma.isMaskedArray(ylower) or ma.isMaskedArray(yupper) or ma.isMaskedArray(x):
        numpy = ma
    else:
        numpy = np

    Nx = len(x)
    if not cbook.iterable(ylower):
        ylower = ylower*numpy.ones(Nx)

    if not cbook.iterable(yupper):
        yupper = yupper*numpy.ones(Nx)

    x = numpy.concatenate( (x, x[::-1]) )
    y = numpy.concatenate( (yupper, ylower[::-1]) )
    return x,y 
Example #11
Source File: UnitDblConverter.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def default_units( value, axis ):
      """: Return the default unit for value, or None.

      = INPUT VARIABLES
      - value   The value or list of values that need units.

      = RETURN VALUE
      - Returns the default units to use for value.
      Return the default unit for value, or None.
      """

      # Determine the default units based on the user preferences set for
      # default units when printing a UnitDbl.
      if ( iterable(value) and not isinstance(value, str) ):
         return UnitDblConverter.default_units( value[0], axis )
      else:
         return UnitDblConverter.defaults[ value.type() ] 
Example #12
Source File: EpochConverter.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def default_units( value, axis ):
      """: Return the default unit for value, or None.

      = INPUT VARIABLES
      - value   The value or list of values that need units.

      = RETURN VALUE
      - Returns the default units to use for value.
      """
      frame = None
      if ( iterable(value) and not isinstance(value, str) ):
         return EpochConverter.default_units( value[0], axis )
      else:
         frame = value.frame()

      return frame 
Example #13
Source File: mlab.py    From Computable with MIT License 6 votes vote down vote up
def poly_between(x, ylower, yupper):
    """
    Given a sequence of *x*, *ylower* and *yupper*, return the polygon
    that fills the regions between them.  *ylower* or *yupper* can be
    scalar or iterable.  If they are iterable, they must be equal in
    length to *x*.

    Return value is *x*, *y* arrays for use with
    :meth:`matplotlib.axes.Axes.fill`.
    """
    if ma.isMaskedArray(ylower) or ma.isMaskedArray(yupper) or ma.isMaskedArray(x):
        numpy = ma
    else:
        numpy = np

    Nx = len(x)
    if not cbook.iterable(ylower):
        ylower = ylower*numpy.ones(Nx)

    if not cbook.iterable(yupper):
        yupper = yupper*numpy.ones(Nx)

    x = numpy.concatenate( (x, x[::-1]) )
    y = numpy.concatenate( (yupper, ylower[::-1]) )
    return x,y 
Example #14
Source File: figure.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
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 key
            ret = []
            for k, v in items:
                if iterable(v):
                    v = tuple(v)
                ret.append((k, v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a):
                    a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.iteritems())
        return key 
Example #15
Source File: dates.py    From Computable with MIT License 6 votes vote down vote up
def num2date(x, tz=None):
    """
    *x* is a float value which gives the number of days
    (fraction part represents hours, minutes, seconds) since
    0001-01-01 00:00:00 UTC *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.

    Return value is a :class:`datetime` instance in timezone *tz* (default to
    rcparams TZ value).

    If *x* is a sequence, a sequence of :class:`datetime` objects will
    be returned.
    """
    if tz is None:
        tz = _get_rc_timezone()
    if not cbook.iterable(x):
        return _from_ordinalf(x, tz)
    else:
        return [_from_ordinalf(val, tz) for val in x] 
Example #16
Source File: cm.py    From Computable with MIT License 6 votes vote down vote up
def set_clim(self, vmin=None, vmax=None):
        """
        set the norm limits for image scaling; if *vmin* is a length2
        sequence, interpret it as ``(vmin, vmax)`` which is used to
        support setp

        ACCEPTS: a length 2 sequence of floats
        """
        if (vmin is not None and vmax is None and
                cbook.iterable(vmin) and len(vmin) == 2):
            vmin, vmax = vmin

        if vmin is not None:
            self.norm.vmin = vmin
        if vmax is not None:
            self.norm.vmax = vmax
        self.changed() 
Example #17
Source File: art3d.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_dir_vector(zdir):
    if zdir == 'x':
        return np.array((1, 0, 0))
    elif zdir == 'y':
        return np.array((0, 1, 0))
    elif zdir == 'z':
        return np.array((0, 0, 1))
    elif zdir is None:
        return np.array((0, 0, 0))
    elif iterable(zdir) and len(zdir) == 3:
        return zdir
    else:
        raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") 
Example #18
Source File: axes3d.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _determine_lims(self, xmin=None, xmax=None, *args, **kwargs):
        if xmax is None and cbook.iterable(xmin):
            xmin, xmax = xmin
        if xmin == xmax:
            xmin -= 0.05
            xmax += 0.05
        return (xmin, xmax) 
Example #19
Source File: axes3d.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_zbound(self, lower=None, upper=None):
        """
        Set the lower and upper numerical bounds of the z-axis.
        This method will honor axes inversion regardless of parameter order.
        It will not change the :attr:`_autoscaleZon` attribute.

        .. versionadded :: 1.1.0
            This function was added, but not tested. Please report any bugs.
        """
        if upper is None and cbook.iterable(lower):
            lower,upper = lower

        old_lower,old_upper = self.get_zbound()

        if lower is None: lower = old_lower
        if upper is None: upper = old_upper

        if self.zaxis_inverted():
            if lower < upper:
                self.set_zlim(upper, lower, auto=None)
            else:
                self.set_zlim(lower, upper, auto=None)
        else :
            if lower < upper:
                self.set_zlim(lower, upper, auto=None)
            else :
                self.set_zlim(upper, lower, auto=None) 
Example #20
Source File: colors.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
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=[], alpha=[])
        for val, color in zip(vals, colors):
            r, g, b, a = colorConverter.to_rgba(color)
            cdict['red'].append((val, r, r))
            cdict['green'].append((val, g, g))
            cdict['blue'].append((val, b, b))
            cdict['alpha'].append((val, a, a))

        return LinearSegmentedColormap(name, cdict, N, gamma) 
Example #21
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _get_bool(val):
        if not cbook.iterable(val):
            val = (val,)
        try:
            bool(val[0])
        except (TypeError, IndexError):
            raise TypeError('val must be a bool or nonzero sequence of them')
        return val 
Example #22
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _get_value(val):
        try:
            return (float(val), )
        except TypeError:
            if cbook.iterable(val) and len(val):
                try:
                    float(val[0])
                except (TypeError, ValueError):
                    pass  # raise below
                else:
                    return val

        raise TypeError('val must be a float or nonzero sequence of floats') 
Example #23
Source File: legend.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _findoffset_loc(self, width, height, xdescent, ydescent, renderer):
        "Helper function to locate the legend using the location code"

        if iterable(self._loc) and len(self._loc) == 2:
            # when loc is a tuple of axes(or figure) coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
        else:
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(),
                                           renderer)

        return x + xdescent, y + ydescent 
Example #24
Source File: patches.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __call__(self, path, mutation_size, linewidth,
                     aspect_ratio=1.):
            """
            The __call__ method is a thin wrapper around the transmute method
            and take care of the aspect ratio.
            """

            path = make_path_regular(path)

            if aspect_ratio is not None:
                # Squeeze the given height by the aspect_ratio

                vertices, codes = path.vertices[:], path.codes[:]
                # Squeeze the height
                vertices[:, 1] = vertices[:, 1] / aspect_ratio
                path_shrinked = Path(vertices, codes)
                # call transmute method with squeezed height.
                path_mutated, fillable = self.transmute(path_shrinked,
                                                        linewidth,
                                                        mutation_size)
                if cbook.iterable(fillable):
                    path_list = []
                    for p in zip(path_mutated):
                        v, c = p.vertices, p.codes
                        # Restore the height
                        v[:, 1] = v[:, 1] * aspect_ratio
                        path_list.append(Path(v, c))
                    return path_list, fillable
                else:
                    return path_mutated, fillable
            else:
                return self.transmute(path, mutation_size, linewidth) 
Example #25
Source File: mlab.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def offset_line(y, yerr):
    """
    Offsets an array *y* by +/- an error and returns a tuple (y - err, y + err).

    The error term can be:

    * A scalar. In this case, the returned tuple is obvious.
    * A vector of the same length as *y*. The quantities y +/- err are computed
      component-wise.
    * A tuple of length 2. In this case, yerr[0] is the error below *y* and
      yerr[1] is error above *y*. For example::

        from pylab import *
        x = linspace(0, 2*pi, num=100, endpoint=True)
        y = sin(x)
        y_minus, y_plus = mlab.offset_line(y, 0.1)
        plot(x, y)
        fill_between(x, ym, y2=yp)
        show()

    """
    if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and len(yerr) == len(y)):
        ymin = y - yerr
        ymax = y + yerr
    elif len(yerr) == 2:
        ymin, ymax = y - yerr[0], y + yerr[1]
    else:
        raise ValueError("yerr must be scalar, 1xN or 2xN")
    return ymin, ymax 
Example #26
Source File: mlab.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def rec_append_fields(rec, names, arrs, dtypes=None):
    """
    Return a new record array with field names populated with data
    from arrays in *arrs*.  If appending a single field, then *names*,
    *arrs* and *dtypes* do not have to be lists. They can just be the
    values themselves.
    """
    if (not cbook.is_string_like(names) and cbook.iterable(names) \
            and len(names) and cbook.is_string_like(names[0])):
        if len(names) != len(arrs):
            raise ValueError("number of arrays do not match number of names")
    else: # we have only 1 name and 1 array
        names = [names]
        arrs = [arrs]
    arrs = map(np.asarray, arrs)
    if dtypes is None:
        dtypes = [a.dtype for a in arrs]
    elif not cbook.iterable(dtypes):
        dtypes = [dtypes]
    if len(arrs) != len(dtypes):
        if len(dtypes) == 1:
            dtypes = dtypes * len(arrs)
        else:
            raise ValueError("dtypes must be None, a single dtype or a list")

    newdtype = np.dtype(rec.dtype.descr + zip(names, dtypes))
    newrec = np.recarray(rec.shape, dtype=newdtype)
    for field in rec.dtype.fields:
        newrec[field] = rec[field]
    for name, arr in zip(names, arrs):
        newrec[name] = arr
    return newrec 
Example #27
Source File: mlab.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def fftsurr(x, detrend=detrend_none, window=window_none):
    """
    Compute an FFT phase randomized surrogate of *x*.
    """
    if cbook.iterable(window):
        x=window*detrend(x)
    else:
        x = window(detrend(x))
    z = np.fft.fft(x)
    a = 2.*np.pi*1j
    phase = a * np.random.rand(len(x))
    z = z*np.exp(phase)
    return np.fft.ifft(z).real 
Example #28
Source File: mlab.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
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
    percentile values or a scalar.  If *p* is a sequence, the ith
    element of the return sequence is the *p*(i)-th percentile of *x*.
    If *p* is a scalar, the largest value of *x* less than or equal to
    the *p* percentage point in the sequence is returned.
    """

    # This implementation derived from scipy.stats.scoreatpercentile
    def _interpolate(a, b, fraction):
        """Returns the point at the given fraction between a and b, where
        'fraction' must be between 0 and 1.
        """
        return a + (b - a)*fraction

    scalar = True
    if cbook.iterable(p):
        scalar = False
    per = np.array(p)
    values = np.array(x).ravel()  # copy
    values.sort()

    idxs = per /100. * (values.shape[0] - 1)
    ai = idxs.astype(np.int)
    bi = ai + 1
    frac = idxs % 1

    # handle cases where attempting to interpolate past last index
    cond = bi >= len(values)
    if scalar:
        if cond:
            ai -= 1
            bi -= 1
            frac += 1
    else:
        ai[cond] -= 1
        bi[cond] -= 1
        frac[cond] += 1

    return _interpolate(values[ai],values[bi],frac) 
Example #29
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def add_lines(self, levels, colors, linewidths, erase=True):
        '''
        Draw lines on the colorbar.

        *colors* and *linewidths* must be scalars or
        sequences the same length as *levels*.

        Set *erase* to False to add lines without first
        removing any previously added lines.
        '''
        y = self._locate(levels)
        igood = (y < 1.001) & (y > -0.001)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        N = len(y)
        x = np.array([0.0, 1.0])
        X, Y = np.meshgrid(x, y)
        if self.orientation == 'vertical':
            xy = [zip(X[i], Y[i]) for i in xrange(N)]
        else:
            xy = [zip(Y[i], X[i]) for i in xrange(N)]
        col = collections.LineCollection(xy, linewidths=linewidths)

        if erase and self.lines:
            for lc in self.lines:
                lc.remove()
            self.lines = []
        self.lines.append(col)
        col.set_color(colors)
        self.ax.add_collection(col) 
Example #30
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_ticks(self, ticks, update_ticks=True):
        """
        set tick locations. Tick locations are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if cbook.iterable(ticks):
            self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
        else:
            self.locator = ticks

        if update_ticks:
            self.update_ticks()