Python matplotlib.colors.ColorConverter() Examples

The following are 11 code examples of matplotlib.colors.ColorConverter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.colors , or try the search function .
Example #1
Source File: textbox.py    From visual_dynamics with MIT License 5 votes vote down vote up
def set_bgcolor(self, color, alpha=1.0):
        self._ax.set_axis_bgcolor(ColorConverter().to_rgba(color, alpha))
        self.draw() 
Example #2
Source File: textbox.py    From visual_dynamics with MIT License 5 votes vote down vote up
def draw(self):
        color, alpha = self._ax.get_axis_bgcolor(), self._ax.get_alpha()
        self._ax.set_axis_bgcolor(mpl.rcParams['figure.facecolor'])
        self._ax.draw_artist(self._ax.patch)
        self._ax.set_axis_bgcolor(ColorConverter().to_rgba(color, alpha))

        self._ax.draw_artist(self._ax.patch)
        self._ax.draw_artist(self._text_box)
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #3
Source File: config.py    From threeML with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_matplotlib_color(color):
        # color_converter = colors.ColorConverter()

        try:

            return colors.is_color_like(color)

        except (ValueError):

            return False 
Example #4
Source File: svg_to_axes.py    From figurefirst with MIT License 5 votes vote down vote up
def mplkwargs(self):
        mpl_map = {"stroke": "edgecolor", "stroke-width": "lw", "fill": "facecolor"}
        mpl_kwargs = {}
        keylist = list()
        for k, v in self.style.items():
            try:
                mpl_kwargs[mpl_map[k]] = v
            except KeyError:
                pass
        from matplotlib.colors import ColorConverter

        converter = ColorConverter()
        for k, v in mpl_kwargs.items():
            if k == "lw":
                tmp = v.split("px")[0]
                tmp = (
                    self.layout.from_userx(tmp, "in") / 13.889e-3
                )  # hard coding pnt scaling
                mpl_kwargs["lw"] = tmp
            if k == "edgecolor":
                mpl_kwargs["edgecolor"] = np.array(
                    converter.to_rgba(v, float(self.style["stroke-opacity"]))
                )
            if k == "facecolor":
                mpl_kwargs["facecolor"] = np.array(
                    converter.to_rgba(v, float(self.style["fill-opacity"]))
                )
        return mpl_kwargs 
Example #5
Source File: matplotlib_venn.py    From altanalyze with Apache License 2.0 5 votes vote down vote up
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])) 
Example #6
Source File: matplotlib_venn.py    From altanalyze with Apache License 2.0 5 votes vote down vote up
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])) 
Example #7
Source File: colors.py    From tropycal with MIT License 5 votes vote down vote up
def make_colormap(colors,whiten=0):
    
    z  = np.array(sorted(colors.keys()))
    n  = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)
    
    CC = mcolors.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 = mcolors.LinearSegmentedColormap('mymap',cmap_dict)
    
    return mymap 
Example #8
Source File: multi_scatter.py    From glue-vispy-viewers with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def set_color(self, label, rgb):
        if isinstance(rgb, str):
            rgb = ColorConverter().to_rgb(rgb)
        self.layers[label]['color'] = np.asarray(rgb)
        self._update() 
Example #9
Source File: layer_artist.py    From glue-vispy-viewers with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _update_cmap_from_color(self):
        cmap = get_translucent_cmap(*ColorConverter().to_rgb(self.state.color))
        self._multivol.set_cmap(self.id, cmap)
        self.redraw() 
Example #10
Source File: math_flowable.py    From rst2pdf with MIT License 4 votes vote down vote up
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 not fontname 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) 
Example #11
Source File: math_flowable.py    From rst2pdf with MIT License 4 votes vote down vote up
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(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