Пример #1
0
 def IsValidColour(self, color):
     """Checks if color is a valid matplotlib color"""
     try:
         cc = ColorConverter()
         cc.to_rgb(color)
         return True
     except ValueError:  #invalid color
         return False
Пример #2
0
 def IsValidColour(self, color):
     """Checks if color is a valid matplotlib color"""
     try:
         cc = ColorConverter()
         cc.to_rgb(color)
         return True
     except ValueError: #invalid color
         return False
Пример #3
0
    def drawOn(self, canv, x, y, _sW=0):
        if _sW and hasattr(self, 'hAlign'):
            from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT

            a = self.hAlign
            if a in ('CENTER', 'CENTRE', TA_CENTER):
                x = x + 0.5 * _sW
            elif a in ('RIGHT', TA_RIGHT):
                x = x + _sW
            elif a not in ('LEFT', TA_LEFT):
                raise ValueError("Bad hAlign value " + str(a))
        height = 0
        if HAS_MATPLOTLIB:
            global fonts
            canv.saveState()
            canv.translate(x, y)
            try:
                (
                    width,
                    height,
                    descent,
                    glyphs,
                    rects,
                    used_characters,
                ) = self.parser.parse(enclose(self.s),
                                      72,
                                      prop=FontProperties(size=self.fontsize))
                for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                    if fontname not in fonts:
                        fonts[fontname] = fontname
                        pdfmetrics.registerFont(TTFont(fontname, fontname))
                    canv.setFont(fontname, fontsize)
                    col_conv = ColorConverter()
                    rgb_color = col_conv.to_rgb(self.color)
                    canv.setFillColorRGB(rgb_color[0], rgb_color[1],
                                         rgb_color[2])
                    canv.drawString(ox, oy, chr(num))

                canv.setLineWidth(0)
                canv.setDash([])
                for ox, oy, width, height in rects:
                    canv.rect(ox, oy + 2 * height, width, height, fill=1)
            except Exception:
                # FIXME: report error
                col_conv = ColorConverter()
                rgb_color = col_conv.to_rgb(self.color)
                canv.setFillColorRGB(rgb_color[0], rgb_color[1], rgb_color[2])
                canv.drawString(0, 0, self.s)
            canv.restoreState()
        else:
            canv.saveState()
            canv.drawString(x, y, self.s)
            canv.restoreState()
        if self.label:
            log.info('Drawing equation-%s' % self.label)
            canv.bookmarkHorizontal('equation-%s' % self.label, 0, height)
Пример #4
0
def linear_gradient(cstart, cend, n=10):
    '''
    Return a gradient list of `n` colors going from `cstart` to `cend`.
    '''
    s = np.array(ColorConverter.to_rgb(cstart))
    f = np.array(ColorConverter.to_rgb(cend))

    rgb_list = [s + (t / (n - 1)) * (f - s) for t in range(n)]

    return rgb_list
Пример #5
0
 def validate_color(self, color):
     """ Function for validating Matplotlib user input color choice
     """
     print color
     c = ColorConverter()
     try:
         print c.to_rgb(color)
     except:
         return False
     return True
Пример #6
0
def colorMask(v1, v2):
    cc = ColorConverter()
    mask = []
    for i in range(len(v1)):
        if v1[i] == v2[i]:
            mask.append(cc.to_rgb("black"))
        elif v1[i] < v2[i]:
            mask.append(cc.to_rgb("red"))
        else:
            mask.append(cc.to_rgb("blue"))
    return mask
Пример #7
0
def set_legend_to_bw(leg, style, colormap, line_style='continuous'):
    """
    Takes the figure legend and converts it to black and white. Note that
    it currently only converts lines to black and white, other artist 
    intances are currently not being supported, and might cause errors or
    other unexpected behavior.
    
    Parameters
    ----------
    leg : legend
    style : {GREYSCALE, HATCHING}
    colormap : dict
               mapping of color to B&W rendering
    line_style: str
                linestyle to use for converting, can be continuous, black
                or None
                
    # TODO:: None is strange as a value, and should be field based, see
    # set_ax_lines_bw
    
    """
    color_converter = ColorConverter()

    if leg:
        if isinstance(leg, list):
            leg = leg[0]

        for element in leg.legendHandles:
            if isinstance(element, mpl.collections.PathCollection):
                rgb_orig = color_converter.to_rgb(element._facecolors[0])
                new_color = color_converter.to_rgba(colormap[rgb_orig]['fill'])
                element._facecolors = np.array((new_color, ))
            elif isinstance(element, mpl.patches.Rectangle):
                rgb_orig = color_converter.to_rgb(element._facecolor)

                if style == HATCHING:
                    element.update({'alpha': 1})
                    element.update({'facecolor': 'none'})
                    element.update({'edgecolor': 'black'})
                    element.update({'hatch': colormap[rgb_orig]['hatch']})
                elif style == GREYSCALE:
                    ema_logging.info(colormap.keys())
                    element.update({'facecolor': colormap[rgb_orig]['fill']})
                    element.update({'edgecolor': colormap[rgb_orig]['fill']})
            else:
                line = element
                orig_color = line.get_color()

                line.set_color('black')
                if not line_style == 'continuous':
                    line.set_dashes(colormap[orig_color]['dash'])
                    line.set_marker(colormap[orig_color]['marker'])
                    line.set_markersize(MARKERSIZE)
def set_legend_to_bw(leg, style, colormap, line_style='continuous'):
    """
    Takes the figure legend and converts it to black and white. Note that
    it currently only converts lines to black and white, other artist 
    intances are currently not being supported, and might cause errors or
    other unexpected behavior.
    
    Parameters
    ----------
    leg : legend
    style : {GREYSCALE, HATCHING}
    colormap : dict
               mapping of color to B&W rendering
    line_style: str
                linestyle to use for converting, can be continuous, black
                or None
                
    # TODO:: None is strange as a value, and should be field based, see
    # set_ax_lines_bw
    
    """
    color_converter = ColorConverter()

    if leg:
        if isinstance(leg, list):
            leg = leg[0]
    
        for element in leg.legendHandles:
            if isinstance(element, mpl.collections.PathCollection):
                rgb_orig = color_converter.to_rgb(element._facecolors[0])
                new_color = color_converter.to_rgba(colormap[rgb_orig]['fill'])
                element._facecolors = np.array((new_color,))
            elif isinstance(element, mpl.patches.Rectangle):
                rgb_orig = color_converter.to_rgb(element._facecolor)
                
                if style==HATCHING:
                    element.update({'alpha':1})
                    element.update({'facecolor':'none'})
                    element.update({'edgecolor':'black'})
                    element.update({'hatch':colormap[rgb_orig]['hatch']})
                elif style==GREYSCALE:
                    ema_logging.info(colormap.keys())
                    element.update({'facecolor':colormap[rgb_orig]['fill']})
                    element.update({'edgecolor':colormap[rgb_orig]['fill']})
            else:
                line = element
                orig_color = line.get_color()
                
                line.set_color('black')
                if not line_style=='continuous':
                    line.set_dashes(colormap[orig_color]['dash'])
                    line.set_marker(colormap[orig_color]['marker'])
                    line.set_markersize(MARKERSIZE)
Пример #9
0
def set_legend_to_bw(leg, style):
    """
    Takes the figure legend and converts it to black and white. Note that
    it currently only converts lines to black and white, other artist 
    intances are currently not being supported, and might cause errors or
    other unexpected behavior.
    
    Parameters
    ----------
    leg : legend
    style : {GREYSCALE, HATCHING}
    
    """
    color_converter = ColorConverter()
    colors = {}
    for key, value in color_converter.colors.items():
        colors[value] = key
    
    if leg:
        if isinstance(leg, list):
            leg = leg[0]
    
        for element in leg.legendHandles:
            if isinstance(element, mpl.collections.PathCollection):
                rgb_orig = color_converter.to_rgb(element._facecolors[0])
                origColor = colors[rgb_orig]
                new_color = color_converter.to_rgba(COLORMAP[origColor]['fill'])
                element._facecolors = np.array((new_color,))
            elif isinstance(element, mpl.patches.Rectangle):
                rgb_orig = color_converter.to_rgb(element._facecolor)
                c = colors[rgb_orig]
                
                if style==HATCHING:
                    element.update({'alpha':1})
                    element.update({'facecolor':'none'})
                    element.update({'edgecolor':'black'})
                    element.update({'hatch':COLORMAP[c]['hatch']})
                elif style==GREYSCALE:
                    element.update({'facecolor':COLORMAP[c]['fill']})
                    element.update({'edgecolor':COLORMAP[c]['fill']})

            else:
                line = element
                origColor = line.get_color()
                line.set_color('black')
                line.set_dashes(COLORMAP[origColor]['dash'])
                line.set_marker(COLORMAP[origColor]['marker'])
                line.set_markersize(MARKERSIZE)
Пример #10
0
def make_colormap(colors,whiten=0):
    import numpy as np
    from matplotlib.colors import LinearSegmentedColormap, ColorConverter
    
    z  = np.array(sorted(colors.keys()))
    n  = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)
    
    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in range(n):
        Ci = colors[z[i]]
        if type(Ci) == str:
            RGB = CC.to_rgb(Ci)
        else:
            RGB = Ci
        R.append(RGB[0] + (1-RGB[0])*whiten)
        G.append(RGB[1] + (1-RGB[1])*whiten)
        B.append(RGB[2] + (1-RGB[2])*whiten)
    
    cmap_dict = {}
    cmap_dict['red']   = [(x0[i],R[i],R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
    cmap_dict['blue']  = [(x0[i],B[i],B[i]) for i in range(len(B))]
    mymap = LinearSegmentedColormap('mymap',cmap_dict)
    
    return mymap
Пример #11
0
def _return_rgb_colors():
    """."""
    colors = ['#9E0142', '#B31C42', '#C93742', '#DE5242', '#F46D43', '#F68955', '#F9A667',
              '#FBC379', '#FEE08B', '#F8E58E', '#F2EA91', '#ECEF94', '#E6F598', '#C6E89B',
              '#A6DB9E', '#86CEA1', '#66C2A5', '#64A5A4', '#6288A3', '#606BA2', '#5E4FA2']
    cc = ColorConverter()
    return [cc.to_rgb(i) for i in colors]
def _set_ax_pathcollection_to_bw(collection, ax, style, colormap):
    '''helper function for converting a pathcollection to black and white
    
    Parameters
    ----------
    collection : pathcollection
    ax : axes
    style : {GREYSCALE, HATCHING}
    colormap : dict
               mapping of color to B&W rendering
    
    '''
    color_converter = ColorConverter()
    colors = {}
    for key, value in color_converter.colors.items():
        colors[value] = key    

    rgb_orig = collection._facecolors_original
    rgb_orig = [color_converter.to_rgb(row) for row in rgb_orig]
    
    new_color = [color_converter.to_rgba(colormap[entry]['fill']) for entry 
                 in rgb_orig]
    new_color = np.asarray(new_color)
    
    collection.update({'facecolors' : new_color}) 
    collection.update({'edgecolors' : new_color}) 
Пример #13
0
 def parse_list_of_colors(self, number, colors):
     from matplotlib.colors import ColorConverter
     cconvert = ColorConverter()
     if number != len(colors):
         raise ValueError("the length of colors must be the number of groups")
     rgbcolors = [cconvert.to_rgb(c) for c in colors]
     return rgbcolors 
Пример #14
0
def set_legend_to_bw(leg):
    """
    Takes the figure legend and converts it to black and white. Note that
    it currently only converts lines to black and white, other artist 
    intances are currently not being supported, and might cause errors or
    other unexpected behavior.
    
    :param fig: The figure which needs to be transformed to B&W.
    
    """
    color_converter = ColorConverter()
    colors = {}
    for key, value in color_converter.colors.items():
        colors[value] = key
    
    if leg:
        if type(leg) == ListType:
            leg = leg[0]
    
        for element in leg.legendHandles:
            if isinstance(element, mpl.collections.PathCollection):
                rgb_orig = color_converter.to_rgb(element._facecolors[0])
                origColor = colors[rgb_orig]
                new_color = color_converter.to_rgba(COLORMAP[origColor]['fill'])
                element._facecolors = np.array((new_color,))
            else:
                line = element
                origColor = line.get_color()
                line.set_color('black')
                line.set_dashes(COLORMAP[origColor]['dash'])
                line.set_marker(COLORMAP[origColor]['marker'])
                line.set_markersize(MARKERSIZE)
Пример #15
0
def _set_ax_pathcollection_to_bw(collection, ax, style, colormap):
    '''helper function for converting a pathcollection to black and white

    Parameters
    ----------
    collection : pathcollection
    ax : axes
    style : {GREYSCALE, HATCHING}
    colormap : dict
               mapping of color to B&W rendering

    '''
    color_converter = ColorConverter()
    colors = {}
    for key, value in color_converter.colors.items():
        colors[value] = key

    rgb_orig = collection._original_facecolor

    if isinstance(rgb_orig, six.string_types):
        rgb_orig = [rgb_orig]
    rgb_orig = [color_converter.to_rgb(row) for row in rgb_orig]

    new_color = [color_converter.to_rgba(colormap[entry]['fill']) for entry
                 in rgb_orig]
    new_color = np.asarray(new_color)

    collection.update({'facecolors': new_color})
    collection.update({'edgecolors': new_color})
Пример #16
0
def make_colormap(colors):
    z = np.sort(colors.keys())
    n = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)
    
    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in range(n):
        Ci = colors[z[i]]      
        if type(Ci) == str:
            RGB = CC.to_rgb(Ci)
        else:
            RGB = Ci
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])

    cmap_dict = {}
    cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
    cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
    mymap = LinearSegmentedColormap('mymap',cmap_dict)
    return mymap
def get_rgb_hexad_color_palete():
    """Returns a list of RGB values with the color palette used to plot the
    transit vehicles returned by NextBus. Each entry returned in the color
    palette has the RGB hexadecimal format, and without the prefix '0x' as
    for colors in Google Maps, nor the prefix '#' for the matplotlib color.
    Ie., the entry for blue is returned as '0000FF' and for red 'FF0000'."""

    # We don't use these color names directly because their intensity might
    # be (are) reflected diferently between between the remote server and
    # matplotlib, and this difference in rendering a same color affects the
    # color-legend in matplotlib. For this reason too, we don't need to use
    # only the named colors in Google Maps but more in matplotlib, for in
    # both cases hexadecimal RGB values are really used.

    high_contrast_colors = ["green", "red", "blue", "yellow", "aqua",
                            "brown", "gray", "honeydew", "purple",
                            "turquoise", "magenta", "orange"]

    from matplotlib.colors import ColorConverter, rgb2hex

    color_converter = ColorConverter()
    hex_color_palette = [rgb2hex(color_converter.to_rgb(cname))[1:] for \
                         cname in high_contrast_colors]
    # matplotlib.colors.cnames[cname] could have been used instead of rgb2hex

    return hex_color_palette
Пример #18
0
def get_rgb_hexad_color_palete():
    """Returns a list of RGB values with the color palette used to plot the
    transit vehicles returned by NextBus. Each entry returned in the color
    palette has the RGB hexadecimal format, and without the prefix '0x' as
    for colors in Google Maps, nor the prefix '#' for the matplotlib color.
    Ie., the entry for blue is returned as '0000FF' and for red 'FF0000'."""

    # We don't use these color names directly because their intensity might
    # be (are) reflected diferently between between the remote server and
    # matplotlib, and this difference in rendering a same color affects the
    # color-legend in matplotlib. For this reason too, we don't need to use
    # only the named colors in Google Maps but more in matplotlib, for in
    # both cases hexadecimal RGB values are really used.

    high_contrast_colors = [
        "green", "red", "blue", "yellow", "aqua", "brown", "gray", "honeydew",
        "purple", "turquoise", "magenta", "orange"
    ]

    from matplotlib.colors import ColorConverter, rgb2hex

    color_converter = ColorConverter()
    hex_color_palette = [rgb2hex(color_converter.to_rgb(cname))[1:] for \
                         cname in high_contrast_colors]
    # matplotlib.colors.cnames[cname] could have been used instead of rgb2hex

    return hex_color_palette
Пример #19
0
    def make_colormap(self, key):
        """ define a new color map based on values specified in the color_scale file for the key"""
        #colors = {0.1:'#005a00', 0.2:'#6e0dc6',0.3:'#087fdb',0.4:'#1c47e8',0.5:'#007000'} # parsed result format from color_scale file
        colors = self.colorTable[key]
        z = sort(colors.keys()) ## keys
        n = len(z)
        z1 = min(z)
        zn = max(z)
        x0 = (z - z1) / (zn - z1)   ## normalized keys
        CC = ColorConverter()
        R = []
        G = []
        B = []
        for i in range(n):
            ## i'th color at level z[i]:
            Ci = colors[z[i]]      
            if type(Ci) == str:
                ## a hex string of form '#ff0000' for example (for red)
                RGB = CC.to_rgb(Ci)
            else:
                ## assume it's an RGB triple already:
                RGB = Ci
            R.append(RGB[0])
            G.append(RGB[1])
            B.append(RGB[2])

        cmap_dict = {}
        cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))] ## normalized value in X0
        cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
        cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
        mymap = LinearSegmentedColormap(key,cmap_dict)
        return mymap, z
def plot_em(step, X, K, amps, means, covs, z,
            newamps, newmeans, newcovs, show=True):
    import pylab as plt
    from matplotlib.colors import ColorConverter

    (N,D) = X.shape

    if z is None:
        z = np.zeros((N,K))
        for k,(amp,mean,cov) in enumerate(zip(amps, means, covs)):
            z[:,k] = amp * gaussian_probability(X, mean, cov)
        z /= np.sum(z, axis=1)[:,np.newaxis]
    
    plt.clf()
    # snazzy color coding
    cc = np.zeros((N,3))
    CC = ColorConverter()
    for k in range(K):
        rgb = np.array(CC.to_rgb(colors[k]))
        cc += z[:,k][:,np.newaxis] * rgb[np.newaxis,:]

    plt.scatter(X[:,0], X[:,1], color=cc, s=9, alpha=0.5)

    ax = plt.axis()
    for k,(amp,mean,cov) in enumerate(zip(amps, means, covs)):
        plot_ellipse(mean, cov, 'k-', lw=4)
        plot_ellipse(mean, cov, 'k-', color=colors[k], lw=2)

    plt.axis(ax)
    if show:
        plt.show()
Пример #21
0
    def drawOn(self, canv, x, y, _sW=0):
        if _sW and hasattr(self, 'hAlign'):
            from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
            a = self.hAlign
            if a in ('CENTER', 'CENTRE', TA_CENTER):
                x = x + 0.5 * _sW
            elif a in ('RIGHT', TA_RIGHT):
                x = x + _sW
            elif a not in ('LEFT', TA_LEFT):
                raise ValueError("Bad hAlign value " + str(a))
        height = 0
        if HAS_MATPLOTLIB:
            global fonts
            canv.saveState()
            canv.translate(x, y)
            try:
                width, height, descent, glyphs, rects, used_characters = \
                    self.parser.parse(enclose(self.s), 72,
                                      prop=FontProperties(size=self.fontsize))
                for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                    if fontname not in fonts:
                        fonts[fontname] = fontname
                        pdfmetrics.registerFont(TTFont(fontname, fontname))
                    canv.setFont(fontname, fontsize)
                    col_conv = ColorConverter()
                    rgb_color = col_conv.to_rgb(self.color)
                    canv.setFillColorRGB(rgb_color[0], rgb_color[1], rgb_color[2])
                    canv.drawString(ox, oy, chr(num))

                canv.setLineWidth(0)
                canv.setDash([])
                for ox, oy, width, height in rects:
                    canv.rect(ox, oy + 2 * height, width, height, fill=1)
            except:
                # FIXME: report error
                col_conv = ColorConverter()
                rgb_color = col_conv.to_rgb(self.color)
                canv.setFillColorRGB(rgb_color[0], rgb_color[1], rgb_color[2])
                canv.drawString(0, 0, self.s)
            canv.restoreState()
        else:
            canv.saveState()
            canv.drawString(x, y, self.s)
            canv.restoreState()
        if self.label:
            log.info('Drawing equation-%s' % self.label)
            canv.bookmarkHorizontal('equation-%s' % self.label, 0, height)
Пример #22
0
    def genImage(self):
        """Create a PNG from the contents of this flowable.

        Required so we can put inline math in paragraphs.
        Returns the file name.
        The file is caller's responsability.

        """

        dpi = 72
        scale = 10

        try:
            import Image
            import ImageFont
            import ImageDraw
            import ImageColor
        except ImportError:
            from PIL import (
                Image,
                ImageFont,
                ImageDraw,
                ImageColor,
            )

        if not HAS_MATPLOTLIB:
            img = Image.new('RGBA', (120, 120), (255, 255, 255, 0))
        else:
            width, height, descent, glyphs,\
            rects, used_characters = self.parser.parse(
                enclose(self.s), dpi, prop=FontProperties(size=self.fontsize))
            img = Image.new('RGBA', (int(width * scale), int(height * scale)),
                            (255, 255, 255, 0))
            draw = ImageDraw.Draw(img)
            for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                font = ImageFont.truetype(fontname, int(fontsize * scale))
                tw, th = draw.textsize(unichr(num), font=font)
                # No, I don't understand why that 4 is there.
                # As we used to say in the pure math
                # department, that was a numerical solution.
                col_conv = ColorConverter()
                fc = col_conv.to_rgb(self.color)
                rgb_color = (int(fc[0] * 255), int(fc[1] * 255),
                             int(fc[2] * 255))
                draw.text((ox * scale, (height - oy - fontsize + 4) * scale),
                          unichr(num),
                          font=font,
                          fill=rgb_color)
            for ox, oy, w, h in rects:
                x1 = ox * scale
                x2 = x1 + w * scale
                y1 = (height - oy) * scale
                y2 = y1 + h * scale
                draw.rectangle([x1, y1, x2, y2], (0, 0, 0))

        fh, fn = tempfile.mkstemp(suffix=".png")
        os.close(fh)
        img.save(fn)
        return fn
Пример #23
0
def idx2color(idx, colorpalette, isscatter):
    if idx is None:
        c = (0, 0, 0)
    else:
        c = ColorConverter.to_rgb(
            sns.color_palette(colorpalette).as_hex()[idx])
    if isscatter: c = np.atleast_2d(np.asarray(c))
    return c
Пример #24
0
 def MplToWxColour(self, color):
     """Converts matplotlib color (0-1) to wx.Colour (0-255)"""
     try:
         cc = ColorConverter()
         rgb = tuple([d * 255 for d in cc.to_rgb(color)])
         return wx.Colour(*rgb)
     except ValueError:  #invalid color
         return wx.Colour()
Пример #25
0
 def MplToWxColour(self, color):
     """Converts matplotlib color (0-1) to wx.Colour (0-255)"""
     try:
         cc = ColorConverter()
         rgb = tuple([d*255 for d in cc.to_rgb(color)])
         return wx.Colour(*rgb)
     except ValueError: #invalid color
         return wx.Colour()
Пример #26
0
    def parse_list_of_colors(self, number, colors):
        from matplotlib.colors import ColorConverter

        cconvert = ColorConverter()
        if number != len(colors):
            raise ValueError(
                "the length of colors must be the number of groups")
        rgbcolors = [cconvert.to_rgb(c) for c in colors]
        return rgbcolors
Пример #27
0
def compute_venn2_colors(set_colors):
    """
    Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    returns a list of 6 elements, providing colors for regions (Ab_in, Ab_out, aB_in, aB_out, AB_in, AB_out).
    """
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    return base_colors[0], base_colors[1], mix_colors(base_colors[0],
                                                      base_colors[1])
Пример #28
0
    def genImage(self):
        """Create a PNG from the contents of this flowable.

        Required so we can put inline math in paragraphs.
        Returns the file name.
        The file is caller's responsability.
        """
        dpi = 72
        scale = 10

        try:
            import Image
            import ImageFont
            import ImageDraw
        except ImportError:
            from PIL import (
                Image,
                ImageFont,
                ImageDraw,
            )

        if not HAS_MATPLOTLIB:
            img = Image.new('RGBA', (120, 120), (255, 255, 255, 0))
        else:
            width, height, descent, glyphs, rects, used_characters = \
                self.parser.parse(enclose(self.s), dpi,
                                  prop=FontProperties(size=self.fontsize))
            img = Image.new('RGBA', (int(width * scale), int(height * scale)),
                            (255, 255, 255, 0))
            draw = ImageDraw.Draw(img)
            for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                font = ImageFont.truetype(fontname, int(fontsize * scale))
                tw, th = draw.textsize(chr(num), font=font)
                # No, I don't understand why that 4 is there.
                # As we used to say in the pure math
                # department, that was a numerical solution.
                col_conv = ColorConverter()
                fc = col_conv.to_rgb(self.color)
                rgb_color = (
                    int(fc[0] * 255),
                    int(fc[1] * 255),
                    int(fc[2] * 255)
                )
                draw.text((ox * scale, (height - oy - fontsize + 4) * scale),
                          chr(num), font=font, fill=rgb_color)
            for ox, oy, w, h in rects:
                x1 = ox * scale
                x2 = x1 + w * scale
                y1 = (height - oy) * scale
                y2 = y1 + h * scale
                draw.rectangle([x1, y1, x2, y2], (0, 0, 0))

        fh, fn = tempfile.mkstemp(suffix=".png")
        os.close(fh)
        img.save(fn)
        return fn
Пример #29
0
    def mplot_surface(self, ures=8, vres=8, figax=False, **kwargs):
        """Plot the enclosing surfaces of the volume using Mayavi's `mesh()` function

        Parameters
        ----------
        ures, vres : int
            Specifies the oversampling of the original
            volume in u and v directions. For example:
            if `ures` = 2, and `self.u` = [0, 1, 2, 3],
            then the surface will be resampled at
            [0, 0.5, 1, 1.5, 2, 2.5, 3] prior to
            plotting.

        kwargs : dict
            See Mayavi docs for `mesh()`

        Returns
        -------
            None
        """
        from mayavi import mlab
        from matplotlib.colors import ColorConverter

        if not 'color' in kwargs:
            # Generate random color
            cvec = np.random.rand(3)
            cvec /= math.sqrt(cvec.dot(cvec))
            kwargs['color'] = tuple(cvec)
        else:
            # The following will convert text strings representing
            # colors into their (r, g, b) equivalents (which is
            # the only way Mayavi will accept them)
            from matplotlib.colors import ColorConverter
            cconv = ColorConverter()
            if kwargs['color'] is not None:
                kwargs['color'] = cconv.to_rgb(kwargs['color'])

        # Make new u and v values of (possibly) higher resolution
        # the original ones.
        hru, hrv = self._resample_uv(ures, vres)
        # Sample the surface at the new u, v values and plot
        meshpts1 = self.ev(hru, hrv, np.max(self.l))
        meshpts2 = self.ev(hru, hrv, np.min(self.l))

        if figax is None:
            m1 = mlab.mesh(*meshpts1, **kwargs)
            m2 = mlab.mesh(*meshpts2, **kwargs)

            # Turn off perspective
            fig = mlab.gcf()
            fig.scene.camera.trait_set(parallel_projection=1)
            return fig
        else:
            fig, ax = figax
            m1 = ax.plot_surface(*meshpts1, **kwargs)
            m2 = ax.plot_surface(*meshpts2, **kwargs)
Пример #30
0
def compute_venn2_colors(set_colors):
    '''
    Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    returns a list of 3 elements, providing colors for regions (10, 01, 11).
    >>> compute_venn2_colors(('r', 'g'))
    (array([ 1.,  0.,  0.]), array([ 0. ,  0.5,  0. ]), array([ 0.7 ,  0.35,  0.  ]))
    '''
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
Пример #31
0
def modify_color(color, d_saturation=0., d_lightness=0.):
    conv = ColorConverter()
    if not isinstance(color, tuple):
        rgb_color = conv.to_rgb(color)
    else:
        rgb_color = color
    hls_color = rgb_to_hls(*rgb_color)
    new_l = max(0, min(0.9, hls_color[1] + d_lightness))
    new_s = max(0, min(1, hls_color[2] + d_saturation))
    return hls_to_rgb(hls_color[0], new_l, new_s)
Пример #32
0
    def mplot_volume(self, ures=8, vres=8, **kwargs):
        """Plot the volume using Mayavi's `scalar_scatter()` function

        Parameters
        ----------
        ures, vres : int
            Specifies the oversampling of the original
            volume in u and v directions. For example:
            if `ures` = 2, and `self.u` = [0, 1, 2, 3],
            then the surface will be resampled at
            [0, 0.5, 1, 1.5, 2, 2.5, 3] prior to
            plotting.

        kwargs : dict
            See Mayavi docs for `mesh()`

        Returns
        -------
            None
        """
        from mayavi import mlab
        from matplotlib.colors import ColorConverter

        if not 'color' in kwargs:
            # Generate random color
            cvec = np.random.rand(3)
            cvec /= math.sqrt(cvec.dot(cvec))
            kwargs['color'] = tuple(cvec)
        else:
            # The following will convert text strings representing
            # colors into their (r, g, b) equivalents (which is
            # the only way Mayavi will accept them)
            from matplotlib.colors import ColorConverter
            cconv = ColorConverter()
            if kwargs['color'] is not None:
                kwargs['color'] = cconv.to_rgb(kwargs['color'])

        # Make new u and v values of (possibly) higher resolution
        # the original ones.
        hru, hrv = self._resample_uv(ures, vres)
        volpts = self.ev(hru, hrv, self.l).reshape(3, -1)

        s = np.ones_like(volpts[0, :])
        sct = mlab.pipeline.scalar_scatter(volpts[0, :], volpts[1, :],
                                           volpts[2, :], s, **kwargs)
        ug = mlab.pipeline.delaunay3d(sct)
        mq = mlab.pipeline.user_defined(ug, filter='MeshQuality')
        c2d = mlab.pipeline.cell_to_point_data(mq)
        aa = mlab.pipeline.set_active_attribute(c2d)
        vol = mlab.pipeline.surface(aa, **kwargs)

        # Turn off perspective
        fig = mlab.gcf()
        fig.scene.camera.trait_set(parallel_projection=1)
        return fig
Пример #33
0
def _parse_colour(x):
    if isinstance(x, basestring):
        from matplotlib.colors import ColorConverter
        c = ColorConverter()
        x = c.to_rgb(x)

    if isinstance(x, (tuple, list)):
        # Assume we have a floating point rgb
        if any(a <= 1.0 for a in x):
            x = [int(a * 255) for a in x]
    return tuple(x)
Пример #34
0
def _parse_colour(x):
    if isinstance(x, basestring):
        from matplotlib.colors import ColorConverter
        c = ColorConverter()
        x = c.to_rgb(x)

    if isinstance(x, (tuple, list)):
        # Assume we have a floating point rgb
        if any(a <= 1.0 for a in x):
            x = [int(a * 255) for a in x]
    return tuple(x)
Пример #35
0
def compute_venn3_colors(set_colors):
    '''
    Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
    >>> compute_venn3_colors(['r', 'g', 'b'])
    (array([ 1.,  0.,  0.]),..., array([ 0.4,  0.2,  0.4]))
    '''
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]), base_colors[2],
            mix_colors(base_colors[0], base_colors[2]), mix_colors(base_colors[1], base_colors[2]), mix_colors(base_colors[0], base_colors[1], base_colors[2]))
Пример #36
0
def compute_venn2_colors(set_colors):
    '''
    Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    returns a list of 3 elements, providing colors for regions (10, 01, 11).

    >>> compute_venn2_colors(('r', 'g'))
    (array([ 1.,  0.,  0.]), array([ 0. ,  0.5,  0. ]), array([ 0.7 ,  0.35,  0.  ]))
    '''
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
Пример #37
0
def compute_venn3_colors(set_colors):
    '''
    Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).

    >>> compute_venn3_colors(['r', 'g', 'b'])
    (array([ 1.,  0.,  0.]),..., array([ 0.4,  0.2,  0.4]))
    '''
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]), base_colors[2],
            mix_colors(base_colors[0], base_colors[2]), mix_colors(base_colors[1], base_colors[2]), mix_colors(base_colors[0], base_colors[1], base_colors[2]))
Пример #38
0
def _set_ax_pathcollection_to_bw(collection, ax, style):
        color_converter = ColorConverter()
        colors = {}
        for key, value in color_converter.colors.items():
            colors[value] = key    

        rgb_orig = collection._facecolors_original
        rgb_orig = [color_converter.to_rgb(row) for row in rgb_orig]
        color = [colors.get(entry) for entry in rgb_orig]
        new_color = [color_converter.to_rgba(COLORMAP[entry]['fill']) for entry in color]
        new_color = np.asarray(new_color)
        collection.update({'facecolors' : new_color}) 
        collection.update({'edgecolors' : 'black'}) 
Пример #39
0
def create_gradient(values, low, high, mid=None, val_range=None, intervals=100):
    
    # get anchor values
    vmin = val_range[0] if val_range is not None else values.min()
    vmax = val_range[1] if val_range is not None else values.max()
    vmid = (vmax+vmin)/2

    # get anchor colors
    cc = ColorConverter()
    low_color = np.array(cc.to_rgb(low))
    high_color = np.array(cc.to_rgb(high))
    mid_color = np.array(cc.to_rgb(mid)) if mid is not None else \
        (np.array(low_color)+np.array(high_color))/2
    
    # create array of values in order
    vals_low = np.linspace(vmin, vmid, intervals+1)
    vals_high = np.linspace(vmid, vmax, intervals+1)
    all_vals = np.unique(np.append(vals_low, vals_high))
    
    # calculate hex color representaitons for all values
    color_list = [low_color, mid_color, high_color]
    step_list = [(mid_color-low_color), (high_color-mid_color)]
    step_list = [l/intervals for l in step_list]
    color_range = []
    for v in all_vals:
        i = all_vals.tolist().index(v)
        j = 0 if i <= intervals else 1
        i = i - (intervals * j) - j
        nexti = color_list[0+j]+(step_list[j]*i)
        hsv = colorsys.rgb_to_hsv(*nexti)
        r, g, b = colorsys.hsv_to_rgb(*hsv)
        hex_value = '#%02X%02X%02X' % (r * 255, g * 255, b * 255)
        color_range.append(hex_value)

    # bring everything together
    output_values = [color_range[np.abs(v-all_vals).argmin()] for v in values]
    output_values = np.array(output_values)

    return output_values
def _identify_colors(fig):
    '''Identify the various colors that are used in the figure and
    return as a set
    
    '''
    
    color_converter = ColorConverter()
    all_colors = set()
    
    for ax in fig.axes:
        for line in ax.get_lines():
            orig_color = line.get_color()
            all_colors.add(orig_color)
        
        for patch in ax.patches:
            rgb_orig = color_converter.to_rgb(patch._facecolor)
            all_colors.add(rgb_orig)
                
        for collection in ax.collections:
            for color in collection.get_facecolor():
                rgb_orig = color_converter.to_rgb(color)
                all_colors.add(rgb_orig)
    
    return all_colors
Пример #41
0
def _identify_colors(fig):
    '''Identify the various colors that are used in the figure and
    return as a set

    '''

    color_converter = ColorConverter()
    all_colors = set()

    for ax in fig.axes:
        for line in ax.get_lines():
            orig_color = line.get_color()
            all_colors.add(orig_color)

        for patch in ax.patches:
            rgb_orig = color_converter.to_rgb(patch._facecolor)
            all_colors.add(rgb_orig)

        for collection in ax.collections:
            for color in collection.get_facecolor():
                rgb_orig = color_converter.to_rgb(color)
                all_colors.add(rgb_orig)

    return all_colors
Пример #42
0
def mpl_to_qt4_color(color):
    """ Convert a matplotlib color stirng into a PyQT4 QColor object

    Parameters
    ----------
    color: String
       A color specification that matplotlib understands

    Returns
    -------
    A QColor object representing color

    """
    cc = ColorConverter()
    r, g, b = cc.to_rgb(color)
    return QColor(r * 255, g * 255, b * 255)
Пример #43
0
def gen_image(bool_matrix, colors=("#BF5264","beige"), figsize=None):
    """Generates an image from a matrix of booleans
                        
    :param bool_matrix: array of booleans
    :type bool_matrix: :py:code:`numpy.ndArray`
    """
    from matplotlib.colors import ColorConverter
    from scipy.misc import toimage
    cc = ColorConverter()
    rgb_colors = [cc.to_rgb(x) for x in colors]
    new_matrix = np.zeros(bool_matrix.shape + (3,))
    for i in range(3):
      new_matrix[:,:,i] = np.where(bool_matrix, rgb_colors[0][i], rgb_colors[1][i])

    img = toimage(new_matrix)
    img.save("ca_smallest.png")
Пример #44
0
def compute_venn_colors(set_colors):
    """
    Given any amount of base colors, computes combinations of colors corresponding to all regions of the venn diagram.
    It returns a list of X elements, where X is the number of available combinations.

    >>> compute_venn_colors(['r', 'g', 'b', 'y'])
    (array([ 1.,  0.,  0.]),..., array([ 0.4,  0.2,  0.4]))
    """
    ccv = ColorConverter()
    base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
    final = []
    for num in range(len(set_colors)):
        for combination in combinations(range(len(set_colors)), num):
            final.append(mix_colors(*[base_colors[_] for _ in combination]))

    return tuple(final)
Пример #45
0
    def updatePage(self,modelSel):
        if modelSel is None:
            self.txt.SetLabel("")
            return
    
        txtLabel = modelSel.get_name()
        self.txt.SetLabel(txtLabel)
        log.info(txtLabel)
            
        self.__modelSel = modelSel

        if self.pg.GetPageCount()>0:
            self.pg.RemovePage(0)
        self.pg.AddPage(txtLabel)        
        
        #modelSel        
        for name, propertyKey in modelSel.getProperties().items():
            propertyClass = propertyMap[propertyKey]            
            value=modelSel.getAttr(name)
            
            ## To be handled by custom property 
            if "alpha" == name and value is None:
                value = 1.0
            
            if "color" == propertyKey:
                c = ColorConverter()

                if isinstance(value,(unicode,str)):
                    if "none" ==  value.lower():
                        value = None
                    else:
                        value = c.to_rgb(value)
                
                if not value is None:
                    try:
                        r,g,b = value
                    except:
                        r,g,b,_ = value
                    value = wx.Colour(r*255,g*255,b*255)
                
            ## 
            log.info("%s:%s"%(name,value))
            if not value is None:
                self.pg.Append(propertyClass(name,value=value))
            else:
                self.pg.Append(propertyClass(name))
Пример #46
0
    def updatePage(self,modelSel):
        if modelSel is None:
            self.txt.SetLabel("")
            return
    
        txtLabel = modelSel.get_name()
        self.txt.SetLabel(txtLabel)
        log.info(txtLabel)
            
        self.__modelSel = modelSel

        if self.pg.GetPageCount()>0:
            self.pg.RemovePage(0)
        self.pg.AddPage(txtLabel)        
        
        #modelSel        
        for name, propertyKey in modelSel.getProperties().items():
            propertyClass = propertyMap[propertyKey]            
            value=modelSel.getAttr(name)
            
            ## To be handled by custom property 
            if "alpha" == name and value is None:
                value = 1.0
            
            if "color" == propertyKey:
                c = ColorConverter()

                if isinstance(value,(unicode,str)):
                    if "none" ==  value.lower():
                        value = None
                    else:
                        value = c.to_rgb(value)
                
                if not value is None:
                    try:
                        r,g,b = value
                    except:
                        r,g,b,_ = value
                    value = wx.Colour(r*255,g*255,b*255)
                
            ## 
            log.info("%s:%s"%(name,value))
            if not value is None:
                self.pg.Append(propertyClass(name,value=value))
            else:
                self.pg.Append(propertyClass(name))
Пример #47
0
def make_colormap(colors):
#-------------------------
    """
    Define a new color map based on values specified in the dictionary
    colors, where colors[z] is the color that value z should be mapped to,
    with linear interpolation between the given values of z.

    The z values (dictionary keys) are real numbers and the values
    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
    html hex string, e.g. "#ff0000" for red.
    """

    from matplotlib.colors import LinearSegmentedColormap, ColorConverter
    from numpy import sort

    z = [i for i in colors.keys()]
    z = sort(z)
    n = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)

    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in range(n):
        #i'th color at level z[i]:
        Ci = colors[z[i]]
        if type(Ci) == str:
            # a hex string of form '#ff0000' for example (for red)
            RGB = CC.to_rgb(Ci)
        else:
            # assume it's an RGB triple already:
            RGB = Ci
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])

    cmap_dict = {}
    cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
    cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
    mymap = LinearSegmentedColormap('mymap',cmap_dict)
    return mymap
Пример #48
0
def make_colormap(colors):
    #-------------------------
    """
    Define a new color map based on values specified in the dictionary
    colors, where colors[z] is the color that value z should be mapped to,
    with linear interpolation between the given values of z.

    The z values (dictionary keys) are real numbers and the values
    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
    html hex string, e.g. "#ff0000" for red.
    """

    from matplotlib.colors import LinearSegmentedColormap, ColorConverter
    from numpy import sort

    z = [i for i in colors.keys()]
    z = sort(z)
    n = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)

    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in range(n):
        #i'th color at level z[i]:
        Ci = colors[z[i]]
        if type(Ci) == str:
            # a hex string of form '#ff0000' for example (for red)
            RGB = CC.to_rgb(Ci)
        else:
            # assume it's an RGB triple already:
            RGB = Ci
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])

    cmap_dict = {}
    cmap_dict['red'] = [(x0[i], R[i], R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(x0[i], G[i], G[i]) for i in range(len(G))]
    cmap_dict['blue'] = [(x0[i], B[i], B[i]) for i in range(len(B))]
    mymap = LinearSegmentedColormap('mymap', cmap_dict)
    return mymap
Пример #49
0
def make_colormap(colors):
    from matplotlib.colors import LinearSegmentedColormap, ColorConverter
    z = np.sort(list(colors.keys()))
    anchors = (z - min(z)) / (max(z) - min(z))
    CC = ColorConverter()
    R, G, B = [], [], []
    for i in range(len(z)):
        Ci = colors[z[i]]
        RGB = CC.to_rgb(Ci)
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])
    cmap_dict = {}
    cmap_dict['red'] = [(anchors[i], R[i], R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(anchors[i], G[i], G[i]) for i in range(len(G))]
    cmap_dict['blue'] = [(anchors[i], B[i], B[i]) for i in range(len(B))]
    mymap = LinearSegmentedColormap('mymap', cmap_dict)
    return mymap
Пример #50
0
    def color_chooser(self, property):
        """ Creates a box with widgets related to choosing a color.

        :param property: A color related key in matplotlib.rcParams.

        :returns: A box with widgets.
        """
        cc = ColorConverter()
        rgb = cc.to_rgb(mpl.rcParams[property])
        logger = log_api.env_logger()
        logger.debug('{0} {1}'.format(property, rgb))

        r = widgets.FloatSlider(min=0, max=1, value=rgb[0], description='Red')
        r.border_color = 'red'

        g = widgets.FloatSlider(min=0,
                                max=1,
                                value=rgb[1],
                                description='Green')
        g.border_color = 'green'

        b = widgets.FloatSlider(min=0, max=1, value=rgb[2], description='Blue')
        b.border_color = 'blue'

        h = widgets.widget_string.HTML(property)
        # TODO put this in a func
        hex = rgb2hex((rgb[0], rgb[1], rgb[2]))
        h.value = '<p style="background-color: {0};">{0}</p>'.format(hex)

        def update(name, value):
            hex = rgb2hex((r.value, g.value, b.value))
            h.value = '<p style="background-color: {0};">{0}</p>'.format(hex)
            self.rc_widget.process(property, hex)

        r.on_trait_change(update, 'value')
        g.on_trait_change(update, 'value')
        b.on_trait_change(update, 'value')

        box = widgets.VBox(children=(r, g, b, h))
        box.border_style = 'dotted'
        box.description = property

        return box
Пример #51
0
def gen_big_image(bool_matrix, colors=("#BF5264","beige")):
    """Generates an image using PIL instead"""
    from matplotlib.colors import ColorConverter
    from scipy.misc import toimage
    cc = ColorConverter()
    rgb_colors = [cc.to_rgb(x) for x in colors]
    new_matrix = np.zeros(bool_matrix.shape + (3,))
    for i in range(3):
      new_matrix[:,:,i] = np.where(bool_matrix, rgb_colors[0][i], rgb_colors[1][i])

    n_imgs = bool_matrix.shape[0] / 2000
    for i in range(n_imgs):
      img = toimage(new_matrix[i*2000:(i+1)*2000,:,:])
      img.save("ca{0}.png".format(i))

    remainder = bool_matrix.shape[0] % 2000
    if remainder > 0:
      img = toimage(new_matrix[n_imgs*2000:n_imgs*2000+remainder,:,:])
      img.save("ca{0}.png".format(n_imgs))
Пример #52
0
def set_ax_patches_bw(ax):
    """
    Take each patch in the axes, ax, and convert the face color to be 
    suitable for black and white viewing.
    
    Parameters
    ----------
    ax : axes
         The ax of which the patches needs to be transformed to B&W.
    
    """    
    
    color_converter = ColorConverter()
    
    for patch in ax.patches:
        rgb_orig = color_converter.to_rgb(patch._facecolor)
        new_color = color_converter.to_rgba(COLORMAP[rgb_orig]['fill'])
        
        patch._facecolor = new_color
Пример #53
0
def set_ax_patches_bw(ax):
    """
    Take each patch in the axes, ax, and convert the face color to be 
    suitable for black and white viewing.
    
    :param ax: The ax of which the patches needs to be transformed to B&W.
    
    """    
    
    color_converter = ColorConverter()
    colors = {}
    for key, value in color_converter.colors.items():
        colors[value] = key
    
    for patch in ax.patches:
        rgb_orig = color_converter.to_rgb(patch._facecolor)
        origColor = colors[rgb_orig]
        new_color = color_converter.to_rgba(COLORMAP[origColor]['fill'])
        
        patch._facecolor = new_color
Пример #54
0
def mpl_to_qt4_color(color, alpha=1.0):
    """ Convert a matplotlib color stirng into a PyQT4 QColor object

    :param color:
       A color specification that matplotlib understands
    :type color: str

    :param alpha:
       Optional opacity. Float in range [0,1]
    :type alpha: float

    * Returns *
    A QColor object representing color

    :rtype: QColor
    """
    cc = ColorConverter()
    r, g, b = cc.to_rgb(color)
    alpha = max(0, min(255, int(256 * alpha)))
    return QColor(r * 255, g * 255, b * 255, alpha)
Пример #55
0
def imsave(fname, arr, **kwargs):

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.colors import ColorConverter as CC
    C = CC()
    
    import pylab
    if pylab.isinteractive():
        i_was_on = True
        pylab.ioff()
    else:
        i_was_on = False
        
    fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
    canvas = FigureCanvas(fig)

    if 'background' in kwargs.keys():
        if kwargs['background'] != 'transparent':
            [r,g,b] = C.to_rgb(kwargs['background'])
            BG = numpy.ones(shape=(arr.shape[0],arr.shape[1],3))
            BG[:,:,0] = r
            BG[:,:,1] = g
            BG[:,:,2] = b
            fig.figimage(BG)

    fig.figimage(arr,
                 xo = kwargs.get('xo',0),
                 yo = kwargs.get('yo',0),
                 alpha = kwargs.get('alpha',None),
                 norm = kwargs.get('norm',None),
                 cmap = kwargs.get('cmap',None),
                 vmin = kwargs.get('vmin',None),
                 vmax = kwargs.get('vmax',None),
                 origin = kwargs.get('origin',None))
    
    fig.savefig(fname,
                dpi=1,
                format = kwargs.get('format',None))
    if i_was_on:
        pylab.ion()
Пример #56
0
def mpl_to_qt4_color(color, alpha=1.0):
    """
    Convert a matplotlib color stirng into a Qt QColor object

    Parameters
    ----------
    color : str
       A color specification that matplotlib understands
    alpha : float
        Optional opacity. Float in range [0,1]

    Returns
    -------
    qcolor : ``QColor``
        A QColor object representing the converted color
    """
    if color in [None, 'none', 'None']:
        return QtGui.QColor(0, 0, 0, 0)

    cc = ColorConverter()
    r, g, b = cc.to_rgb(color)
    alpha = max(0, min(255, int(256 * alpha)))
    return QtGui.QColor(r * 255, g * 255, b * 255, alpha)
Пример #57
0
def _plot_dominant_classes_2D(self, ax, **kwargs):

    if self.plot_subclasses:
        probs = self.subclass_probs
    else:
        probs = self.probs

    # <>TODO: come up with more elegant solution than scatter plot
    # Identify colors of critical classes for each state
    np.set_printoptions(threshold=np.nan)
    max_pdf_indices = np.argmax(probs, axis=1)
    max_colors = np.take(self.class_colors, max_pdf_indices)
    cc = ColorConverter()
    max_colors_rgb = np.array([cc.to_rgb(_) for _ in max_colors])

    ax.scatter(self.X, self.Y, c=max_colors_rgb, marker='s', s=100,
               linewidths=0, alpha=1)

    ax.set_xlim(self.bounds[0], self.bounds[2])
    ax.set_ylim(self.bounds[1], self.bounds[3])
    ax.set_xlabel('x1')
    ax.set_ylabel('x2')
    ax.set_title('Critical Classes')