Python matplotlib.colors 模块,rgb2hex() 实例源码

我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用matplotlib.colors.rgb2hex()

项目:BinarySTLfileReader    作者:sukhbinder    | 项目源码 | 文件源码
def ShowCooordsTopology(coords,topo):
    '''Plots the STL if coords and topology is given.  '''
    ax = a3d.Axes3D(plt.figure())

    xm,ym,zm=coords.max(axis=0)
    xmi,ymi,zmi =coords.min(axis=0)

    for nodes in topo:
        tri = a3d.art3d.Poly3DCollection([coords[nodes,:3]])
        tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
        tri.set_edgecolor('k')
        ax.add_collection3d(tri)

    ax.set_xlim3d([xmi,xm])
    ax.set_ylim3d([ymi,ym])
    ax.set_zlim3d([zmi,zm])

    plt.show()
项目:BinarySTLfileReader    作者:sukhbinder    | 项目源码 | 文件源码
def ShowSTLFile(v1,v2,v3):
    '''Plots the STL files, give vertices v1,v2,v3'''
    ax = a3d.Axes3D(plt.figure())  

    xm,ym,zm=v1.max(axis=0)
    xmi,ymi,zmi =v2.min(axis=0)

    for i in range(v1.shape[0]):
        vtx=np.vstack((v1[i],v2[i],v3[i]))
        tri = a3d.art3d.Poly3DCollection([vtx])
        tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
        tri.set_edgecolor('k')
        ax.add_collection3d(tri)

    ax.set_xlim3d([xmi,xm])
    ax.set_ylim3d([ymi,ym])
    ax.set_zlim3d([zmi,zm])

    plt.show()
项目:hdhp.py    作者:Networks-Learning    | 项目源码 | 文件源码
def linear_gradient(start_hex, finish_hex="#FFFFFF", n=10):
    """Returns a gradient list of (n) colors between
    two hex colors. start_hex and finish_hex
    should be the full six-digit color string,
    including the number sign ("#FFFFFF")

    Code from http://bsou.io/posts/color-gradients-with-python
    """
    # Starting and ending colors in RGB form
    s = hex2color(start_hex)
    f = hex2color(finish_hex)
    # Initialize a list of the output colors with the starting color
    RGB_list = [rgb2hex(s)]
    # Calcuate a color at each evenly spaced value of t from 1 to n
    for t in range(1, n):
        # Interpolate RGB vector for color at the current value of t
        curr_vector = [s[j] + (t / (n - 1)) * (f[j] - s[j])
                       for j in range(3)]
        # Add it to our list of output colors
        RGB_list.append(rgb2hex(curr_vector))
    return RGB_list
项目:pecos    作者:sandialabs    | 项目源码 | 文件源码
def color_value(val):

    nThresholds = 10
    colors=[(0.75, 0.15, 0.15), (1, 0.75, 0.15), (0.15, 0.75, 0.15)]
    cmap = LinearSegmentedColormap.from_list(name='custom', colors = colors, N=nThresholds)

    return_color = ''
    if np.isnan(val):
        return_color = 'background-color: gray'
    elif val > 1:
        return_color = 'background-color: gray'
    elif val < 0:
        return_color = 'background-color: gray'
    else:
        binned_value = int(np.floor(val*10))
        rgb_color = cmap(binned_value)[:3]
        hex_color =  rgb2hex(rgb_color)
        return_color = 'background-color: ' + hex_color

    return return_color

# Define system names, location names, and analysis date
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
def scatter_group(ax, key, imask, adata, Y, projection='2d', size=3, alpha=None):
    """Scatter of group using representation of data Y.
    """
    mask = adata.smp[key].cat.categories[imask] == adata.smp[key].values
    color = adata.uns[key + '_colors'][imask]
    if not isinstance(color[0], str):
        from matplotlib.colors import rgb2hex
        color = rgb2hex(adata.uns[key + '_colors'][imask])
    if not is_color_like(color):
        raise ValueError('"{}" is not a valid matplotlib color.'.format(color))
    data = [Y[mask, 0], Y[mask, 1]]
    if projection == '3d': data.append(Y[mask, 2])
    ax.scatter(*data,
               marker='.',
               alpha=alpha,
               c=color,
               edgecolors='none',
               s=size,
               label=adata.smp[key].cat.categories[imask])
    return mask
项目:pygmtsar    作者:bakerunavco    | 项目源码 | 文件源码
def dismph_colormap():
    '''Make a custom colormap like the one used in dismph.  The list was
      created from dismphN.mat in geodmod which is a 64 segmented colormap
      using the following:
        from scipy.io import loadmat
        cmap = loadmat('dismphN.mat',struct_as_record=True)['dismphN']
        from matplotlib.colors import rgb2hex
        list=[]
        for i in cmap: list.append(rgb2hex(i))
    '''
    list = ['#f579cd', '#f67fc6', '#f686bf', '#f68cb9', '#f692b3', '#f698ad',
            '#f69ea7', '#f6a5a1', '#f6ab9a', '#f6b194', '#f6b78e', '#f6bd88',
            '#f6c482', '#f6ca7b', '#f6d075', '#f6d66f', '#f6dc69', '#f6e363',
            '#efe765', '#e5eb6b', '#dbf071', '#d0f477', '#c8f67d', '#c2f684',
            '#bbf68a', '#b5f690', '#aff696', '#a9f69c', '#a3f6a3', '#9cf6a9',
            '#96f6af', '#90f6b5', '#8af6bb', '#84f6c2', '#7df6c8', '#77f6ce',
            '#71f6d4', '#6bf6da', '#65f6e0', '#5ef6e7', '#58f0ed', '#52e8f3',
            '#4cdbf9', '#7bccf6', '#82c4f6', '#88bdf6', '#8eb7f6', '#94b1f6',
            '#9aabf6', '#a1a5f6', '#a79ef6', '#ad98f6', '#b392f6', '#b98cf6',
            '#bf86f6', '#c67ff6', '#cc79f6', '#d273f6', '#d86df6', '#de67f6',
            '#e561f6', '#e967ec', '#ed6de2', '#f173d7']
    dismphCM = matplotlib.colors.LinearSegmentedColormap.from_list('mycm', list)
    dismphCM.set_bad('w', 0.0)
    return dismphCM
项目:MOSFiT    作者:guillochon    | 项目源码 | 文件源码
def radiocolorf(freq):
    """Replace radio code with color."""
    ffreq = (float(freq) - 1.0) / (45.0 - 1.0)
    pal = sns.diverging_palette(200, 60, l=80, as_cmap=True, center="dark")
    return rgb2hex(pal(ffreq))
项目:ChainConsumer    作者:Samreay    | 项目源码 | 文件源码
def get_formatted(self, list_colors):
        formatted = []
        for c in list_colors:
            if isinstance(c, np.ndarray):
                c = rgb2hex(c)
            if c[0] == "#":
                formatted.append(c)
            elif c in self.color_map:
                formatted.append(self.color_map[c])
            elif c in self.aliases:
                alias = self.aliases[c]
                formatted.append(self.color_map[alias])
            else:
                raise ValueError("Color %s is not mapped. Please give a hex code" % c)
        return formatted
项目:SecuML    作者:ANSSI-FR    | 项目源码 | 文件源码
def colors(num):
    colors = cm.rainbow(np.linspace(0, 1, num))
    colors = map(rgb2hex, colors)
    return colors
项目:hdhp.py    作者:Networks-Learning    | 项目源码 | 文件源码
def qualitative_cmap(n_colors=17):
    """Returns a colormap suitable for a categorical plot with many categories.


    Parameters
    ----------
    n_colors : int, default is 17
        The number of colors that, usually, matches with the number of
        categories.


    Returns
    -------
    list
        A list of hex colors.
    """
    set1 = sns.mpl_palette("Set1", n_colors=9)
    hex_colors = [rgb2hex(rgb) for rgb in set1]
    hex_colors[5] = '#FFDE00'
    if n_colors <= 9:
        return hex_colors
    if n_colors <= 17:
        n_colors = 17
    else:
        n_colors = 8 * ceil((n_colors - 1) / 8)
    gradient = polylinear_gradient(hex_colors, n_colors)
    return gradient
项目:ms_deisotope    作者:mobiusklein    | 项目源码 | 文件源码
def random_colorizer(profile, *args, **kwargs):
    return mcolors.rgb2hex(np.random.rand(3))
项目:pyEPR    作者:zlatko-minev    | 项目源码 | 文件源码
def get_color_cycle(n, colormap=Plotting_Options.default_color_map, start=0., stop=1., format='hex'):
    pts = np.linspace(start, stop, n)
    if format == 'hex':
        colors = [rgb2hex(colormap(pt)) for pt in pts]
    return colors
项目:route-plotter    作者:perimosocordiae    | 项目源码 | 文件源码
def color_mapping(arr, cmap):
  sm = ScalarMappable(cmap=cmap)
  sm.set_array(arr)
  sm.autoscale()
  return map(rgb2hex, sm.to_rgba(arr))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _background_gradient(s, cmap='PuBu', low=0, high=0):
        """Color background in a range according to the data."""
        with _mpl(Styler.background_gradient) as (plt, colors):
            rng = s.max() - s.min()
            # extend lower / upper bounds, compresses color range
            norm = colors.Normalize(s.min() - (rng * low),
                                    s.max() + (rng * high))
            # matplotlib modifies inplace?
            # https://github.com/matplotlib/matplotlib/issues/5427
            normed = norm(s.values)
            c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
            return ['background-color: %s' % color for color in c]
项目:gcMapExplorer    作者:rjdkmr    | 项目源码 | 文件源码
def segmentDataColorMapToColorInfo(colormap):
    """ make a colormap information dictionary from
    segmented Data colormap object.

    Structure of ouput colorInfo dictionary

    colorInfo ----- 'name'
        |
        ?------ 'colors'
                    |
                    ?------ values -> color
                    |
                    ?------ values -> color
                    |
                    :
                    ?------ values -> color

    """
    colorInfo = dict()
    colorInfo['name'] = colormap.name
    colorInfo['colors'] = dict()
    for i in range(len(colormap._segmentdata['blue'])):
        value = colormap._segmentdata['blue'][i][0]
        r = colormap._segmentdata['red'][i][1]
        g = colormap._segmentdata['green'][i][1]
        b = colormap._segmentdata['blue'][i][1]
        a = colormap._segmentdata['alpha'][i][1]
        colorInfo['colors'][value] = mplColors.rgb2hex((r, g, b, a))

    return colorInfo
项目:astrocats    作者:astrocatalogs    | 项目源码 | 文件源码
def radiocolorf(freq):
    ffreq = (float(freq) - 1.0)/(45.0 - 1.0)
    pal = sns.diverging_palette(200, 60, l=80, as_cmap=True, center="dark")
    return rgb2hex(pal(ffreq))
项目:mizani    作者:has2k1    | 项目源码 | 文件源码
def grey_pal(start=0.2, end=0.8):
    """
    Utility for creating continuous grey scale palette

    Parameters
    ----------
    start : float
        grey value at low end of palette
    end : float
        grey value at high end of palette

    Returns
    -------
    out : function
        Continuous color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        equally spaced colors.


    >>> palette = grey_pal()
    >>> palette(5)
    ['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc']
    """
    gamma = 2.2
    ends = ((0.0, start, start), (1.0, end, end))
    cdict = {'red': ends, 'green': ends, 'blue': ends}
    grey_cmap = mcolors.LinearSegmentedColormap('grey', cdict)

    def continuous_grey_palette(n):
        colors = []
        # The grey scale points are linearly separated in
        # gamma encoded space
        for x in np.linspace(start**gamma, end**gamma, n):
            # Map points onto the [0, 1] palette domain
            x = (x ** (1./gamma) - start) / (end - start)
            colors.append(mcolors.rgb2hex(grey_cmap(x)))
        return colors

    return continuous_grey_palette
项目:mizani    作者:has2k1    | 项目源码 | 文件源码
def ratios_to_colors(values, colormap):
    """
    Map values in the range [0, 1] onto colors

    Parameters
    ----------
    values : array_like | float
        Numeric(s) in the range [0, 1]
    colormap : cmap
        Matplotlib colormap to use for the mapping

    Returns
    -------
    out : list | float
        Color(s) corresponding to the values
    """
    iterable = True
    try:
        iter(values)
    except TypeError:
        iterable = False
        values = [values]

    color_tuples = colormap(values)
    try:
        hex_colors = [mcolors.rgb2hex(t) for t in color_tuples]
    except IndexError:
        hex_colors = mcolors.rgb2hex(color_tuples)
    return hex_colors if iterable else hex_colors[0]
项目:freecad-nurbs    作者:microelly2    | 项目源码 | 文件源码
def dialog(sk=None):

    if sk==None:
        [sk]=Gui.Selection.getSelection()
    if 1:

        w=QtGui.QWidget()
        w.sk=sk
        w.texts=[]

        tc=sk.ViewObject.LineColor
        color=colors.rgb2hex(sk.ViewObject.LineColor)    
        invers=(1.0-tc[0],1.0-tc[1],1.0-tc[2])
        icolor=colors.rgb2hex(invers) 
        mcolor='#808080'   
        w.setStyleSheet("QWidget { background-color:"+color+"}\
            QPushButton { margin-right:0px;margin-left:0px;margin:0 px;padding:0px;;\
            background-color:#ccc;text-align:left;;padding:6px;padding-left:4px;color:#333; }")

        box = QtGui.QVBoxLayout()
        w.setLayout(box)
        w.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        l=QtGui.QLabel(sk.Label)
        l.setText( '<font color='+icolor+'>'+sk.Label+'</font>' ) 
        box.addWidget(l)

        w.box=[]
        for i,c in enumerate(sk.Constraints):
            print (c.Name,c.Value)
            if c.Name.startswith("Weight"):
                l=QtGui.QLabel(c.Name)
                l.setText( '<font color='+icolor+'>'+c.Name+'</font>' ) 
                box.addWidget(l)

                d=QtGui.QSlider(QtCore.Qt.Horizontal)
                d.c=c
                d.i=i

                box.addWidget(d)
                d.setValue(c.Value-1)
                d.setMaximum(100)
                d.setMinimum(0)
                d.valueChanged.connect(lambda:wrun(w))
                w.box.append(d)

        w.r=QtGui.QPushButton("close")
        box.addWidget(w.r)
        w.r.pressed.connect(lambda :runex(w))
        wrun(w)
        w.show()

    return w
项目:pypers    作者:frankosan    | 项目源码 | 文件源码
def process(self):

        ip_rings = open(self.input_rings)

        fileName, fileExt = os.path.splitext(self.input_rings)
        self.output_rings = '%s/%s.annot%s' % (self.output_dir,os.path.basename(fileName),fileExt)

        cmap = plt.get_cmap('hot')

        op_rings = open(self.output_rings,'w')

        for read in ip_rings:
            # Change the color palette
            m = re.search('#(\w{2})0{4}',read)
            if m:
                hexcode = mplcols.rgb2hex(cmap(int(m.group(1),16)))
                read = read.replace(m.group(0),hexcode)
            op_rings.write('%s\n' % read.rstrip())

        rings = {} # dict of lists to hold rings names


        ip_tree = open(self.input_tree,'ro')
        for line in ip_tree:

            level=line.split('.')

            if len(level) > 1:

                if level[0] not in rings:
                    rings[level[0]] = []

                if level[1] not in rings[level[0]]:
                    rings[level[0]].append(level[1])


        colors = ['b','g','r','w','y']
        i = 0
        j = 1

        for ring in rings:
            op_rings.write('%s\t%s\t%i.00:%s\n' % (ring,'annotation',j,ring))
            op_rings.write('%s\t%s\t%s\n' % (ring,'annotation_background_color',colors[i]))

            k = 1
            for level2 in rings[ring]:
                op_rings.write('%s.%s\t%s\t%i.%02i:%s\n' % (ring,level2,'annotation',j,k,level2))
                op_rings.write('%s.%s\t%s\t%s\n' % (ring,level2,'annotation_background_color',colors[i]))
                k += 1

            i += 1
            j += 1
            if i == len(colors):
                i = 0
项目:mizani    作者:has2k1    | 项目源码 | 文件源码
def hue_pal(h=.01, l=.6, s=.65, color_space='hls'):
    """
    Utility for making hue palettes for color schemes.

    Parameters
    ----------
    h : float
        first hue. In the [0, 1] range
    l : float
        lightness. In the [0, 1] range
    s : float
        saturation. In the [0, 1] range
    color_space : 'hls' | 'husl'
        Color space to use for the palette

    Returns
    -------
    out : function
        Continuous color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        equally spaced colors. Though the palette
        is continuous, since it is varies the hue it
        is good for categorical data. However if ``n``
        is large enough the colors show continuity.


    >>> hue_pal()(5)
    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']
    >>> hue_pal(color_space='husl')(5)
    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']
    """
    if not all([0 <= val <= 1 for val in (h, l, s)]):
        msg = ("hue_pal expects values to be between 0 and 1. "
               " I got h={}, l={}, s={}".format(h, l, s))
        raise ValueError(msg)

    if color_space not in ('hls', 'husl'):
        msg = "color_space should be one of ['hls', 'husl']"
        raise ValueError(msg)

    name = '{}_palette'.format(color_space)
    palette = globals()[name]

    def _hue_pal(n):
        colors = palette(n, h=h, l=l, s=s)
        return [mcolors.rgb2hex(c) for c in colors]

    return _hue_pal
项目:mizani    作者:has2k1    | 项目源码 | 文件源码
def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8,
                  light=.85, dark=.15, reverse=False):
    """
    Utility for creating continuous palette from the cubehelix system.

    This produces a colormap with linearly-decreasing (or increasing)
    brightness. That means that information will be preserved if printed to
    black and white or viewed by someone who is colorblind.

    Parameters
    ----------
    start : float, 0 <= start <= 3
        The hue at the start of the helix.
    rot : float
        Rotations around the hue wheel over the range of the palette.
    gamma : float 0 <= gamma
        Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
        colors.
    hue : float, 0 <= hue <= 1
        Saturation of the colors.
    dark : float 0 <= dark <= 1
        Intensity of the darkest color in the palette.
    light : float 0 <= light <= 1
        Intensity of the lightest color in the palette.
    reverse : bool
        If True, the palette will go from dark to light.

    Returns
    -------
    out : function
        Continuous color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        equally spaced colors.


    References
    ----------
    Green, D. A. (2011). "A colour scheme for the display of astronomical
    intensity images". Bulletin of the Astromical Society of India, Vol. 39,
    p. 289-295.


    >>> palette = cubehelix_pal()
    >>> palette(5)
    ['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e']
    """
    cdict = mpl._cm.cubehelix(gamma, start, rot, hue)
    cubehelix_cmap = mpl.colors.LinearSegmentedColormap('cubehelix', cdict)

    def cubehelix_palette(n):
        values = np.linspace(light, dark, n)
        return [mcolors.rgb2hex(cubehelix_cmap(x)) for x in values]

    return cubehelix_palette
项目:scikit-cmeans    作者:bm424    | 项目源码 | 文件源码
def contour(data, algorithm, axes=(0, 1), ax=None, resolution=200, threshold=0.5):
    """Scatter plot of data, with cluster contours overlaid.

    Parameters
    ----------
    data : :obj:`np.ndarray`
        (n_samples, n_features)
        The original data.
    algorithm : :obj:`skcmeans.algorithms.CMeans`
        A cluster algorithm that has fitted the data.
    axes : :obj:`tuple` of :obj:`int`, optional
        Which of the data dimensions should be used for the 2-d plot. Default:
        `(0, 1)`
    ax : :obj:`matplotlib.axes.Axes`, optional
        Plot on an existing axis. The default behaviour is to create a new plot.
    resolution : int, optional
        The number of coordinates in both the x- and y-directions to use for the
        contours. Higher values take slightly longer to compute but lead to
        smoother contours. Default: 200
    threshold : float, optional
        Between 0 and 1. The cutoff point for the contours. Below this value,
        contours will not be plotted. Default: 0.5

    """
    if ax is None:
        ax = plt.figure().add_subplot(111)
    x, y = data[:, axes[0]], data[:, axes[1]]
    x_margin = 0.1 * x.ptp()
    y_margin = 0.1 * y.ptp()
    ax.scatter(x, y, c='k', s=4, linewidth=0)
    xv, yv = np.array(np.meshgrid(
        np.linspace(x.min() - x_margin, x.max() + x_margin, resolution),
        np.linspace(y.min() - y_margin, y.max() + y_margin, resolution)))
    shape = (data.shape[-1], 1, 1)
    data_means = np.tile(np.zeros_like(xv), shape) + data.mean(axis=0).reshape(
        shape)
    data_means[axes[0]] = xv
    data_means[axes[1]] = yv
    estimated_memberships = algorithm.calculate_memberships(
        data_means.reshape(data_means.shape[0], -1).T
            ).reshape(resolution, resolution, algorithm.n_clusters)
    estimated_memberships[estimated_memberships<threshold] = 0
    order = algorithm.centers[:, -1].argsort(axis=-1)
    color = plt.cm.viridis(np.linspace(0, 1, algorithm.n_clusters))
    for j, c in zip(range(algorithm.n_clusters), color):
        ax.contour(xv, yv, estimated_memberships[:, :, order[j]],
                   colors=mc.rgb2hex(c))
    if ax is plt:
        plt.xlim(x.min() - x_margin, x.max() + x_margin)
        plt.ylim(y.min() - y_margin, y.max() + y_margin)
    else:
        ax.set_xlim(x.min() - x_margin, x.max() + x_margin)
        ax.set_ylim(y.min() - y_margin, y.max() + y_margin)