本文整理汇总了Python中matplotlib.colors.rgb2hex函数的典型用法代码示例。如果您正苦于以下问题:Python rgb2hex函数的具体用法?Python rgb2hex怎么用?Python rgb2hex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rgb2hex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_style_dict
def _get_style_dict(self, gc, rgbFace):
"""
return the style string. style is generated from the
GraphicsContext and rgbFace
"""
attrib = {}
if gc.get_hatch() is not None:
attrib[u"fill"] = u"url(#%s)" % self._get_hatch(gc, rgbFace)
else:
if rgbFace is None:
attrib[u"fill"] = u"none"
elif tuple(rgbFace[:3]) != (0, 0, 0):
attrib[u"fill"] = rgb2hex(rgbFace)
if gc.get_alpha() != 1.0:
attrib[u"opacity"] = str(gc.get_alpha())
offset, seq = gc.get_dashes()
if seq is not None:
attrib[u"stroke-dasharray"] = u",".join([u"%f" % val for val in seq])
attrib[u"stroke-dashoffset"] = unicode(float(offset))
linewidth = gc.get_linewidth()
if linewidth:
attrib[u"stroke"] = rgb2hex(gc.get_rgb())
if linewidth != 1.0:
attrib[u"stroke-width"] = str(linewidth)
if gc.get_joinstyle() != "round":
attrib[u"stroke-linejoin"] = gc.get_joinstyle()
if gc.get_capstyle() != "projecting":
attrib[u"stroke-linecap"] = _capstyle_d[gc.get_capstyle()]
return attrib
示例2: _on_color_pick
def _on_color_pick(self):
# store old value and type
try:
old_value = self.get_value()
old_color_dev = colors.get_color_dev(old_value)
color = colors.get_color_as_rgba_f(old_value)
except ValueError:
color = None
if color is None:
color = [1., 0., 0.]
color = np.array(color) * 255
qcolor = QtGui.QColor(*color.astype(int))
# create dialog
dialog = QtGui.QColorDialog(self)
dialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True)
color = dialog.getColor(initial=qcolor)
# convert the color to previous type if possible
if old_color_dev == 'name':
color_name = mpl_colors.rgb2hex(color.getRgbF())
new_value = colors.COLORS_INV.get(color_name, color_name)
elif old_color_dev in ['rgbf', 'rgbaf']:
new_value = color.getRgbF()
new_value = [round(i, 2) for i in new_value]
elif old_color_dev in ['rgb', 'rgba']:
new_value = color.getRgb()
elif old_color_dev == 'hex':
new_value = mpl_colors.rgb2hex(color.getRgbF())
else:
new_value = color.name()
self.set_value(new_value)
示例3: _get_style
def _get_style(self, gc, rgbFace):
"""
return the style string.
style is generated from the GraphicsContext, rgbFace and clippath
"""
if rgbFace is None:
fill = "none"
else:
fill = rgb2hex(rgbFace[:3])
offset, seq = gc.get_dashes()
if seq is None:
dashes = ""
else:
dashes = "stroke-dasharray: %s; stroke-dashoffset: %f;" % (",".join(["%f" % val for val in seq]), offset)
linewidth = gc.get_linewidth()
if linewidth:
return (
"fill: %s; stroke: %s; stroke-width: %f; "
"stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f"
% (
fill,
rgb2hex(gc.get_rgb()[:3]),
linewidth,
gc.get_joinstyle(),
_capstyle_d[gc.get_capstyle()],
dashes,
gc.get_alpha(),
)
)
else:
return "fill: %s; opacity: %f" % (fill, gc.get_alpha())
示例4: ratios_to_colors
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]
示例5: heat_map
def heat_map(self, cmap='RdYlGn', vmin=None, vmax=None, font_cmap=None):
if cmap is None:
carr = ['#d7191c', '#fdae61', '#ffffff', '#a6d96a', '#1a9641']
cmap = LinearSegmentedColormap.from_list('default-heatmap', carr)
if isinstance(cmap, basestring):
cmap = get_cmap(cmap)
if isinstance(font_cmap, basestring):
font_cmap = get_cmap(font_cmap)
vals = self.actual_values.astype(float)
if vmin is None:
vmin = vals.min().min()
if vmax is None:
vmax = vals.max().max()
norm = (vals - vmin) / (vmax - vmin)
for ridx in range(self.nrows):
for cidx in range(self.ncols):
v = norm.iloc[ridx, cidx]
if np.isnan(v):
continue
color = cmap(v)
hex = rgb2hex(color)
styles = {'BACKGROUND': HexColor(hex)}
if font_cmap is not None:
styles['TEXTCOLOR'] = HexColor(rgb2hex(font_cmap(v)))
self.iloc[ridx, cidx].apply_styles(styles)
return self
示例6: heat_map
def heat_map(self, cmap="RdYlGn", vmin=None, vmax=None, font_cmap=None):
if cmap is None:
carr = ["#d7191c", "#fdae61", "#ffffff", "#a6d96a", "#1a9641"]
cmap = LinearSegmentedColormap.from_list("default-heatmap", carr)
if isinstance(cmap, str):
cmap = get_cmap(cmap)
if isinstance(font_cmap, str):
font_cmap = get_cmap(font_cmap)
vals = self.actual_values.astype(float)
if vmin is None:
vmin = vals.min().min()
if vmax is None:
vmax = vals.max().max()
norm = (vals - vmin) / (vmax - vmin)
for ridx in range(self.nrows):
for cidx in range(self.ncols):
v = norm.iloc[ridx, cidx]
if np.isnan(v):
continue
color = cmap(v)
hex = rgb2hex(color)
styles = {"BACKGROUND": HexColor(hex)}
if font_cmap is not None:
styles["TEXTCOLOR"] = HexColor(rgb2hex(font_cmap(v)))
self.iloc[ridx, cidx].apply_styles(styles)
return self
示例7: _get_style
def _get_style(self, gc, rgbFace):
"""
return the style string.
style is generated from the GraphicsContext, rgbFace and clippath
"""
if rgbFace is None:
fill = 'none'
else:
fill = rgb2hex(rgbFace)
offset, seq = gc.get_dashes()
if seq is None:
dashes = ''
else:
dashes = 'stroke-dasharray: %s; stroke-dashoffset: %s;' % (
','.join(['%s'%val for val in seq]), offset)
linewidth = gc.get_linewidth()
if linewidth:
return 'fill: %s; stroke: %s; stroke-width: %s; ' \
'stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %s' % (
fill,
rgb2hex(gc.get_rgb()),
linewidth,
gc.get_joinstyle(),
_capstyle_d[gc.get_capstyle()],
dashes,
gc.get_alpha(),
)
else:
return 'fill: %s; opacity: %s' % (\
fill,
gc.get_alpha(),
)
示例8: assign_continuous_colors
def assign_continuous_colors(data, gg, color_col):
"""
Logic to assign colors in the continuous case.
Handle continuous colors here. We're going to use whatever colormap
is defined to evaluate for each value. We're then going to convert
each color to HEX so that it can fit in 1 column. This will make it
much easier when creating layers. We're also going to evaluate the
quantiles for that particular column to generate legend scales. This
isn't what ggplot does, but it's good enough for now.
Parameters
----------
data : DataFrame
dataframe which should have shapes assigned to
gg : ggplot object, which holds information and gets a legend assigned
color_col : The column we are using to color.
Returns
-------
data : DataFrame
the changed dataframe
"""
values = data[color_col].tolist()
values = [(i - min(values)) / (max(values) - min(values)) for i in values]
color_mapping = gg.colormap(values)[::, :3]
data["color_mapping"] = [rgb2hex(value) for value in color_mapping]
quantiles = np.percentile(gg.data[color_col], [0, 25, 50, 75, 100])
key_colors = gg.colormap([0, 25, 50, 75, 100])[::, :3]
key_colors = [rgb2hex(value) for value in key_colors]
gg.add_to_legend("color", dict(zip(key_colors, quantiles)),
scale_type="continuous")
return data
示例9: test_xkcd
def test_xkcd():
x11_blue = mcolors.rgb2hex(
mcolors.colorConverter.to_rgb('blue'))
assert x11_blue == '#0000ff'
XKCD_blue = mcolors.rgb2hex(
mcolors.colorConverter.to_rgb('XKCDblue'))
assert XKCD_blue == '#0343df'
示例10: getLevels
def getLevels(self):
levels = []
colHEX_RGB = []
colHEX_BGR = []
colRGB = []
colBGR = []
level_ok = True
col_ok = True
rows = self.ui.tableWidget.rowCount()
if rows > 0:
for row in range(rows):
try:
levels.append(float(self.ui.tableWidget.item(row, 0).text()))
float(self.ui.tableWidget.item(row, 1).text())
except:
return [], False, [], [], True
try:
col = str(self.ui.tableWidget.item(row, 2).text()).split(",")
colFloat_RGB = (float(col[0])/255.0, float(col[1])/255.0, float(col[2])/255.0)
colFloat_BGR = (float(col[2])/255.0, float(col[1])/255.0, float(col[0])/255.0)
colRGB.append([float(col[0]), float(col[1]), float(col[2])])
colBGR.append([float(col[2]), float(col[1]), float(col[0])])
# colHex = colors.rgb2hex(colFloat_RGB)
colHEX_RGB.append(colors.rgb2hex(colFloat_RGB))
colHEX_BGR.append(colors.rgb2hex(colFloat_BGR))
except:
return [], True, [], [], False
# check if level ranges are in ascending order
for row in range(rows-1):
level_ai = round(float(self.ui.tableWidget.item(row, 0).text()), 6)
level_aj = round(float(self.ui.tableWidget.item(row, 1).text()), 6)
level_bi = round(float(self.ui.tableWidget.item(row+1, 0).text()), 6)
if level_aj != level_bi:
level_ok = False
if level_aj <= level_ai:
level_ok = False
level_1i = float(self.ui.tableWidget.item(0, 0).text())
level_1j = float(self.ui.tableWidget.item(0, 1).text())
if level_1j <= level_1i:
level_ok = False
level_Ni = float(self.ui.tableWidget.item(rows-1, 0).text())
level_Nj = float(self.ui.tableWidget.item(rows-1, 1).text())
if level_Nj <= level_Ni:
level_ok = False
levels.append(float(self.ui.tableWidget.item(rows-1, 1).text()))
return levels, level_ok, colHEX_RGB, colRGB, colHEX_BGR, colBGR, col_ok
示例11: draw_gouraud_triangle
def draw_gouraud_triangle(self, gc, points, colors, trans):
# This uses a method described here:
#
# http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html
#
# that uses three overlapping linear gradients to simulate a
# Gouraud triangle. Each gradient goes from fully opaque in
# one corner to fully transparent along the opposite edge.
# The line between the stop points is perpendicular to the
# opposite edge. Underlying these three gradients is a solid
# triangle whose color is the average of all three points.
trans_and_flip = self._make_flip_transform(trans)
tpoints = trans_and_flip.transform(points)
write = self._svgwriter.write
write("<defs>")
for i in range(3):
x1, y1 = points[i]
x2, y2 = points[(i + 1) % 3]
x3, y3 = points[(i + 2) % 3]
c = colors[i][:3]
if x2 == x3:
xb = x2
yb = y1
elif y2 == y3:
xb = x1
yb = y2
else:
m1 = (y2 - y3) / (x2 - x3)
b1 = y2 - (m1 * x2)
m2 = -(1.0 / m1)
b2 = y1 - (m2 * x1)
xb = (-b1 + b2) / (m1 - m2)
yb = m2 * xb + b2
write(
'<linearGradient id="GR%x_%d" x1="%f" y1="%f" x2="%f" y2="%f" gradientUnits="userSpaceOnUse">'
% (self._n_gradients, i, x1, y1, xb, yb)
)
write('<stop offset="0" stop-color="%s" stop-opacity="1.0"/>' % rgb2hex(c))
write('<stop offset="1" stop-color="%s" stop-opacity="0.0"/>' % rgb2hex(c))
write("</linearGradient>")
# Define the triangle itself as a "def" since we use it 4 times
write('<polygon id="GT%x" points="%f %f %f %f %f %f"/>' % (self._n_gradients, x1, y1, x2, y2, x3, y3))
write("</defs>\n")
avg_color = np.sum(colors[:, :3], axis=0) / 3.0
write('<use xlink:href="#GT%x" fill="%s"/>\n' % (self._n_gradients, rgb2hex(avg_color)))
for i in range(3):
write(
'<use xlink:href="#GT%x" fill="url(#GR%x_%d)" filter="url(#colorAdd)"/>\n'
% (self._n_gradients, self._n_gradients, i)
)
self._n_gradients += 1
示例12: assign_colors
def assign_colors(data, aes, gg):
"""
Assigns colors to the given data based on the aes and adds the right legend
We need to take a value an convert it into colors that we can actually
plot. This means checking to see if we're colorizing a discrete or
continuous value, checking if their is a colormap, etc.
Parameters
----------
data : DataFrame
dataframe which should have shapes assigned to
aes : aesthetic
mapping, including a mapping from color to variable
gg : ggplot object, which holds information and gets a legend assigned
Returns
-------
data : DataFrame
the changed dataframe
"""
if 'color' in aes:
color_col = aes['color']
# Handle continuous colors here. We're going to use whatever colormap
# is defined to evaluate for each value. We're then going to convert
# each color to HEX so that it can fit in 1 column. This will make it
# much easier when creating layers. We're also going to evaluate the
# quantiles for that particular column to generate legend scales. This
# isn't what ggplot does, but it's good enough for now.
if color_col in data._get_numeric_data().columns:
values = data[color_col].tolist()
# Normalize the values for the colormap
values = [(i - min(values)) / (max(values) - min(values)) for i in values]
color_mapping = gg.colormap(values)[::, :3]
data["color_mapping"] = [rgb2hex(value) for value in color_mapping]
quantiles = np.percentile(gg.data[color_col], [0, 25, 50, 75, 100])
key_colors = gg.colormap([0, 25, 50, 75, 100])[::, :3]
key_colors = [rgb2hex(value) for value in key_colors]
gg.add_to_legend("color", dict(zip(key_colors, quantiles)), scale_type="continuous")
# Handle discrete colors here. We're going to check and see if the user
# has defined their own color palette. If they have then we'll use those
# colors for mapping. If not, then we'll generate some default colors.
# We also have to be careful here because for some odd reason the next()
# function is different in Python 2.7 and Python 3.0. Once we've done that
# we generate the legends based off the the (color -> value) mapping.
else:
possible_colors = np.unique(data[color_col])
if gg.manual_color_list:
color = color_gen(len(possible_colors), gg.manual_color_list)
else:
color = color_gen(len(possible_colors))
color_mapping = dict((value, six.next(color)) for value in possible_colors)
data["color_mapping"] = data[color_col].apply(lambda x: color_mapping[x])
gg.add_to_legend("color", dict((v, k) for k, v in color_mapping.items()))
return data
示例13: __init__
def __init__(self, pdb_object, structure_name, residues_of_interest = [], label_all_residues_of_interest = False, **kwargs):
'''The chain_seed_color kwarg can be either:
- a triple of R,G,B values e.g. [0.5, 1.0, 0.75] where each value is between 0.0 and 1.0;
- a hex string #RRGGBB e.g. #77ffaa;
- a name defined in the predefined dict above e.g. "aquamarine".
'''
self.pdb_object = pdb_object
self.structure_name = structure_name
self.add_residues_of_interest(residues_of_interest)
self.label_all_residues_of_interest = label_all_residues_of_interest
self.chain_colors = kwargs.get('chain_colors') or {}
# Set up per-chain colors
try:
if not self.chain_colors and kwargs.get('chain_seed_color'):
chain_seed_color = kwargs.get('chain_seed_color')
if isinstance(chain_seed_color, str) or isinstance(chain_seed_color, unicode):
chain_seed_color = str(chain_seed_color)
if chain_seed_color.startswith('#'):
if len(chain_seed_color) != 7:
chain_seed_color = None
else:
trpl = predefined.get(chain_seed_color)
chain_seed_color = None
if trpl:
chain_seed_color = mpl_colors.rgb2hex(trpl)
elif isinstance(chain_seed_color, list) and len(chain_seed_color) == 3:
chain_seed_color = mpl_colors.rgb2hex(chain_seed_color)
if chain_seed_color.startswith('#') and len(chain_seed_color) == 7:
# todo: We are moving between color spaces multiple times so are probably introducing artifacts due to rounding. Rewrite this to minimize this movement.
chain_seed_color = chain_seed_color[1:]
hsl_color = colorsys.rgb_to_hls(int(chain_seed_color[0:2], 16)/255.0, int(chain_seed_color[2:4], 16)/255.0, int(chain_seed_color[4:6], 16)/255.0)
chain_seed_hue = int(360.0 * hsl_color[0])
chain_seed_saturation = max(0.15, hsl_color[1]) # otherwise some colors e.g. near-black will not yield any alternate colors
chain_seed_lightness = max(0.15, hsl_color[2]) # otherwise some colors e.g. near-black will not yield any alternate colors
min_colors_in_wheel = 4 # choose at least 4 colors - this usually results in a wider variety of colors and prevents clashes e.g. given 2 chains in both mut and wt, wt seeded with blue, and mut seeded with yellow, we will get a clash
chain_ids = sorted(pdb_object.atom_sequences.keys())
# Choose complementary colors, respecting the original saturation and lightness values
chain_colors = ggplot_color_wheel(max(len(chain_ids), min_colors_in_wheel), start = chain_seed_hue, saturation_adjustment = None, saturation = chain_seed_saturation, lightness = chain_seed_lightness)
assert(len(chain_colors) >= len(chain_ids))
self.chain_colors = {}
for i in xrange(len(chain_ids)):
self.chain_colors[chain_ids[i]] = str(list(mpl_colors.hex2color('#' + chain_colors[i])))
# Force use of the original seed as this may have been altered above in the "= max(" statements
self.chain_colors[chain_ids[0]] = str(list(mpl_colors.hex2color('#' + chain_seed_color)))
except Exception, e:
print('An exception occurred setting the chain colors. Ignoring exception and resuming with default colors.')
print(str(e))
print(traceback.format_exc())
示例14: _cmap_d_pal
def _cmap_d_pal(n):
if n > ncolors:
raise ValueError(
"cmap `{}` has {} colors you requested {} "
"colors.".format(name, ncolors, n))
if ncolors < 256:
return [mcolors.rgb2hex(c) for c in colormap.colors[:n]]
else:
# Assume these are continuous and get colors equally spaced
# intervals e.g. viridis is defined with 256 colors
idx = np.linspace(0, ncolors-1, n).round().astype(int)
return [mcolors.rgb2hex(colormap.colors[i]) for i in idx]
示例15: test_cn
def test_cn():
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['blue', 'r'])
x11_blue = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C0'))
assert x11_blue == '#0000ff'
red = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C1'))
assert red == '#ff0000'
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['XKCDblue', 'r'])
XKCD_blue = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C0'))
assert XKCD_blue == '#0343df'
red = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C1'))
assert red == '#ff0000'