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


Python colorConverter.to_rgb函数代码示例

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


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

示例1: _compute_colors

    def _compute_colors(self, array_x, array_y):

        # on calcule le maximum absolu de toutes valeurs pour former un carré
        abs_maximum = max([max(map(abs,array_x)), max(map(abs,array_y))])
        diagonal_length = norm(array([abs_maximum, abs_maximum])) # longueur de la projection
        diag = array([diagonal_length, diagonal_length])
        anti_diag = array([-diagonal_length, diagonal_length])

        # on instancie le gradient de couleur sur le modèle de couleur du centre
        linear_normalizer = mpl.colors.Normalize(vmin=-abs_maximum, vmax=abs_maximum)
        log_normalizer = mpl.colors.SymLogNorm(abs_maximum/5, vmin=-abs_maximum, vmax=abs_maximum)
        r_to_b_gradient = cm.ScalarMappable(norm=linear_normalizer, cmap=redtoblue)

        # on calcule le produit scalaire de chaque valeur avec la diagonale
        # ensuite, on calcule la couleur à partir de la valeur de la projection sur la diagonale
        hex_color_values = []
        for i, x in enumerate(array_x):
            # on calcule les produits scalaire du point avec la diagonale et l'antidiagonale
            scal_p_diag = dot(array([array_x[i], array_y[i]]), diag) / diagonal_length
            scal_p_antidiag = dot(array([array_x[i], array_y[i]]), anti_diag) / diagonal_length

            #on calcule le gradient de couleur sur la diagonale
            on_diag_color = colorConverter.to_rgb(r_to_b_gradient.to_rgba(scal_p_diag))
            # puis on utilise cette couleur (en rgb) pour définir un gradient, dont la valeur sera estimée
            # sur l'antidiagonale
            on_diag_gradient = make_white_gradient(on_diag_color, log_normalizer)
            final_color = on_diag_gradient.to_rgba(scal_p_antidiag)

            #on traduit en HEX
            hex_color_values.append(rgb2hex(colorConverter.to_rgb(final_color)))

        return hex_color_values, abs_maximum
开发者ID:ThomasPoncet,项目名称:Ocre,代码行数:32,代码来源:correlations.py

示例2: add_bars

    def add_bars(self, colorup='g', colordown='r', alpha=0.5, width=1):
        r,g,b = colorConverter.to_rgb(colorup)
        colorup = r,g,b,alpha
        r,g,b = colorConverter.to_rgb(colordown)
        colordown = r,g,b,alpha
        colord = {True: colorup, False: colordown}
        colors = [colord[open<close] for open, close in zip(self.opens, self.closes)]

        delta = width/2.0
        bars = [((x-delta, 0), (x-delta, y), (x+delta, y), (x+delta, 0)) 
            for x, y in zip(self.dates, self.volumes)]

        barCollection = PolyCollection(bars, facecolors = colors)

        #self.ax.step(self.dates, self.volumes)
        #self.ax.add_collection(barCollection)
        #self.ax.bar(self.dates, self.volumes)
        #self.ax.plot(self.dates, self.volumes)
        self.ax.fill_between(self.dates, self.volumes, alpha=0.5)

        xmin, xmax = self.ax.get_xlim()
        ys = [y for x, y in zip(self.dates, self.volumes) if xmin<=x<=xmax]
        if ys:
            self.ax.set_ylim([0, max(ys)*10])

        for tick in self.ax.get_yticklabels():
            tick.set_visible(False)
开发者ID:AgeanSea,项目名称:quantdigger,代码行数:27,代码来源:matplotlibwidget.py

示例3: plot

    def plot(self, widget, width=0.6,
             colorup='r', colordown='g', lc='k', alpha=1):
        """docstring for plot"""
        delta = self.width/2.
        barVerts = [((i-delta, open),
                     (i-delta, close),
                     (i+delta, close),
                     (i+delta, open))
                    for i, open, close in zip(xrange(len(self.data)),
                                              self.data.open,
                                              self.data.close)
                    if open != -1 and close != -1]
        rangeSegments = [((i, low), (i, high))
                         for i, low, high in zip(
                                 xrange(len(self.data)),
                                 self.data.low,
                                 self.data.high)
                         if low != -1]
        r, g, b = colorConverter.to_rgb(self.colorup)
        colorup = r, g, b, self.alpha
        r, g, b = colorConverter.to_rgb(self.colordown)
        colordown = r, g, b, self.alpha
        colord = {
            True: colorup,
            False: colordown,
        }
        colors = [colord[open < close]
                  for open, close in zip(self.data.open, self.data.close)
                  if open != -1 and close != -1]
        assert(len(barVerts) == len(rangeSegments))
        useAA = 0,  # use tuple here
        lw = 0.5,   # and here
        r, g, b = colorConverter.to_rgb(self.lc)
        linecolor = r, g, b, self.alpha
        lineCollection = LineCollection(rangeSegments,
                                        colors=(linecolor,),
                                        linewidths=lw,
                                        antialiaseds=useAA,
                                        zorder=0)

        barCollection = PolyCollection(barVerts,
                                       facecolors=colors,
                                       edgecolors=colors,
                                       antialiaseds=useAA,
                                       linewidths=lw,
                                       zorder=1)
        #minx, maxx = 0, len(rangeSegments)
        #miny = min([low for low in self.data.low if low !=-1])
        #maxy = max([high for high in self.data.high if high != -1])
        #corners = (minx, miny), (maxx, maxy)
        #ax.update_datalim(corners)
        widget.autoscale_view()
        # add these last
        widget.add_collection(barCollection)
        widget.add_collection(lineCollection)

        #ax.plot(self.data.close, color = 'y')
        #lineCollection, barCollection = None, None
        return lineCollection, barCollection
开发者ID:AgeanSea,项目名称:quantdigger,代码行数:59,代码来源:mplots.py

示例4: plot

    def plot(self, widget, data, width=0.6,
             colorup='r', colordown='g', lc='k', alpha=1):

        if self.lineCollection:
            self.lineCollection.remove()
        if self.barCollection:
            self.barCollection.remove()

        self.set_yrange(data.low.values, data.high.values)
        self.data = data
        """docstring for plot"""
        delta = self.width / 2.
        barVerts = [((i - delta, open),
                     (i - delta, close),
                     (i + delta, close),
                     (i + delta, open))
                    for i, open, close in zip(range(len(self.data)),
                                              self.data.open,
                                              self.data.close)
                    if open != -1 and close != -1]
        rangeSegments = [((i, low), (i, high))
                         for i, low, high in zip(range(len(self.data)),
                                                 self.data.low,
                                                 self.data.high)
                         if low != -1]
        r, g, b = colorConverter.to_rgb(self.colorup)
        colorup = r, g, b, self.alpha
        r, g, b = colorConverter.to_rgb(self.colordown)
        colordown = r, g, b, self.alpha
        colord = {
            True: colorup,
            False: colordown,
        }
        colors = [colord[open < close]
                  for open, close in zip(self.data.open, self.data.close)
                  if open != -1 and close != -1]
        assert(len(barVerts) == len(rangeSegments))
        useAA = 0,  # use tuple here
        lw = 0.5,   # and here
        r, g, b = colorConverter.to_rgb(self.lc)
        linecolor = r, g, b, self.alpha
        self.lineCollection = LineCollection(rangeSegments,
                                             colors=(linecolor,),
                                             linewidths=lw,
                                             antialiaseds=useAA,
                                             zorder=0)

        self.barCollection = PolyCollection(barVerts,
                                            facecolors=colors,
                                            edgecolors=colors,
                                            antialiaseds=useAA,
                                            linewidths=lw,
                                            zorder=1)
        widget.autoscale_view()
        # add these last
        widget.add_collection(self.barCollection)
        widget.add_collection(self.lineCollection)
        return self.lineCollection, self.barCollection
开发者ID:QuantFans,项目名称:quantdigger,代码行数:58,代码来源:mplots.py

示例5: create_colormap

def create_colormap(col1, col2):
    c1 = colorConverter.to_rgb(col1)
    c2 = colorConverter.to_rgb(col2)
    
    cdict = {
        'red': ((0.,c1[0], c1[0]),(1.,c2[0], c2[0])),
        'green': ((0.,c1[1], c1[1]),(1.,c2[1], c2[1])),
        'blue': ((0.,c1[2], c1[2]),(1.,c2[2], c2[2]))
    }
    return LinearSegmentedColormap('custom', cdict, 256)
开发者ID:CnatureS,项目名称:fluff,代码行数:10,代码来源:color.py

示例6: _to_rgb

def _to_rgb(c):
    """
    Convert color *c* to a numpy array of *RGB* handling exeption
    Parameters
    ----------
    c: Matplotlib color
        same as *color* in *colorAlpha_to_rgb*
    output
    ------
    rgbs: list of numpy array
        list of c converted to *RGB* array
    """

    if(getattr(c, '__iter__', False) == False):  #if1: if c is a single element (number of string)
        rgbs = [np.array(cC.to_rgb(c)),]  #list with 1 RGB numpy array

    else:  #if1, else: if is more that one element

        try:   #try1: check if c is numberic or not
            np.array(c) + 1

        except (TypeError, ValueError):  #try1: if not numerics is not (only) RGB or RGBA colors
            #convert the list/tuble/array of colors into a list of numpy arrays of RGB
            rgbs = [np.array( cC.to_rgb(i)) for i in c]

        except Exception as e:  #try1: if any other exception raised
            print("Unexpected error: {}".format(e))
            raise e #raise it

        else:  #try1: if the colors are all numberics

            arrc = np.array(c)  #convert c to a numpy array
            arrcsh = arrc.shape  #shape of the array 

            if len(arrcsh)==1:  #if2: if 1D array given 
                if(arrcsh[0]==3 or arrcsh[0]==4):  #if3: if RGB or RBGA
                    rgbs = [np.array(cC.to_rgb(c)),]  #list with 1 RGB numpy array
                else:   #if3, else: the color cannot be RBG or RGBA
                    raise ValueError('Invalid rgb arg "{}"'.format(c))
                #end if3
            elif len(arrcsh)==2:  #if2, else: if 2D array
                if(arrcsh[1]==3 or arrcsh[1]==4):  #if4: if RGB or RBGA
                    rgbs = [np.array(cC.to_rgb(i)) for i in c]  #list with RGB numpy array
                else:   #if4, else: the color cannot be RBG or RGBA
                    raise ValueError('Invalid list or array of rgb')
                #end if4
            else:  #if2, else: if more dimention
                raise ValueError('The rgb or rgba values must be contained in a 1D or 2D list or array')
            #end if2
        #end try1
    #end if1

    return rgbs
开发者ID:pcubillos,项目名称:mimic_alpha,代码行数:53,代码来源:mimic_alpha.py

示例7: volume_overlay

def volume_overlay(ax, opens, closes, volumes, colorup="k", colordown="r", width=4, alpha=1.0):
    """Add a volume overlay to the current axes.  The opens and closes
    are used to determine the color of the bar.  -1 is missing.  If a
    value is missing on one it must be missing on all

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    opens : sequence
        a sequence of opens
    closes : sequence
        a sequence of closes
    volumes : sequence
        a sequence of volumes
    width : int
        the bar width in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
        the color of the lines where close <  open
    alpha : float
        bar transparency

    Returns
    -------
    ret : `barCollection`
        The `barrCollection` added to the axes

    """

    r, g, b = colorConverter.to_rgb(colorup)
    colorup = r, g, b, alpha
    r, g, b = colorConverter.to_rgb(colordown)
    colordown = r, g, b, alpha
    colord = {True: colorup, False: colordown}
    colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1]

    delta = width / 2.0
    bars = [((i - delta, 0), (i - delta, v), (i + delta, v), (i + delta, 0)) for i, v in enumerate(volumes) if v != -1]

    barCollection = PolyCollection(
        bars, facecolors=colors, edgecolors=((0, 0, 0, 1),), antialiaseds=(0,), linewidths=(0.5,)
    )

    ax.add_collection(barCollection)
    corners = (0, 0), (len(bars), max(volumes))
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    return barCollection
开发者ID:JamesPinkard,项目名称:matplotlib,代码行数:52,代码来源:finance.py

示例8: plot_hmm

def plot_hmm(means_, transmat, covars, initProbs, axes=None, clr=None, transition_arrows=True):
    if axes != None:
        axes(axes)
        # f, axes = subplots(2)#,sharex=True, sharey=True)
    #     sca(axes[0])
    global annotations
    annotations = []
    global means
    means = []
    colors = clr
    # color_map = colors #[colorConverter.to_rgb(colors[i]) for i in range(len(means_))]
    for i, mean in enumerate(means_):
        #         print_n_flush( "MEAN:", tuple(mean))
        means.append(scatter(*tuple(mean), color=colorConverter.to_rgb(colors[i]), picker=10, label="State%i" % i))
        annotate(s="%d" % i, xy=mean, xytext=(-10, -10), xycoords="data", textcoords="offset points",
                 alpha=1, bbox=dict(boxstyle='round,pad=0.2', fc=colorConverter.to_rgb(colors[i]), alpha=0.3))
        #         gca().add_patch(Ellipse(xy = means_[i], width = np.diag(covars[i])[0], height = np.diag(covars[i])[1],
        #                         alpha=.15, color=colorConverter.to_rgb(colors[i])))
        plot_cov_ellipse(covars[i], mean, alpha=.15, color=colorConverter.to_rgb(colors[i]))
        x0, y0 = mean
        prob_string = "P(t0)=%f" % initProbs[i]
        for j, p in enumerate(transmat[i]):
            xdif = 10
            ydif = 5
            s = "P(%d->%d)=%f" % (i, j, p)
            #             print_n_flush( "State%d: %s" % (i, s))
            prob_string = "%s\n%s" % (prob_string, s)
            if transition_arrows:
                if i != j:
                    x1, y1 = means_[j]
                    # if transmat[i][j] is too low, we get an underflow here
                    #                 q = quiver([x0], [y0], [x1-x0], [y1-y0], alpha = 10000 * (transmat[i][j]**2),
                    alpha = 10 ** -300
                    if p > 10 ** -100:
                        alpha = (100 * p) ** 2
                    q = quiver([x0], [y0], [x1 - x0], [y1 - y0], alpha=1 / log(alpha),
                               scale_units='xy', angles='xy', scale=1, width=0.005, label="P(%d->%d)=%f" % (i, j, p))
                #         legend()

        annotations.append(annotate(s=prob_string, xy=mean, xytext=(0, 10), xycoords="data", textcoords="offset points",
                                    alpha=1,
                                    bbox=dict(boxstyle='round,pad=0.2', fc=colorConverter.to_rgb(colors[i]), alpha=0.3),
                                    picker=True,
                                    visible=False))


    #         print_n_flush( "State%i is %s" % (i, colors[i]))
    cid = gcf().canvas.mpl_connect('pick_event', on_pick)
开发者ID:keryil,项目名称:leaparticulatorqt,代码行数:48,代码来源:StreamlinedDataAnalysisGhmm.py

示例9: gradient

def gradient(cmin, cmax):
    if isinstance(cmin, str):
        cmin = colorConverter.to_rgb(cmin)
    if isinstance(cmax, str):
        cmax = colorConverter.to_rgb(cmax)

    cdict = {
        'red':   [(0, 0,       cmin[0]),
                  (1, cmax[0], 1)],
        'green': [(0, 0,       cmin[1]),
                  (1, cmax[1], 1)],
        'blue':  [(0, 0,       cmin[2]),
                  (1, cmax[2], 1)]
        }

    return mpl.colors.LinearSegmentedColormap('cmap', cdict, N=1000)
开发者ID:frsong,项目名称:pyrl,代码行数:16,代码来源:figtools.py

示例10: add_aliasing_edges

def add_aliasing_edges(G, only_states, belief_mdp, pomdp):  # @UnusedVariable
    for s1 in only_states:
        for s2 in only_states:
            if s1 == s2:
                continue

            obs1 = pomdp.get_observations_dist_given_belief(s1)
            obs2 = pomdp.get_observations_dist_given_belief(s2)

            can_distinguish = len(set(obs1) & set(obs2)) == 0

#             if not len(obs1) == 0 or not len(obs2) == 0:
#                 print('not deterministic, %s , %s , %s ,
#  %s ' % (s1, obs1, s2, obs2))
#                 continue

            if not can_distinguish:
                # aliasing!
                G.add_edge(s1, s2)
                G.edge[s1][s2]['type'] = 'aliasing'
                G.edge[s1][s2]['edge_color'] = colorConverter.to_rgb('y')
                G.edge[s1][s2]['edge_style'] = 'dotted'



    return G
开发者ID:AndreaCensi,项目名称:tmdp,代码行数:26,代码来源:reports.py

示例11: from_list

    def from_list(name, colors, N=256, gamma=1.0):
        """
        Make a linear segmented colormap with *name* from a sequence
        of *colors* which evenly transitions from colors[0] at val=0
        to colors[-1] at val=1.  *N* is the number of rgb quantization
        levels.
        Alternatively, a list of (value, color) tuples can be given
        to divide the range unevenly.
        """

        if not cbook.iterable(colors):
            raise ValueError('colors must be iterable')

        if cbook.iterable(colors[0]) and len(colors[0]) == 2 and \
                not cbook.is_string_like(colors[0]):
            # List of value, color pairs
            vals, colors = zip(*colors)
        else:
            vals = np.linspace(0., 1., len(colors))

        cdict = dict(red=[], green=[], blue=[])
        for val, color in zip(vals, colors):
            r,g,b = colorConverter.to_rgb(color)
            cdict['red'].append((val, r, r))
            cdict['green'].append((val, g, g))
            cdict['blue'].append((val, b, b))

        return MixedAlphaColormap(name, cdict, N, gamma)
开发者ID:cindeem,项目名称:xipy,代码行数:28,代码来源:color_mapping.py

示例12: color_to_hex

def color_to_hex(color):
    """Convert matplotlib color code to hex color code"""
    if color is None or colorConverter.to_rgba(color)[3] == 0:
        return 'none'
    else:
        rgb = colorConverter.to_rgb(color)
        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
开发者ID:Peque,项目名称:vispy,代码行数:7,代码来源:mplutils.py

示例13: pastel

def pastel(colour, weight=2.4):
    '''
    Convert colour into a nice pastel shade
    '''

    rgb = asarray(colorConverter.to_rgb(colour))
    # scale colour
    maxc = max(rgb)
    if maxc < 1.0 and maxc > 0:
        # scale colour
        scale = 1.0 / maxc
        rgb = rgb * scale
    # now decrease saturation
    total = sum(rgb)
    slack = 0
    for x in rgb:
        slack += 1.0 - x

    # want to increase weight from total to weight
    # pick x s.t.  slack * x == weight - total
    # x = (weight - total) / slack
    x = (weight - total) / slack

    rgb = [c + (x * (1.0-c)) for c in rgb]

    return rgb
开发者ID:pombredanne,项目名称:Tapper,代码行数:26,代码来源:xen_weekly.py

示例14: __init__

 def __init__(self, label=None, marker="o", markersize=10,
              color="blue", saturation=1, opaqcity=1, zorder=0):
     self.label = label
     self.marker = marker
     self.markersize = markersize
     self.color_rgb = colorConverter.to_rgb(color)
     self.saturation = saturation
     self.opaqcity = opaqcity
     self.zorder = zorder
开发者ID:eike-welk,项目名称:clair,代码行数:9,代码来源:diagram.py

示例15: get_selection_box_colour

def get_selection_box_colour(series):
    """
    Returns a colour (as an RGB tuple) that will be visible against the 
    background of the subplot.
    """  
    subplot = series.get_subplot()
    bkgd_col = colorConverter.to_rgb(subplot.get_mpl_axes().get_axis_bgcolor())
    
    return tuple([1.0 - c for c in bkgd_col])
开发者ID:drjvnv,项目名称:avoplot,代码行数:9,代码来源:data_selection.py


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