本文整理汇总了Python中matplotlib.colors.to_rgba函数的典型用法代码示例。如果您正苦于以下问题:Python to_rgba函数的具体用法?Python to_rgba怎么用?Python to_rgba使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_rgba函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: print_jpg
def print_jpg(self, filename_or_obj, *args, dryrun=False,
pil_kwargs=None, **kwargs):
"""
Write the figure to a JPEG file.
Parameters
----------
filename_or_obj : str or PathLike or file-like object
The file to write to.
Other Parameters
----------------
quality : int
The image quality, on a scale from 1 (worst) to 100 (best).
The default is :rc:`savefig.jpeg_quality`. Values above
95 should be avoided; 100 completely disables the JPEG
quantization stage.
optimize : bool
If present, indicates that the encoder should
make an extra pass over the image in order to select
optimal encoder settings.
progressive : bool
If present, indicates that this image
should be stored as a progressive JPEG file.
pil_kwargs : dict, optional
Additional keyword arguments that are passed to
`PIL.Image.save` when saving the figure. These take precedence
over *quality*, *optimize* and *progressive*.
"""
buf, size = self.print_to_buffer()
if dryrun:
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['savefig.facecolor'])
color = tuple([int(x * 255) for x in rgba[:3]])
background = Image.new('RGB', size, color)
background.paste(image, image)
if pil_kwargs is None:
pil_kwargs = {}
for k in ["quality", "optimize", "progressive"]:
if k in kwargs:
pil_kwargs.setdefault(k, kwargs[k])
pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"])
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
return background.save(
filename_or_obj, format='jpeg', **pil_kwargs)
开发者ID:matplotlib,项目名称:matplotlib,代码行数:51,代码来源:backend_agg.py
示例17: plot_colortable
def plot_colortable(colors, title, sort_colors=True, emptycols=0):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
topmargin = 40
# Sort colors by hue, saturation, value and name.
by_hsv = ((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
if sort_colors is True:
by_hsv = sorted(by_hsv)
names = [name for hsv, name in by_hsv]
n = len(names)
ncols = 4 - emptycols
nrows = n // ncols + int(n % ncols > 0)
width = cell_width * 4 + 2 * margin
height = cell_height * nrows + margin + topmargin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-topmargin)/height)
ax.set_xlim(0, cell_width * 4)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
ax.set_title(title, fontsize=24, loc="left", pad=10)
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
swatch_end_x = cell_width * col + swatch_width
text_pos_x = cell_width * col + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y, swatch_start_x, swatch_end_x,
color=colors[name], linewidth=18)
return fig
开发者ID:dopplershift,项目名称:matplotlib,代码行数:50,代码来源:named_colors.py
示例18: get_colors
def get_colors(c, num):
"""Stretch the color argument to provide the required number num"""
if type(c) == type("string"):
c = mcolors.to_rgba(c)
if iscolor(c):
return [c] * num
if len(c) == num:
return c
elif iscolor(c):
return [c] * num
elif len(c) == 0: #if edgecolor or facecolor is specified as 'none'
return [[0,0,0,0]] * num
elif iscolor(c[0]):
return [c[0]] * num
else:
raise ValueError('unknown color format %s' % c)
开发者ID:4over7,项目名称:matplotlib,代码行数:18,代码来源:art3d.py
示例19: display_frame_coords
def display_frame_coords(data, coords, window, vectors=None, ref=None, outlines=None,
**kws):
from grafico.imagine import ImageDisplay #FITSCubeDisplay,
from obstools.aps import ApertureCollection
fig, ax = plt.subplots()
imd = ImageDisplay(ax, data)
imd.connect()
aps = ApertureCollection(coords=coords[:,::-1], radii=7,
ec='darkorange', lw=1, ls='--',
**kws)
aps.axadd(ax)
aps.annotate(color='orangered', size='small')
if window:
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
llc = coords[:,::-1] - window/2
patches = [Rectangle(coo-window/2, window, window) for coo in llc]
rcol = PatchCollection(patches, edgecolor='r', facecolor='none',
lw=1, linestyle=':')
ax.add_collection(rcol)
if outlines is not None:
from matplotlib.colors import to_rgba
overlay = np.empty(data.shape+(4,))
overlay[...] = to_rgba('0.8', 0)
overlay[...,-1][~outlines.mask] = 1
ax.hold(True)
ax.imshow(overlay)
if vectors is not None:
if ref is None:
'cannot plot vectors without reference star'
Y, X = coords[ref]
V, U = vectors.T
ax.quiver(X, Y, U, V, color='r', scale_units='xy', scale=1, alpha=0.6)
return fig
开发者ID:apodemus,项目名称:obstools,代码行数:43,代码来源:diagnostics.py
示例20: __init__
def __init__(self, offset=(2, -2),
shadow_rgbFace=None, alpha=None,
rho=0.3, **kwargs):
"""
Parameters
----------
offset : pair of floats
The offset of the shadow in points.
shadow_rgbFace : color
The shadow color.
alpha : float
The alpha transparency of the created shadow patch.
Default is 0.3.
http://matplotlib.1069221.n5.nabble.com/path-effects-question-td27630.html
rho : float
A scale factor to apply to the rgbFace color if `shadow_rgbFace`
is not specified. Default is 0.3.
**kwargs
Extra keywords are stored and passed through to
:meth:`AbstractPathEffect._update_gc`.
"""
super(SimplePatchShadow, self).__init__(offset)
if shadow_rgbFace is None:
self._shadow_rgbFace = shadow_rgbFace
else:
self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
if alpha is None:
alpha = 0.3
self._alpha = alpha
self._rho = rho
#: The dictionary of keywords to update the graphics collection with.
self._gc = kwargs
#: The offset transform object. The offset isn't calculated yet
#: as we don't know how big the figure will be in pixels.
self._offset_tran = mtransforms.Affine2D()
开发者ID:4over7,项目名称:matplotlib,代码行数:41,代码来源:patheffects.py
注:本文中的matplotlib.colors.to_rgba函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论