• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python colorConverter.to_rgb函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: _register_cmap_transparent

def _register_cmap_transparent(name, color):
    """Create a color map from a given color to transparent."""
    from matplotlib.colors import colorConverter, LinearSegmentedColormap
    red, green, blue = colorConverter.to_rgb(color)
    cdict = {'red': ((0, red, red), (1, red, red)),
             'green': ((0, green, green), (1, green, green)),
             'blue': ((0, blue, blue), (1, blue, blue)),
             'alpha': ((0, 0, 0), (1, 1, 1))}
    cmap = LinearSegmentedColormap(name, cdict)
    _plt.cm.register_cmap(cmap=cmap)
开发者ID:sfstoolbox,项目名称:sfs-python,代码行数:10,代码来源:plot2d.py


示例17: colorAlpha_to_rgb

def colorAlpha_to_rgb(colors, alpha, bg='w'):
    """
    Given a Matplotlib color and a value of alpha, it returns 
    a RGB color which mimic the RGBA colors on the given background

    Parameters
    ----------
    colors: Matplotlib color (documentation from matplotlib.colors.colorConverter.to_rgb), 
        list/tuple/numpy array of colors
        Can be an *RGB* or *RGBA* sequence or a string in any of
        several forms:
        1) a letter from the set 'rgbcmykw'
        2) a hex color string, like '#00FFFF'
        3) a standard name, like 'aqua'
        4) a float, like '0.4', indicating gray on a 0-1 scale
        if *color* is *RGBA*, the *A* will simply be discarded.
    alpha: float [0,1] or list/tuple/numpy array with len(colors) elements
        Value of alpha to mimic. 
    bg: Matplotlib color (optional, default='w')
        Color of the background. Can be of any type shown in *color*

    output
    ------
    rgb: *RGB* color 

    example
    -------

    import mimic_alpha as ma

    print(ma.colorAlpha_to_rgb('r', 0.5))
    >>> [array([ 1. ,  0.5,  0.5])]
    print(ma.colorAlpha_to_rgb(['r', 'g'], 0.5)) 
    >>> [array([ 1. ,  0.5,  0.5]), array([ 0.5 ,  0.75,  0.5 ])]
    print(ma.colorAlpha_to_rgb(['r', 'g'], [0.5, 0.3])) 
    >>> [array([ 1. ,  0.5,  0.5]), array([ 0.7 ,  0.85,  0.7 ])]
    print(ma.colorAlpha_to_rgb(['r', [1,0,0]], 0.5)) 
    >>> [array([ 1. ,  0.5,  0.5]), array([ 1. ,  0.5,  0.5])]
    print( ma.colorAlpha_to_rgb([[0,1,1], [1,0,0]], 0.5) ) 
    >>> [array([ 0.5,  1. ,  1. ]), array([ 1. ,  0.5,  0.5])]
    print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5)) 
    >>> [array([ 0.5,  1. ,  1. ]), array([ 1. ,  0.5,  0.5])]
    print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5, bg='0.5')) 
    >>> [array([ 0.25,  0.75,  0.75]), array([ 0.75,  0.25,  0.25])]
    """

    colors = _to_rgb(colors)  #convert the color and save in a list of np arrays
    bg = np.array(cC.to_rgb(bg))   #convert the background

    #check if alpha has 1 or len(colors) elements and return a list of len(color) alpha 
    alpha = _check_alpha(alpha, len(colors))  
    #interpolate between background and color 
    rgb = [(1.-a) * bg + a*c for c,a in zip(colors, alpha)]

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


示例18: export_color

def export_color(color):
    """Convert matplotlib color code to hex color or RGBA color"""
    if color is None or colorConverter.to_rgba(color)[3] == 0:
        return 'none'
    elif colorConverter.to_rgba(color)[3] == 1:
        rgb = colorConverter.to_rgb(color)
        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
    else:
        c = colorConverter.to_rgba(color)
        return "rgba(" + ", ".join(str(int(np.round(val * 255)))
                                        for val in c[:3])+', '+str(c[3])+")"
开发者ID:codybushnell,项目名称:plotly.py,代码行数:11,代码来源:utils.py


示例19: plot_hit_matrix

def plot_hit_matrix(hit_matrix, k, m, fold, kmers, virus_family, sequence_type, project_path):
    background_colors = {
        'white' :   np.array([255,255,255]).reshape(1,3)/255.,
        'black' :   np.array([0,0,0]).reshape(1,3)/255.,
         'grey' :   np.array([38,38,38]).reshape(1,3)/255.,
     'darkgrey' :   np.array([18,18,18]).reshape(1,3)/255.,
     'offwhite' :   np.array([235,235,235]).reshape(1,3)/255.,
    }

    kmer_colors = ['red','green','blue','purple','cyan','orange','magenta','black','hotpink']
    (num_proteins,C,ig) = hit_matrix.shape
    C = C-1
    V = min([9,len(kmers)])
    data = np.zeros((num_proteins,C,3),dtype='float')
    for i in range(V):
        data += hit_matrix[:,1:,i:i+1] * np.array(list(convert.to_rgb(kmer_colors[i]))) 
    
    idx = (hit_matrix[:,0,0]==1).nonzero()[0]
    data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1) * background_colors['white']
    idx = (hit_matrix[:,0,0]==2).nonzero()[0]
    data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1) * background_colors['offwhite']
#    idx = (hit_matrix[:,0,0]==3).nonzero()[0]
#    data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1)*color_scheme['white']

    fig = plot.figure()
    im = fig.add_subplot(111)
    im.set_position([0.03,0.07,0.80,0.88])
    im.imshow(data,aspect='auto',interpolation='nearest')
    im.axis([0,hit_matrix.shape[1]-1,0,hit_matrix.shape[0]])
    im.set_xticks([0,hit_matrix.shape[1]-1])
    im.set_xticklabels((0,1))
    im.set_xlabel('Relative location')
    y_labels = ('Plant','Animal')
    y_label_loc = []
    for c in np.unique(hit_matrix[:,0,0]):
        y_label_loc.append(int(np.mean((hit_matrix[:,0,0]==c).nonzero()[0])))
    im.set_yticks(y_label_loc)
    im.set_yticklabels(y_labels, rotation=90)
    for line in im.get_yticklines():
        line.set_markersize(0)

    im.set_title('k = %d, m = %d' % (k,m))

    # a figtext bbox for legend
    kmer_locs = np.linspace(0.5+V/2*0.04,0.5-V/2*0.04,V)
    for kidx in range(V):
        kmer = kmers[kidx]
        try:
            plot.figtext(0.84, kmer_locs[kidx], kmer, fontsize=9, color=kmer_colors[kidx], horizontalalignment='left', verticalalignment='center')
        except IndexError:
            pdb.set_trace()

    fname = project_path + 'fig/%s_%s_kmer_visualization_%d_%d_%d.pdf' % (virus_family, sequence_type, k, m, fold)
    fig.savefig(fname,dpi=(300),format='pdf')
开发者ID:mikedewar,项目名称:picorna,代码行数:54,代码来源:visualize_kmers.py


示例20: show

  def show(self):
    self.fr1=Frame(self.fig.fr_curves, padx=3, pady=3)
    self.fr1.pack(side=TOP)
    l=Label(self.fr1, text="%s(%s)"%(self.y, self.x)); l.pack(side=LEFT)
    Button(self.fr1, text="Del", command=self.destroy).pack(side=LEFT)
#    self.line, = self.fig.ax.plot(self.sode[self.x], self.sode[self.y],'.-',label="%s(%s)"%(self.y, self.x))
    self.line, = self.fig.ax.plot(self.sode[self.x], self.sode[self.y],label="%s(%s)"%(self.y, self.x))
    self.fr1["bg"] = rgb2hex(colorConverter.to_rgb(self.line.get_color()))
#    self.ax.legend()
#    self.ax.figure.canvas.draw()
    self.fig.cnvs.update_idletasks()
    self.fig.cnvs["scrollregion"]=self.fig.cnvs.bbox(ALL)
开发者ID:pmamonov,项目名称:pytrax,代码行数:12,代码来源:trax.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python colorConverter.to_rgba函数代码示例发布时间:2022-05-27
下一篇:
Python colors.Normalize类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap