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


Python colors.to_rgba函数代码示例

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


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

示例1: on_combobox_lineprops_changed

    def on_combobox_lineprops_changed(self, item):
        "update the widgets from the active line"
        if not self._inited:
            return
        self._updateson = False
        line = self.get_active_line()

        ls = line.get_linestyle()
        if ls is None:
            ls = "None"
        self.cbox_linestyles.set_active(self.linestyled[ls])

        marker = line.get_marker()
        if marker is None:
            marker = "None"
        self.cbox_markers.set_active(self.markerd[marker])

        rgba = mcolors.to_rgba(line.get_color())
        color = gtk.gdk.Color(*[int(val * 65535) for val in rgba[:3]])
        button = self.wtree.get_widget("colorbutton_linestyle")
        button.set_color(color)

        rgba = mcolors.to_rgba(line.get_markerfacecolor())
        color = gtk.gdk.Color(*[int(val * 65535) for val in rgba[:3]])
        button = self.wtree.get_widget("colorbutton_markerface")
        button.set_color(color)
        self._updateson = True
开发者ID:QuLogic,项目名称:matplotlib,代码行数:27,代码来源:backend_gtk.py

示例2: 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

    """

    colorup = mcolors.to_rgba(colorup, alpha)
    colordown = mcolors.to_rgba(colordown, 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.
    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:NigelKB,项目名称:matplotlib,代码行数:59,代码来源:finance.py

示例3: __init__

    def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow',
                 alpha=1.0):
        self.fontsize = fontsize
        self.labelcolor = labelcolor
        self.bgcolor = bgcolor
        self.alpha = alpha

        self.labelcolor_rgb = colors.to_rgba(labelcolor)[:3]
        self.bgcolor_rgb = colors.to_rgba(bgcolor)[:3]
开发者ID:QuLogic,项目名称:matplotlib,代码行数:9,代码来源:menu.py

示例4: test_conversions

def test_conversions():
    # to_rgba_array("none") returns a (0, 4) array.
    assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
    # alpha is properly set.
    assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5))
    # builtin round differs between py2 and py3.
    assert_equal(mcolors.to_hex((.7, .7, .7)), "#b2b2b2")
    # hex roundtrip.
    hex_color = "#1234abcd"
    assert_equal(mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True),
                 hex_color)
开发者ID:717524640,项目名称:matplotlib,代码行数:11,代码来源:test_colors.py

示例5: test_legend_edgecolor

def test_legend_edgecolor():
    get_func = 'get_edgecolor'
    rcparam = 'legend.edgecolor'
    test_values = [({rcparam: 'r'},
                    mcolors.to_rgba('r')),
                   ({rcparam: 'inherit', 'axes.edgecolor': 'r'},
                    mcolors.to_rgba('r')),
                   ({rcparam: 'g', 'axes.facecolor': 'r'},
                    mcolors.to_rgba('g'))]
    for rc_dict, target in test_values:
        yield _legend_rcparam_helper, rc_dict, target, get_func
开发者ID:Jajauma,项目名称:dotfiles,代码行数:11,代码来源:test_rcparams.py

示例6: test_failed_conversions

def test_failed_conversions():
    with pytest.raises(ValueError):
        mcolors.to_rgba('5')
    with pytest.raises(ValueError):
        mcolors.to_rgba('-1')
    with pytest.raises(ValueError):
        mcolors.to_rgba('nan')
    with pytest.raises(ValueError):
        mcolors.to_rgba('unknown_color')
    with pytest.raises(ValueError):
        # Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
        mcolors.to_rgba(0.4)
开发者ID:QuLogic,项目名称:matplotlib,代码行数:12,代码来源:test_colors.py

示例7: convert_colors_string_to_tuple

def convert_colors_string_to_tuple(cols):
    for col in cols:
        if isinstance(col, str):
            if col in BASE_COLORS:
                yield to_rgba(BASE_COLORS[col])
            elif col in CSS4_COLORS:
                yield to_rgba(CSS4_COLORS[col])
            else:
                raise ValueError("Color specifier {} "
                                 "not recognized".format(col))
        else:
            yield to_rgba(col)
开发者ID:jcmgray,项目名称:xyzpy,代码行数:12,代码来源:color.py

示例8: __init__

 def __init__(self, offset=(2, -2),
              shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
     """
     Parameters
     ----------
     offset : pair of floats
         The offset to apply to the path, in points.
     shadow_color : color
         The shadow color. Default is black.
         A value of ``None`` takes the original artist's color
         with a scale factor of `rho`.
     alpha : float
         The alpha transparency of the created shadow patch.
         Default is 0.3.
     rho : float
         A scale factor to apply to the rgbFace color if `shadow_rgbFace`
         is ``None``. Default is 0.3.
     **kwargs
         Extra keywords are stored and passed through to
         :meth:`AbstractPathEffect._update_gc`.
     """
     super().__init__(offset)
     if shadow_color is None:
         self._shadow_color = shadow_color
     else:
         self._shadow_color = mcolors.to_rgba(shadow_color)
     self._alpha = alpha
     self._rho = rho
     #: The dictionary of keywords to update the graphics collection with.
     self._gc = kwargs
开发者ID:anntzer,项目名称:matplotlib,代码行数:30,代码来源:patheffects.py

示例9: make_image

 def make_image(self, renderer, magnification=1.0, unsampled=False):
     if self._A is None:
         raise RuntimeError('You must first set the image array')
     if unsampled:
         raise ValueError('unsampled not supported on PColorImage')
     fc = self.axes.patch.get_facecolor()
     bg = mcolors.to_rgba(fc, 0)
     bg = (np.array(bg)*255).astype(np.uint8)
     l, b, r, t = self.axes.bbox.extents
     width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
     height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
     # The extra cast-to-int is only needed for python2
     width = int(np.round(width * magnification))
     height = int(np.round(height * magnification))
     if self._rgbacache is None:
         A = self.to_rgba(self._A, bytes=True)
         self._rgbacache = A
         if self._A.ndim == 2:
             self.is_grayscale = self.cmap.is_gray()
     else:
         A = self._rgbacache
     vl = self.axes.viewLim
     im = _image.pcolor2(self._Ax, self._Ay, A,
                         height,
                         width,
                         (vl.x0, vl.x1, vl.y0, vl.y1),
                         bg)
     return im, l, b, IdentityTransform()
开发者ID:Perados,项目名称:matplotlib,代码行数:28,代码来源:image.py

示例10: get_color_range

def get_color_range(n):
    colors = mcolors.TABLEAU_COLORS
    by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                    for name, color in colors.items())
    sorted_names = [name for hsv, name in by_hsv]
    delta = int(len(sorted_names)/n)
    return sorted_names[::delta]
开发者ID:NazBen,项目名称:impact-of-dependence,代码行数:7,代码来源:plots.py

示例11: draw_3d

def draw_3d(verts, ymin, ymax, line_at_zero=True, colors=True):
    '''Given verts as a list of plots, each plot being a list
       of (x, y) vertices, generate a 3-d figure where each plot
       is shown as a translucent polygon.
       If line_at_zero, a line will be drawn through the zero point
       of each plot, otherwise the baseline will be at the bottom of
       the plot regardless of where the zero line is.
    '''
    # add_collection3d() wants a collection of closed polygons;
    # each polygon needs a base and won't generate it automatically.
    # So for each subplot, add a base at ymin.
    if line_at_zero:
        zeroline = 0
    else:
        zeroline = ymin
    for p in verts:
        p.insert(0, (p[0][0], zeroline))
        p.append((p[-1][0], zeroline))

    if colors:
        # All the matplotlib color sampling examples I can find,
        # like cm.rainbow/linspace, make adjacent colors similar,
        # the exact opposite of what most people would want.
        # So cycle hue manually.
        hue = 0
        huejump = .27
        facecolors = []
        edgecolors = []
        for v in verts:
            hue = (hue + huejump) % 1
            c = mcolors.hsv_to_rgb([hue, 1, 1])
                                    # random.uniform(.8, 1),
                                    # random.uniform(.7, 1)])
            edgecolors.append(c)
            # Make the facecolor translucent:
            facecolors.append(mcolors.to_rgba(c, alpha=.7))
    else:
        facecolors = (1, 1, 1, .8)
        edgecolors = (0, 0, 1, 1)

    poly = PolyCollection(verts,
                          facecolors=facecolors, edgecolors=edgecolors)

    zs = range(len(data))
    # zs = range(len(data)-1, -1, -1)

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1, projection='3d')

    plt.tight_layout(pad=2.0, w_pad=10.0, h_pad=3.0)

    ax.add_collection3d(poly, zs=zs, zdir='y')

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    ax.set_xlim3d(0, len(data[1]))
    ax.set_ylim3d(-1, len(data))
    ax.set_zlim3d(ymin, ymax)
开发者ID:akkana,项目名称:scripts,代码行数:60,代码来源:multiplot3d.py

示例12: test_conversions

def test_conversions():
    # to_rgba_array("none") returns a (0, 4) array.
    assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
    # a list of grayscale levels, not a single color.
    assert_array_equal(
        mcolors.to_rgba_array([".2", ".5", ".8"]),
        np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]]))
    # alpha is properly set.
    assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5)
    assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5)
    # builtin round differs between py2 and py3.
    assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2"
    # hex roundtrip.
    hex_color = "#1234abcd"
    assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \
        hex_color
开发者ID:dstansby,项目名称:matplotlib,代码行数:16,代码来源:test_colors.py

示例13: print_jpg

        def print_jpg(self, filename_or_obj, *args, **kwargs):
            """
            Supported kwargs:

            *quality*: The image quality, on a scale from 1 (worst) to
                95 (best). The default is 95, if not given in the
                matplotlibrc file in the savefig.jpeg_quality parameter.
                Values above 95 should be avoided; 100 completely
                disables the JPEG quantization stage.

            *optimize*: If present, indicates that the encoder should
                make an extra pass over the image in order to select
                optimal encoder settings.

            *progressive*: If present, indicates that this image
                should be stored as a progressive JPEG file.
            """
            buf, size = self.print_to_buffer()
            if kwargs.pop("dryrun", False):
                return
            # The image is "pasted" onto a white background image to safely
            # handle any transparency
            image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
            rgba = mcolors.to_rgba(rcParams.get('savefig.facecolor', 'white'))
            color = tuple([int(x * 255.0) for x in rgba[:3]])
            background = Image.new('RGB', size, color)
            background.paste(image, image)
            options = restrict_dict(kwargs, ['quality', 'optimize',
                                             'progressive'])

            if 'quality' not in options:
                options['quality'] = rcParams['savefig.jpeg_quality']

            return background.save(filename_or_obj, format='jpeg', **options)
开发者ID:AbdealiJK,项目名称:matplotlib,代码行数:34,代码来源:backend_agg.py

示例14: test_conversions_masked

def test_conversions_masked():
    x1 = np.ma.array(['k', 'b'], mask=[True, False])
    x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]])
    x2[0] = np.ma.masked
    assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0)
    assert_array_equal(mcolors.to_rgba_array(x1),
                       [[0, 0, 0, 0], [0, 0, 1, 1]])
    assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1))
开发者ID:QuLogic,项目名称:matplotlib,代码行数:8,代码来源:test_colors.py

示例15: to_qcolor

def to_qcolor(color):
    """Create a QColor from a matplotlib color"""
    qcolor = QtGui.QColor()
    try:
        rgba = mcolors.to_rgba(color)
    except ValueError:
        warnings.warn('Ignoring invalid color %r' % color)
        return qcolor  # return invalid QColor
    qcolor.setRgbF(*rgba)
    return qcolor
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:10,代码来源:formlayout.py


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