本文整理汇总了Python中matplotlib.colors.to_hex方法的典型用法代码示例。如果您正苦于以下问题:Python colors.to_hex方法的具体用法?Python colors.to_hex怎么用?Python colors.to_hex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.colors
的用法示例。
在下文中一共展示了colors.to_hex方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_cn
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def test_cn():
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['blue', 'r'])
assert mcolors.to_hex("C0") == '#0000ff'
assert mcolors.to_hex("C1") == '#ff0000'
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['xkcd:blue', 'r'])
assert mcolors.to_hex("C0") == '#0343df'
assert mcolors.to_hex("C1") == '#ff0000'
matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r'])
assert mcolors.to_hex("C0") == '#8e4585'
# if '8e4585' gets parsed as a float before it gets detected as a hex
# colour it will be interpreted as a very large number.
# this mustn't happen.
assert mcolors.to_rgb("C0")[0] != np.inf
示例2: test_conversions
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
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
示例3: vectorized_to_hex
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def vectorized_to_hex(c_values, keep_alpha=False):
"""Convert a color (including vector of colors) to hex.
Parameters
----------
c: Matplotlib color
keep_alpha: boolean
to select if alpha values should be kept in the final hex values.
Returns
-------
rgba_hex : vector of hex values
"""
try:
hex_color = to_hex(c_values, keep_alpha)
except ValueError:
hex_color = [to_hex(color, keep_alpha) for color in c_values]
return hex_color
示例4: __init__
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def __init__(self, color, parent=None):
QtWidgets.QHBoxLayout.__init__(self)
assert isinstance(color, QtGui.QColor)
self.lineedit = QtWidgets.QLineEdit(
mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
self.lineedit.editingFinished.connect(self.update_color)
self.addWidget(self.lineedit)
self.colorbtn = ColorButton(parent)
self.colorbtn.color = color
self.colorbtn.colorChanged.connect(self.update_text)
self.addWidget(self.colorbtn)
示例5: update_text
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def update_text(self, color):
self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True))
示例6: test_color_names
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def test_color_names():
assert mcolors.to_hex("blue") == "#0000ff"
assert mcolors.to_hex("xkcd:blue") == "#0343df"
assert mcolors.to_hex("tab:blue") == "#1f77b4"
示例7: swap_colors
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def swap_colors(json_file_path):
'''
Switches out color ramp in meta.json files.
Uses custom color ramp if provided and valid; otherwise falls back to nextstrain default colors.
N.B.: Modifies json in place and writes to original file path.
'''
j = json.load(open(json_file_path, 'r'))
color_options = j['color_options']
for k,v in color_options.items():
if 'color_map' in v:
categories, colors = zip(*v['color_map'])
## Use custom colors if provided AND present for all categories in the dataset
if custom_colors and all([category in custom_colors for category in categories]):
colors = [ custom_colors[category] for category in categories ]
## Expand the color palette if we have too many categories
elif len(categories) > len(default_colors):
from matplotlib.colors import LinearSegmentedColormap, to_hex
from numpy import linspace
expanded_cmap = LinearSegmentedColormap.from_list('expanded_cmap', default_colors[-1], N=len(categories))
discrete_colors = [expanded_cmap(i) for i in linspace(0,1,len(categories))]
colors = [to_hex(c).upper() for c in discrete_colors]
else: ## Falls back to default nextstrain colors
colors = default_colors[len(categories)] # based on how many categories are present; keeps original ordering
j['color_options'][k]['color_map'] = map(list, zip(categories, colors))
json.dump(j, open(json_file_path, 'w'), indent=1)
示例8: getColor
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def getColor(self):
c = self.colorDialog.currentColor()
color = colors.to_hex(c.name(),keep_alpha=True)
return color
示例9: update_selectedShape
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def update_selectedShape(self):
self.selectedShape = self.to_draw
plist = np.ndarray.tolist(self.selectedShape.get_path().vertices)
plist = ', '.join(str(x) for x in plist)
self.df = pandas.read_csv('Markings/marking_records.csv')
if not self.df[self.df['artist'] == str(self.selectedShape)].index.values.astype(int) == []:
try:
self.selectind = self.df[self.df['artist'] == str(self.selectedShape)].index.values.astype(int)[0]
except:
self.selectind = 0
else:
pass
color = self.df.iloc[self.selectind]['labelcolor']
if self.labelon:
self.setToolTip(self.selectedshape_name)
if color is np.nan:
color = colors.to_hex('b', keep_alpha=True)
self.df.loc[self.selectind, 'path'] = plist
self.df.to_csv('Markings/marking_records.csv', index=False)
self.selectedShape.set_facecolor(color)
self.selectedShape.set_alpha(0.5)
self.selectionChanged.emit(True)
try:
canvas = self.selectedShape.get_figure().canvas
axes = self.selectedShape.axes
self.background = canvas.copy_from_bbox(self.selectedShape.axes.bbox)
canvas.restore_region(self.background)
axes.draw_artist(self.selectedShape)
axes.draw_artist(self._corner_handles.artist)
axes.draw_artist(self._edge_handles.artist)
axes.draw_artist(self._center_handle.artist)
# blit just the redrawn area
canvas.blit(axes.bbox)
except:
pass
示例10: mouse_release
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def mouse_release(self, event):
if event.button == 1:
if event.xdata is not None and event.ydata is not None:
x = int(event.xdata)
y = int(event.ydata)
if self.mode > 3 and self.mode <= 6:
try:
pixel = self.total_mask[x, y, :]
except:
pixel = [0, 0, 0]
pixel_color = matplotlib.colors.to_hex(pixel)
color_hex = []
patch_color_df = pandas.read_csv('configGUI/patch_color.csv')
count = patch_color_df['color'].count()
for i in range(count):
color_hex.append(matplotlib.colors.to_hex(patch_color_df.iloc[i]['color']))
try:
ind = color_hex.index(str(pixel_color))
self.mask_class = patch_color_df.iloc[ind]['class']
except:
pass
if self.mask_class is not None and self.labelon:
self.setToolTip(self.mask_class)
if not self.labelon:
self.setToolTip(
'Press Enter to choose label\nClick Rectangle or Ellipse to edit\nPress Delete to remove mark')
else:
if self.new_shape():
self.setToolTip(self.selectedshape_name)
elif event.button == 2:
self.wheel_clicked = False
elif self.picked and event.button == 1:
self._edit_on_release(event)
示例11: get_colors
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def get_colors(n, cmap="viridis", start=0.0, stop=1.0, alpha=1.0, return_hex=False):
"""
Get n evenly-spaced colors from a matplotlib colormap.
Parameters
----------
n : int
number of colors
cmap : string
name of a matplotlib colormap
start : float
where to start in the colorspace
stop : float
where to end in the colorspace
alpha : float
opacity, the alpha channel for the RGBa colors
return_hex : bool
if True, convert RGBa colors to HTML-like hexadecimal RGB strings. if
False, return colors as (R, G, B, alpha) tuples.
Returns
-------
color_list : list
"""
color_list = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, n)]
if return_hex:
color_list = [colors.to_hex(c) for c in color_list]
else:
color_list = [(r, g, b, alpha) for r, g, b, _ in color_list]
return color_list
示例12: evaluate_cmap
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def evaluate_cmap(self, cmap, draw_mu, draw_sigma, obs: Union[float, list] = None):
likelihood_at_observation = stats.norm.pdf(obs, loc=draw_mu, scale=draw_sigma)
color_fill = colors.to_hex(cmap.to_rgba(np.atleast_1d(likelihood_at_observation)[0]))
return color_fill
示例13: plot_nullclines
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_hex [as 别名]
def plot_nullclines(vecfld,
lw=3,
background=None,
save_show_or_return='return',
save_kwargs={},
ax=None):
"""Plot nullclines stored in the VectorField2D class.
Arguments
---------
vecfld: :class:`~VectorField2D`
An instance of the VectorField2D class which presumably has fixed points computed and stored.
lw: `float` (default: 3)
The linewidth of the nullcline.
background: `str` or None (default: None)
The background color of the plot.
save_show_or_return: {'show', 'save', 'return'} (default: `return`)
Whether to save, show or return the figure.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'plot_nullclines', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
ax: :class:`~matplotlib.axes.Axes`
The matplotlib axes used for plotting. Default is to use the current axis.
"""
from matplotlib import rcParams
from matplotlib.colors import to_hex
if background is None:
_background = rcParams.get("figure.facecolor")
_background = to_hex(_background) if type(_background) is tuple else _background
else:
_background = background
if _background in ["#ffffff", "black"]:
colors = ["#189e1a", "#1f77b4"]
else:
colors = ["#189e1a", "#1f77b4"]
if ax is None:
ax = plt.gca()
for ncx in vecfld.NCx:
ax.plot(*ncx.T, c=colors[0], lw=lw)
for ncy in vecfld.NCy:
ax.plot(*ncy.T, c=colors[1], lw=lw)
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'plot_nullclines', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return ax