本文整理匯總了Python中seaborn.color_palette方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.color_palette方法的具體用法?Python seaborn.color_palette怎麽用?Python seaborn.color_palette使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.color_palette方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: zscore_ds_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def zscore_ds_plot(training, target, future, corrected):
labels = ["training", "future", "target", "corrected"]
colors = {k: c for (k, c) in zip(labels, sns.color_palette("Set2", n_colors=4))}
alpha = 0.5
time_target = pd.date_range("1980-01-01", "1989-12-31", freq="D")
time_training = time_target[~((time_target.month == 2) & (time_target.day == 29))]
time_future = pd.date_range("1990-01-01", "1999-12-31", freq="D")
time_future = time_future[~((time_future.month == 2) & (time_future.day == 29))]
plt.figure(figsize=(8, 4))
plt.plot(time_training, training.uas, label="training", alpha=alpha, c=colors["training"])
plt.plot(time_target, target.uas, label="target", alpha=alpha, c=colors["target"])
plt.plot(time_future, future.uas, label="future", alpha=alpha, c=colors["future"])
plt.plot(time_future, corrected.uas, label="corrected", alpha=alpha, c=colors["corrected"])
plt.xlabel("Time")
plt.ylabel("Eastward Near-Surface Wind (m s-1)")
plt.legend()
return
示例2: edge_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def edge_plot(ts, filename):
n = ts.num_samples
pallete = sns.color_palette("husl", 2 ** n - 1)
lines = []
colours = []
for tree in ts.trees():
left, right = tree.interval
for u in tree.nodes():
children = tree.children(u)
# Don't bother plotting unary nodes, which will all have the same
# samples under them as their next non-unary descendant
if len(children) > 1:
for c in children:
lines.append([(left, c), (right, c)])
colours.append(pallete[unrank(tree.samples(c), n)])
lc = mc.LineCollection(lines, linewidths=2, colors=colours)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
save_figure(filename)
示例3: plot_sad
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot_sad(ax, sat_loss_ti, sat_gain_ti):
""" Plot loss and gain SAD scores.
Args:
ax (Axis): matplotlib axis to plot to.
sat_loss_ti (L_sm array): Minimum mutation delta across satmut length.
sat_gain_ti (L_sm array): Maximum mutation delta across satmut length.
"""
rdbu = sns.color_palette('RdBu_r', 10)
ax.plot(-sat_loss_ti, c=rdbu[0], label='loss', linewidth=1)
ax.plot(sat_gain_ti, c=rdbu[-1], label='gain', linewidth=1)
ax.set_xlim(0, len(sat_loss_ti))
ax.legend()
# ax_sad.grid(True, linestyle=':')
ax.xaxis.set_ticks([])
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_linewidth(0.5)
示例4: plot_solution
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot_solution(image_path, model):
"""
Plot an image with the top 5 class prediction
:param image_path:
:param model:
:return:
"""
# Set up plot
plt.figure(figsize=(6, 10))
ax = plt.subplot(2, 1, 1)
# Set up title
flower_num = image_path.split('/')[3]
title_ = cat_to_name[flower_num]
# Plot flower
img = process_image(image_path)
imshow(img, ax, title=title_);
# Make prediction
probs, labs, flowers = predict(image_path, model)
# Plot bar chart
plt.subplot(2, 1, 2)
sns.barplot(x=probs, y=flowers, color=sns.color_palette()[0]);
plt.show()
示例5: customize
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def customize(func):
"""
修飾器,設置輸出圖像內容與風格
"""
@wraps(func)
def call_w_context(*args, **kwargs):
set_context = kwargs.pop("set_context", True)
if set_context:
color_palette = sns.color_palette("colorblind")
with plotting_context(), axes_style(), color_palette:
sns.despine(left=True)
return func(*args, **kwargs)
else:
return func(*args, **kwargs)
return call_w_context
示例6: _register_colormaps
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def _register_colormaps():
import matplotlib as mpl
import seaborn as sns
c = sns.color_palette('nipy_spectral', 64)[2:43]
cmap = mpl.colors.LinearSegmentedColormap.from_list('alex_lv', c)
cmap.set_under(alpha=0)
mpl.cm.register_cmap(name='alex_lv', cmap=cmap)
c = sns.color_palette('YlGnBu', 64)[16:]
cmap = mpl.colors.LinearSegmentedColormap.from_list('alex', c)
cmap.set_under(alpha=0)
mpl.cm.register_cmap(name='alex_light', cmap=cmap)
mpl.cm.register_cmap(name='YlGnBu_crop', cmap=cmap)
mpl.cm.register_cmap(name='alex_dark', cmap=mpl.cm.GnBu_r)
# Temporary hack to workaround issue
# https://github.com/mwaskom/seaborn/issues/855
mpl.cm.alex_light = mpl.cm.get_cmap('alex_light')
mpl.cm.alex_dark = mpl.cm.get_cmap('alex_dark')
# Register colormaps on import if not mocking
示例7: vals2colors
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def vals2colors(vals, cmap='GnBu_d',res=100):
"""Maps values to colors
Args:
values (list or list of lists) - list of values to map to colors
cmap (str) - color map (default is 'husl')
res (int) - resolution of the color map (default: 100)
Returns:
list of rgb tuples
"""
# flatten if list of lists
if any(isinstance(el, list) for el in vals):
vals = list(itertools.chain(*vals))
# get palette from seaborn
palette = np.array(sns.color_palette(cmap, res))
ranks = np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1
return [tuple(i) for i in palette[ranks, :]]
示例8: plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot(self):
r'''
Plots the history of the lr and momentum evolution as a function of iterations
'''
with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette):
fig, axs = plt.subplots(2, 1, figsize=(self.plot_settings.w_mid, self.plot_settings.h_mid))
axs[1].set_xlabel("Iterations", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[0].set_ylabel("Learning Rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[1].set_ylabel("Momentum", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[0].plot(range(len(self.hist['lr'])), self.hist['lr'])
axs[1].plot(range(len(self.hist['mom'])), self.hist['mom'])
for ax in axs:
ax.tick_params(axis='x', labelsize=self.plot_settings.tk_sz, labelcolor=self.plot_settings.tk_col)
ax.tick_params(axis='y', labelsize=self.plot_settings.tk_sz, labelcolor=self.plot_settings.tk_col)
plt.show()
示例9: plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot(self, n_skip:int=0, n_max:Optional[int]=None, lim_y:Optional[Tuple[float,float]]=None) -> None:
r'''
Plot the loss as a function of the LR.
Arguments:
n_skip: Number of initial iterations to skip in plotting
n_max: Maximum iteration number to plot
lim_y: y-range for plotting
'''
# TODO: Decide on whether to keep this; could just pass to plot_lr_finders
with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette):
plt.figure(figsize=(self.plot_settings.w_mid, self.plot_settings.h_mid))
plt.plot(self.history['lr'][n_skip:n_max], self.history['loss'][n_skip:n_max], label='Training loss', color='g')
if np.log10(self.lr_bounds[1])-np.log10(self.lr_bounds[0]) >= 3: plt.xscale('log')
plt.ylim(lim_y)
plt.grid(True, which="both")
plt.legend(loc=self.plot_settings.leg_loc, fontsize=self.plot_settings.leg_sz)
plt.xticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
plt.yticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
plt.ylabel("Loss", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
plt.xlabel("Learning rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
plt.show()
示例10: plot_architectures
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot_architectures(df, save_cfg=cfg.saving_config):
"""Plot bar graph showing the architectures used in the study.
"""
fig, ax = plt.subplots(figsize=(save_cfg['text_width'] / 3,
save_cfg['text_width'] / 3))
colors = sns.color_palette()
counts = df['Architecture (clean)'].value_counts()
_, _, pct = ax.pie(counts.values, labels=counts.index, autopct='%1.1f%%',
wedgeprops=dict(width=0.3, edgecolor='w'), colors=colors,
pctdistance=0.55)
for i in pct:
i.set_fontsize(5)
ax.axis('equal')
plt.tight_layout()
if save_cfg is not None:
fname = os.path.join(save_cfg['savepath'], 'architectures')
fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)
return ax
示例11: plot_embeddings
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot_embeddings(self, embeddings):
embeddings = MinMaxScaler((0, 1)).fit_transform(self.embeddings)
fig = plt.figure()
buf = io.BytesIO()
sns.scatterplot(x=embeddings[:, 0], y=embeddings[:, 1], s=1,
hue=self.labels,
palette=sns.color_palette("hls", self.n_classes),
linewidth=0)
plt.savefig(buf, format='png', dpi=300)
plt.close(fig)
buf.seek(0)
image = tf.Summary.Image(encoded_image_string=buf.getvalue())
return image
示例12: _prepare_fig_labels
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def _prepare_fig_labels(data, labels):
'''Helper function for settiing up animation canvas
'''
# we choose a color palette with seaborn.
max_label = labels.max()
palette = np.array(sns.color_palette("hls", max_label+1))
# we create a scatter plot.
# we add the labels for each digit.
t, b, d = data.shape
data = data.transpose(1, 0, 2).reshape((t*b, d))
labels = labels[np.newaxis].repeat(t, axis=0).transpose(1, 0)
labels = labels.flatten()
fig = plt.figure(figsize=(8, 8))
return labels, palette, fig
示例13: format_colors
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def format_colors(feature_metadata, category, color_palette):
colors = []
annotations = feature_metadata[category].unique()
color_map = values_to_colors(annotations, color_palette)
colors.append('TREE_COLORS')
colors.append('SEPARATOR TAB')
colors.append('DATA')
for idx in feature_metadata.index:
color = color_map[feature_metadata.loc[idx, category]]
if feature_metadata.loc[idx, 'structure_source'] == 'MS2':
style, width = 'normal', 6
else:
style, width = 'dashed', 4
colors.append('%s\tclade\t%s\t%s\t%s' % (idx, color, style, width))
return '\n'.join(colors)
示例14: plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def plot(x, y, plot_id, names=None):
viz_df = pd.DataFrame(data=x[:5000])
viz_df['Label'] = y[:5000]
if names is not None:
viz_df['Label'] = viz_df['Label'].map(names)
viz_df.to_csv(args.save_dir + '/' + args.dataset + '.csv')
plt.subplots(figsize=(8, 5))
sns.scatterplot(x=0, y=1, hue='Label', legend='full', hue_order=sorted(viz_df['Label'].unique()),
palette=sns.color_palette("hls", n_colors=args.n_clusters),
alpha=.5,
data=viz_df)
l = plt.legend(bbox_to_anchor=(-.1, 1.00, 1.1, .5), loc="lower left", markerfirst=True,
mode="expand", borderaxespad=0, ncol=args.n_clusters + 1, handletextpad=0.01, )
l.texts[0].set_text("")
plt.ylabel("")
plt.xlabel("")
plt.tight_layout()
plt.savefig(args.save_dir + '/' + args.dataset +
'-' + plot_id + '.png', dpi=300)
plt.clf()
示例15: _parse_heatmap_metadata_annotations
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import color_palette [as 別名]
def _parse_heatmap_metadata_annotations(metadata_column, margin_palette):
'''
Transform feature or sample metadata into color vector for annotating
margin of clustermap.
Parameters
----------
metadata_column: pd.Series of metadata for annotating plots
margin_palette: str
Name of color palette to use for annotating metadata
along margin(s) of clustermap.
Returns
-------
Returns vector of colors for annotating clustermap and dict mapping colors
to classes.
'''
# Create a categorical palette to identify md col
metadata_column = metadata_column.astype(str)
col_names = sorted(metadata_column.unique())
# Select Color palette
if margin_palette == 'colorhelix':
col_palette = sns.cubehelix_palette(
len(col_names), start=2, rot=3, dark=0.3, light=0.8, reverse=True)
else:
col_palette = sns.color_palette(margin_palette, len(col_names))
class_colors = dict(zip(col_names, col_palette))
# Convert the palette to vectors that will be drawn on the matrix margin
col_colors = metadata_column.map(class_colors)
return col_colors, class_colors