Beispiel #1
0
    def __init__(self, ax, loc=None, bbox=None):

        Artist.__init__(self)

        if is_string_like(loc) and loc not in self.codes:
            warnings.warn(
                "Unrecognized location %s. Falling back on "
                "bottom; valid locations are\n%s\t" % (loc, "\n\t".join(self.codes.iterkeys()))
            )
            loc = "bottom"
        if is_string_like(loc):
            loc = self.codes.get(loc, 1)
        self.set_figure(ax.figure)
        self._axes = ax
        self._loc = loc
        self._bbox = bbox

        # use axes coords
        self.set_transform(ax.transAxes)

        self._texts = []
        self._cells = {}
        self._autoRows = []
        self._autoColumns = []
        self._autoFontsize = True

        self._cachedRenderer = None
Beispiel #2
0
    def __init__(self, ax, loc=None, bbox=None):

        Artist.__init__(self)

        if is_string_like(loc) and loc not in self.codes:
            warnings.warn('Unrecognized location %s. Falling back on '
                          'bottom; valid locations are\n%s\t' %
                          (loc, '\n\t'.join(self.codes.iterkeys())))
            loc = 'bottom'
        if is_string_like(loc):
            loc = self.codes.get(loc, 1)
        self.set_figure(ax.figure)
        self._axes = ax
        self._loc = loc
        self._bbox = bbox

        # use axes coords
        self.set_transform(ax.transAxes)

        self._texts = []
        self._cells = {}
        self._autoRows = []
        self._autoColumns = []
        self._autoFontsize = True

        self.set_clip_on(False)

        self._cachedRenderer = None
Beispiel #3
0
 def get_markerfacecolor(self):
     if self._markerfacecolor is None or (
         is_string_like(self._markerfacecolor) and self._markerfacecolor.lower() == "none"
     ):
         return self._markerfacecolor
     elif is_string_like(self._markerfacecolor) and self._markerfacecolor.lower() == "auto":
         return self._color
     else:
         return self._markerfacecolor
Beispiel #4
0
 def get_markerfacecolor(self):
     if (self._markerfacecolor is None or
         (is_string_like(self._markerfacecolor) and
          self._markerfacecolor.lower()=='none') ):
         return self._markerfacecolor
     elif (is_string_like(self._markerfacecolor) and
           self._markerfacecolor.lower() == 'auto'):
         return self._color
     else:
         return self._markerfacecolor
    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (fc is None or (is_string_like(fc) and fc.lower()=='none') ):
            return fc
        elif (is_string_like(fc) and fc.lower() == 'auto'):
            return self._color
        else:
            return fc
Beispiel #6
0
    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (fc is None or (is_string_like(fc) and fc.lower() == 'none')):
            return fc
        elif (is_string_like(fc) and fc.lower() == 'auto'):
            return self._color
        else:
            return fc
    def to_rgba_list(self, c):
        """
        Returns a list of rgba tuples.

        Accepts a single mpl color spec or a sequence of specs.
        If the sequence is a list, the list items are changed in place.
        """
        # This can be improved after removing float-as-grayscale.
        if not is_string_like(c):
            try:
                N = len(c) # raises TypeError if it is not a sequence
                # Temporary hack: keep single rgb or rgba from being
                # treated as grayscale.
                if N==3 or N==4:
                    L = [x for x in c if x>=0 and x<=1]
                    if len(L) == N:
                        raise ValueError
                # If c is a list, we need to return the same list but
                # with modified items so that items can be appended to
                # it. This is needed for examples/dynamic_collections.py.
                if not isinstance(c, list): # specific; don't need duck-typing
                    c = list(c)
                self._gray = False
                for i, cc in enumerate(c):
                    c[i] = self.to_rgba(cc, warn=False)  # change in place
                if self._gray:
                    msg = "In argument %s: use string, not float, for grayscale" % str(c)
                    warnings.warn(msg, DeprecationWarning)
                return c
            except (ValueError, TypeError):
                pass
        try:
            return [self.to_rgba(c)]
        except (ValueError, TypeError):
            raise TypeError('c must be a matplotlib color arg or a sequence of them')
Beispiel #8
0
 def _get_rgba_face(self, alt=False):
     facecolor = self._get_markerfacecolor(alt=alt)
     if is_string_like(facecolor) and facecolor.lower() == 'none':
         rgbaFace = None
     else:
         rgbaFace = colorConverter.to_rgba(facecolor, self._alpha)
     return rgbaFace
Beispiel #9
0
    def __init__(self, 
                 x=0, y=0, text='',
                 color=None,          # defaults to rc params
                 verticalalignment='bottom',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None, # defaults to FontProperties()
                 rotation=None,
                 ):

        Artist.__init__(self)
        if not is_string_like(text):
            raise TypeError('text must be a string type')
        self.cached = {}
        self._x, self._y = x, y

        if color is None: color = rcParams['text.color']
        if fontproperties is None: fontproperties=FontProperties()

        self._color = color
        self.set_text(text)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment        
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._renderer = None        
Beispiel #10
0
 def __init__(self, colors, name='from_list', N=None):
     """
     """
     self.colors = colors
     self.monochrome = False  # True only if all colors in map are identical;
     # needed for contouring.
     if N is None:
         N = len(self.colors)
     else:
         if is_string_like(self.colors):
             self.colors = [self.colors] * N
             self.monochrome = True
         elif iterable(self.colors):
             if len(self.colors) == 1:
                 self.monochrome = True
             if len(self.colors) < N:
                 self.colors = list(self.colors) * N
                 del (self.colors[N:])
         else:
             try:
                 gray = float(self.colors)
             except TypeError:
                 pass
             else:
                 self.colors = [gray] * N
             self.monochrome = True
     Colormap.__init__(self, name, N)
Beispiel #11
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
Beispiel #12
0
 def _get_rgb_face(self):
     facecolor = self.get_markerfacecolor()
     if is_string_like(facecolor) and facecolor.lower()=='none':
         rgbFace = None
     else:
         rgbFace = colorConverter.to_rgb(facecolor)
     return rgbFace
Beispiel #13
0
    def to_rgb(self, arg):
        """
        returns a tuple of three floats from 0-1.  arg can be a matlab
        format string, a html hex color string, an rgb tuple, or a
        float between 0 and 1.  In the latter case, grayscale is used
        """
        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

        try:
            if is_string_like(arg):
                str1 = cnames.get(arg, arg)
                if str1.startswith('#'):
                    color = hex2color(str1)
                else:
                    color = self.colors[arg]
            elif isinstance(arg, (float,int)):
                if 0<=arg<=1:
                    color = (arg,arg,arg)
                else:
                    raise ValueError('Floating point color arg must be between 0 and 1')
            else: # assume tuple (or list)
                assert isinstance(arg[2], (float,int))
                color = tuple(arg[:3])           

            self.cache[arg] = color # raise exception if color not set

        except KeyError:            
            raise ValueError('to_rgb: Invalid rgb arg "%s"' % (str(arg)))
        except Exception, exc:
            raise ValueError('to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))
Beispiel #14
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)
Beispiel #15
0
    def to_rgb(self, arg):
        """
        returns a tuple of three floats from 0-1.  arg can be a matlab
        format string, a html hex color string, an rgb tuple, or a
        float between 0 and 1.  In the latter case, grayscale is used
        """
        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

        try:
            if is_string_like(arg):
                str1 = cnames.get(arg, arg)
                if str1.startswith('#'):
                    color = hex2color(str1)
                else:
                    color = self.colors[arg]
            elif isinstance(arg, (float,int)):
                if 0<=arg<=1:
                    color = (arg,arg,arg)
                else:
                    raise ValueError('Floating point color arg must be between 0 and 1')
            else: # assume tuple (or list)
                assert isinstance(arg[2], (float,int))
                color = tuple(arg[:3])

            self.cache[arg] = color # raise exception if color not set

        except KeyError:
            raise ValueError('to_rgb: Invalid rgb arg "%s"' % (str(arg)))
        except Exception, exc:
            raise ValueError('to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))
Beispiel #16
0
 def _get_rgba_ln_color(self, alt=False):
     ln_color = self._color
     if is_string_like(ln_color) and ln_color.lower() == 'none':
         rgba_ln = None
     else:
         rgba_ln = colorConverter.to_rgba(ln_color, self._alpha)
     return rgba_ln
Beispiel #17
0
 def _get_rgba_face(self, alt=False):
     facecolor = self._get_markerfacecolor(alt=alt)
     if is_string_like(facecolor) and facecolor.lower() == 'none':
         rgbaFace = None
     else:
         rgbaFace = colorConverter.to_rgba(facecolor, self._alpha)
     return rgbaFace
Beispiel #18
0
def save(fname, X, fmt='%1.4f'):
    """
    Save the data in X to file fname using fmt string to convert the
    data to strings

    fname can be a filename or a file handle    

    Example usage:

    save('test.out', X)         # X is an array
    save('test1.out', (x,y,z))  # x,y,z equal sized 1D arrays
    save('test2.out', x)        # x is 1D
    save('test3.out', x, fmt='%1.4e')  # use exponential notation

    """

    if is_string_like(fname):
        fh = file(fname, 'w')
    elif hasattr(fname, 'seek'):
        fh = fname
    else:
        raise ValueError('fname must be a string or file handle')

    
    X = asarray(X)
    origShape = None
    if len(X.shape)==1:
        origShape = X.shape
        X.shape = len(X), 1
    for row in X:
        fh.write(' '.join([fmt%val for val in row]) + '\n')

    if origShape is not None:
        X.shape = origShape
Beispiel #19
0
    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))
Beispiel #20
0
 def _get_rgba_ln_color(self, alt=False):
     ln_color = self._color
     if is_string_like(ln_color) and ln_color.lower() == 'none':
         rgba_ln = None
     else:
         rgba_ln = colorConverter.to_rgba(ln_color, self._alpha)
     return rgba_ln
Beispiel #21
0
 def _get_rgb_face(self, alt=False):
     facecolor = self._get_markerfacecolor(alt=alt)
     if is_string_like(facecolor) and facecolor.lower() == "none":
         rgbFace = None
     else:
         rgbFace = colorConverter.to_rgb(facecolor)
     return rgbFace
Beispiel #22
0
    def _process_yloc(self, yloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcy to place the y coord at
        draw time
        """
        props = dict()
        if is_numlike(yloc):
            return # nothing to do

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

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

            inout, bottomtop = tup
            
            if inout not in ('inside', 'outside'):
                raise ValueError('y in/out: bad location code "%s"'%yloc)
            if bottomtop not in ('bottom', 'top'):
                raise ValueError('y bottom/top: bad location code "%s"'%yloc)
            if inout=='inside' and bottomtop=='bottom':
                props['verticalalignment'] = 'bottom'
                def funcy(bottom, top):
                    return bottom
                if self._pady=='auto':
                    self._pady = self._autopad
            elif inout=='inside' and bottomtop=='top':
                props['verticalalignment'] = 'top'
                def funcy(bottom, top):
                    return top
                if self._pady=='auto':
                    self._pady = -self._autopad
            elif inout=='outside' and bottomtop=='bottom':
                props['verticalalignment'] = 'top'
                def funcy(bottom, top):
                    return bottom
                if self._pady=='auto':
                    self._pady = -self._autopad
            elif inout=='outside' and bottomtop=='top':
                props['verticalalignment'] = 'bottom'
                def funcy(bottom, top):
                    return top
                if self._pady=='auto':
                    self._pady = self._autopad
                
        self.update(props)
        self._funcy = funcy
Beispiel #23
0
    def _process_xloc(self, xloc):
        """
        This function will set the horiz and vertical alignment
        properties, and set the attr _funcx to place the x coord at
        draw time
        """

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

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

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

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

        self.update(props)
        self._funcx = funcx
Beispiel #24
0
    def get_label_width(self, lev, fmt, fsize):
        "get the width of the label in points"
        if is_string_like(lev):
            lw = (len(lev)) * fsize
        else:
            lw = (len(fmt % lev)) * fsize

        return lw
Beispiel #25
0
    def get_label_width(self, lev, fmt, fsize):
        "get the width of the label in points"
        if is_string_like(lev):
            lw = (len(lev)) * fsize
        else:
            lw = (len(fmt%lev)) * fsize

        return lw
Beispiel #26
0
 def _get_rgb_face(self):
     if (self._markerfacecolor is None
             or (is_string_like(self._markerfacecolor)
                 and self._markerfacecolor.lower() == 'none')):
         rgbFace = None
     else:
         rgbFace = colorConverter.to_rgb(self._markerfacecolor)
     return rgbFace
Beispiel #27
0
 def _get_rgb_face(self):
     if self._markerfacecolor is None or (
         is_string_like(self._markerfacecolor) and self._markerfacecolor.lower() == "none"
     ):
         rgbFace = None
     else:
         rgbFace = colorConverter.to_rgb(self._markerfacecolor)
     return rgbFace
Beispiel #28
0
    def set_fontproperties(self, fp):
        """
        Set the font properties that control the text

        ACCEPTS: a matplotlib.font_manager.FontProperties instance
        """
        if is_string_like(fp):
            fp = FontProperties(fp)
        self._fontproperties = fp
Beispiel #29
0
    def set_fontproperties(self, fp):
        """
        Set the font properties that control the text

        ACCEPTS: a matplotlib.font_manager.FontProperties instance
        """
        if is_string_like(fp):
            fp = FontProperties(fp)
        self._fontproperties = fp
Beispiel #30
0
 def get_markeredgecolor(self):
     if (is_string_like(self._markeredgecolor) and
                                 self._markeredgecolor == 'auto'):
         if self._marker.get_marker() in ('.', ','):
             return self._color
         if self._marker.is_filled():
             return 'k'  # Bad hard-wired default...
         else:
             return self._color
     return self._markeredgecolor
Beispiel #31
0
def datestr2num(d):
    """
    Convert a date string to a datenum using dateutil.parser.parse
    d can be a single string or a sequence of strings
    """
    if is_string_like(d):
        dt = dateutil.parser.parse(d)
        return date2num(dt)
    else:
        return date2num([dateutil.parser.parse(s) for s in d])
Beispiel #32
0
 def get_markeredgecolor(self):
     if (is_string_like(self._markeredgecolor)
             and self._markeredgecolor == 'auto'):
         if self._marker.get_marker() in ('.', ','):
             return self._color
         if self._marker.is_filled():
             return 'k'  # Bad hard-wired default...
         else:
             return self._color
     return self._markeredgecolor
Beispiel #33
0
    def get_markeredgecolor(self):
        if is_string_like(self._markeredgecolor) and self._markeredgecolor == "auto":
            if self._marker.is_filled():
                return "k"
            else:
                return self._color
        else:
            return self._markeredgecolor

        return self._markeredgecolor
Beispiel #34
0
def datestr2num(d):
    """
    Convert a date string to a datenum using dateutil.parser.parse
    d can be a single string or a sequence of strings
    """
    if is_string_like(d):
        dt = dateutil.parser.parse(d)
        return date2num(dt)
    else:
        return date2num([dateutil.parser.parse(s) for s in d])
Beispiel #35
0
    def get_markeredgecolor(self):
        if (is_string_like(self._markeredgecolor)
                and self._markeredgecolor == 'auto'):
            if self._marker in self.filled_markers:
                return 'k'
            else:
                return self._color
        else:
            return self._markeredgecolor

        return self._markeredgecolor
Beispiel #36
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))
Beispiel #37
0
 def get_markeredgecolor(self):
     mec = self._markeredgecolor
     if (is_string_like(mec) and mec == 'auto'):
         if self._marker.get_marker() in ('.', ','):
             return self._color
         if self._marker.is_filled() and self.get_fillstyle() != 'none':
             return 'k'  # Bad hard-wired default...
         else:
             return self._color
     else:
         return mec
Beispiel #38
0
    def set_text(self, s):
        """
Set the text string s

ACCEPTS: string
"""
        if not is_string_like(s):
            raise TypeError("This doesn't look like a string: '%s'"%s)
        self._text = s
        #self._substrings = scanner(s)  # support embedded mathtext
        self._substrings = []           # ignore embedded mathtext for now
Beispiel #39
0
    def __init__(self, x, y, lineWidth=1, color=ColorDispatcher().get('b')):
        Artist.__init__(self)
        #convert sequences to numeric arrays

        self._linewidth = lineWidth
        if is_string_like(color):
            color = ColorDispatcher().get(color)
        self._color = color
        self.verticalOffset = None

        self.set_data(x, y)
Beispiel #40
0
 def get_markeredgecolor(self):
     mec = self._markeredgecolor
     if is_string_like(mec) and mec == "auto":
         if self._marker.get_marker() in (".", ","):
             return self._color
         if self._marker.is_filled() and self.get_fillstyle() != "none":
             return "k"  # Bad hard-wired default...
         else:
             return self._color
     else:
         return mec
Beispiel #41
0
 def get_markeredgecolor(self):
     mec = self._markeredgecolor
     if (is_string_like(mec) and mec == 'auto'):
         if self._marker.get_marker() in ('.', ','):
             return self._color
         if self._marker.is_filled() and self.get_fillstyle() != 'none':
             return 'k'  # Bad hard-wired default...
         else:
             return self._color
     else:
         return mec
Beispiel #42
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
Beispiel #43
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
Beispiel #44
0
    def __init__(self, ax, loc=None, bbox=None):

        Artist.__init__(self)

        if is_string_like(loc) and not self.codes.has_key(loc):
            verbose.report_error('Unrecognized location %s. Falling back on bottom; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys())))
            loc = 'bottom'
        if is_string_like(loc): loc = self.codes.get(loc, 1)
        self.set_figure(ax.figure)
        self._axes = ax
        self._loc = loc
        self._bbox = bbox

        # use axes coords
        self.set_transform(ax.transAxes)

        self._texts = []
        self._cells = {}
        self._autoRows = []
        self._autoColumns = []
        self._autoFontsize = True
Beispiel #45
0
    def get_markeredgecolor(self):
        if (is_string_like(self._markeredgecolor) and
            self._markeredgecolor == 'auto'):
            if self._marker in self.filled_markers:
                return 'k'
            else:
                return self._color
        else:
            return self._markeredgecolor


        return self._markeredgecolor
    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))
Beispiel #47
0
    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (is_string_like(fc) and fc.lower() == 'auto'):
            if self.get_fillstyle() == 'none':
                return 'none'
            else:
                return self._color
        else:
            return fc
Beispiel #48
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
Beispiel #49
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
Beispiel #50
0
 def draw(self, renderer):
     if not self.get_visible(): return
     renderer.open_group('polycollection')
     self._transform.freeze()
     self._transOffset.freeze()
     self.update_scalarmappable()
     if is_string_like(self._edgecolors) and self._edgecolors[:2] == 'No':
         self._linewidths = (0, )
         #self._edgecolors = self._facecolors
     renderer.draw_poly_collection(self._verts, self._transform,
                                   self.clipbox, self._facecolors,
                                   self._edgecolors, self._linewidths,
                                   self._antialiaseds, self._offsets,
                                   self._transOffset)
     self._transform.thaw()
     self._transOffset.thaw()
     renderer.close_group('polycollection')
Beispiel #51
0
    def get(self, arg):
        """
        Get a color by arg if arg is a char in the colors dict, or by
        integer index using a ring buffer if arg is an int
        """

        if isinstance(arg,gtk.gdk.Color):
            return arg
        if is_string_like(arg):
            color =  self._colors.get(arg)
            if color is None:
                raise KeyError, 'Unrecognized color string %s' % arg
            else: return color
        try: ind = arg % self._N
        except TypeError:
            raise TypeError, 'arg must be a string or int'
        else: return self._colors[self._colorOrder[ind]]
Beispiel #52
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
Beispiel #53
0
    def set_alpha(self, alpha):
        """
        Set the alpha tranpancies of the collection.  Alpha must be
        a float.

        ACCEPTS: float
        """
        try:
            float(alpha)
        except TypeError:
            raise TypeError('alpha must be a float')
        else:
            Artist.set_alpha(self, alpha)
            self._facecolors = [(r, g, b, alpha)
                                for r, g, b, a in self._facecolors]
            if is_string_like(self._edgecolors) and self._edgecolors != 'None':
                self._edgecolors = [(r, g, b, alpha)
                                    for r, g, b, a in self._edgecolors]
Beispiel #54
0
    def to_rgb(self, arg):
        """
        returns a tuple of three floats from 0-1.  arg can be a matlab
        format string, a html hex color string, an rgb tuple, or a
        float between 0 and 1.  In the latter case, grayscale is used
        """
        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

        color = None
        try:
            float(arg)
        except:
            if is_string_like(arg):
                hex = cnames.get(arg)
                if hex is not None: arg = hex
                if len(arg) == 7 and arg[0] == '#':
                    color = hex2color(arg)
            if color is None:
                # see if it looks like rgb.  If so, just return arg
                try:
                    float(arg[2])
                except:
                    color = self.colors.get(arg, (0.0, 0.0, 0.0))
                else:
                    color = tuple(arg)
        else:
            if arg >= 0 and arg <= 1:
                color = (arg, arg, arg)
            else:
                msg = 'Floating point color arg must be between 0 and 1\n' +\
                      'Found %1.2f' % arg
                raise RuntimeError(msg)

        self.cache[arg] = color
        return color