当前位置: 首页>>代码示例>>Python>>正文


Python ColorConverter.to_rgb方法代码示例

本文整理汇总了Python中matplotlib.colors.ColorConverter.to_rgb方法的典型用法代码示例。如果您正苦于以下问题:Python ColorConverter.to_rgb方法的具体用法?Python ColorConverter.to_rgb怎么用?Python ColorConverter.to_rgb使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.colors.ColorConverter的用法示例。


在下文中一共展示了ColorConverter.to_rgb方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: IsValidColour

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
 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
开发者ID:nrao,项目名称:deap,代码行数:10,代码来源:PlotEditFrame.py

示例2: validate_color

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
 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
开发者ID:c11,项目名称:TSTools,代码行数:12,代码来源:SavePlotDialog.py

示例3: colorMask

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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
开发者ID:ekeijl,项目名称:BeAT,代码行数:13,代码来源:graph.py

示例4: set_legend_to_bw

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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)
开发者ID:JamesPHoughton,项目名称:EMAworkbench,代码行数:55,代码来源:b_and_w_plotting.py

示例5: set_legend_to_bw

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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)
开发者ID:MasterNicknak007,项目名称:EMAworkbench,代码行数:50,代码来源:b_and_w_plotting.py

示例6: get_rgb_hexad_color_palete

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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
开发者ID:je-nunez,项目名称:NextBus_real_time_Route_Bus_locations_to_Pandas_Dataframe,代码行数:28,代码来源:plot_dataframe_nextbus_vehicle_locations.py

示例7: parse_list_of_colors

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
 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 
开发者ID:dimaslave,项目名称:pele,代码行数:9,代码来源:disconnectivity_graph.py

示例8: make_colormap

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
    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
开发者ID:jjhelmus,项目名称:lrose-soloPy,代码行数:34,代码来源:ColorMap.py

示例9: _set_ax_pathcollection_to_bw

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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}) 
开发者ID:JamesPHoughton,项目名称:EMAworkbench,代码行数:28,代码来源:b_and_w_plotting.py

示例10: plot_em

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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()
开发者ID:LocalGroupAstrostatistics2015,项目名称:Unsupervised,代码行数:33,代码来源:utils.py

示例11: make_colormap

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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
开发者ID:olga,项目名称:olga_model,代码行数:29,代码来源:colormaps.py

示例12: drawOn

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
    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)
开发者ID:aquavitae,项目名称:rst2pdf-py3-dev,代码行数:49,代码来源:math_flowable.py

示例13: MplToWxColour

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
 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()
开发者ID:nrao,项目名称:deap,代码行数:10,代码来源:PlotEditFrame.py

示例14: genImage

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
    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
开发者ID:aquavitae,项目名称:rst2pdf-py3-dev,代码行数:58,代码来源:math_flowable.py

示例15: compute_venn2_colors

# 需要导入模块: from matplotlib.colors import ColorConverter [as 别名]
# 或者: from matplotlib.colors.ColorConverter import to_rgb [as 别名]
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]))
开发者ID:alexanderwhatley,项目名称:matplotlib-venn,代码行数:12,代码来源:_venn2.py


注:本文中的matplotlib.colors.ColorConverter.to_rgb方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。