本文整理匯總了Python中seaborn.barplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.barplot方法的具體用法?Python seaborn.barplot怎麽用?Python seaborn.barplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.barplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: image
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def image(path: str, costs: Dict[str, int]) -> str:
ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
xs = [costs.get(k, 0) for k in ys]
sns.set_style('white')
sns.set(font='Concourse C3', font_scale=3)
g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
g.axes.yaxis.set_ticklabels([])
rects = g.patches
sns.set(font='Concourse C3', font_scale=2)
for rect, label in zip(rects, xs):
if label == 0:
continue
height = rect.get_height()
g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
g.margins(y=0, x=0)
sns.despine(left=True, bottom=True)
g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
plt.clf() # Clear all data from matplotlib so it does not persist across requests.
return path
示例2: plot_solution
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [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()
示例3: render
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def render(self, mode="human"):
if mode=="rgb_array":
env_rgb_array = super().render(mode)
fig, ax = plt.subplots(figsize=(self.image_shape[1]/100,self.image_shape[0]/100), constrained_layout=True, dpi=100)
df = pd.DataFrame(np.array(self.q_values).T)
sns.barplot(x=df.index, y=0, data=df, ax=ax)
ax.set(xlabel='actions', ylabel='q-values')
fig.canvas.draw()
X = np.array(fig.canvas.renderer.buffer_rgba())
Image.fromarray(X)
# Image.fromarray(X)
rgb_image = np.array(Image.fromarray(X).convert('RGB'))
plt.close(fig)
q_value_rgb_array = rgb_image
return np.append(env_rgb_array, q_value_rgb_array, axis=1)
else:
super().render(mode)
# TRY NOT TO MODIFY: setup the environment
示例4: render
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def render(self, mode="human"):
if mode=="rgb_array":
env_rgb_array = super().render(mode)
fig, ax = plt.subplots(figsize=(self.image_shape[1]/100,self.image_shape[0]/100), constrained_layout=True, dpi=100)
df = pd.DataFrame(np.array(self.probs).T)
sns.barplot(x=df.index, y=0, data=df, ax=ax)
ax.set(xlabel='actions', ylabel='probs')
fig.canvas.draw()
X = np.array(fig.canvas.renderer.buffer_rgba())
Image.fromarray(X)
# Image.fromarray(X)
rgb_image = np.array(Image.fromarray(X).convert('RGB'))
plt.close(fig)
q_value_rgb_array = rgb_image
return np.append(env_rgb_array, q_value_rgb_array, axis=1)
else:
super().render(mode)
# TRY NOT TO MODIFY: setup the environment
示例5: plot_features
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_features(self,
labels=None,
frequencies=None,
show=True):
"""Plots feature frequencies"""
print('Plotting feature frequencies.')
if labels is None:
labels = list(self.feature_frequencies.keys())
if frequencies is None:
frequencies = list(self.feature_frequencies.values())
fig, ax = plt.subplots(figsize=(12, int(len(labels)*0.6)))
ax = sns.barplot(x=frequencies, y=labels)
ax.set_xlabel(r'Occurrence probability (\%)')
plt.tight_layout()
if show:
plt.show()
return fig, ax
示例6: plot_histogram
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_histogram(log_file, save_dir):
"""Simple plotting function to plot a hist from a specified file containing counts per labels.
Args:
log_file: A `str` to the file containing the histogram data.
"""
count_dict = {}
with open(log_file, "r") as in_fobj:
for line in in_fobj:
pred_labels = line.strip().split()
for label in pred_labels:
try:
count_dict[label] += 1
except KeyError:
count_dict[label] = 0
bars = [count_dict[label] for label in count_dict.keys()]
labels = [label for label in count_dict.keys()]
set_style("whitegrid")
fig, ax = plt.subplots()
ax = barplot(x=bars, y=labels)
fig.save(os.path.join(save_dir, 'negative_test.png'))
示例7: plot_histogram
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_histogram(log_file, save_dir):
count_dict = {}
with open(log_file, "r") as in_fobj:
for line in in_fobj:
pred_labels = line.strip().split()
for label in pred_labels:
try:
count_dict[label] += 1
except KeyError:
count_dict[label] = 0
bars = [count_dict[label] for label in count_dict.keys()]
labels = [label for label in count_dict.keys()]
set_style("whitegrid")
fig, ax = plt.subplots()
ax = barplot(x=bars, y=labels)
fig.save(os.path.join(save_dir, 'negative_test.png'))
示例8: analyze
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def analyze():
action_count = np.load(action_count_dir, allow_pickle=True)
print('action count loaded')
# action taken > 0
count_dict = {}
for i, v in enumerate(action_count):
if v > 0:
count_dict[i] = v
print('\n\n')
for k, v in sorted(count_dict.items()):
print('action: {}, count: {}'.format(k, v))
# y = np.load(data_dir + '/y_all_3695_score.npy')
# print(y[:20])
# plot barplot
seaborn.lineplot(list(count_dict.keys()), list(count_dict.values()))
plt.title('Action Count')
plt.xlabel('Action Index')
plt.ylabel('Count')
plt.show()
示例9: plot_bars_sns
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_bars_sns(data_map, title, xlab, ylab, plotter):
"""Barplot using seaborn backend.
:param data_map: A dictionary of labels and values.
:param title: Plot title.
:param xlab: X axis label.
:param ylab: Y axis label.
:param plotter: A wub.vis.report.Report instance.
"""
data = pd.DataFrame({'Value': list(data_map.values()), 'Label': list(data_map.keys()),
'x': np.arange(len(data_map))})
ax = sns.barplot(x="x", y="Value", hue="Label", data=data, hue_order=list(data_map.keys()))
ax.set_title(title)
ax.set_xlabel(xlab)
ax.set_ylabel(ylab)
ax.set_xticks([])
plotter.pages.savefig()
plotter.plt.clf()
示例10: plot_context_richness_score_pos_types
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_context_richness_score_pos_types():
prefix = Constants.RESULTS_FOLDER + Constants.ITEM_TYPE + \
'_topic_model_context_richness'
csv_file_path = prefix + '.csv'
json_file_path = prefix + '.json'
bow_type_field = 'POS type'
# bow_type_field = 'bow_type'
data_frame = pandas.read_csv(csv_file_path)
data_frame.drop(columns=['cycle_time'], inplace=True)
data_frame['num_topics'].astype('category')
data_frame['bow_type'].fillna('All', inplace=True)
data_frame.rename(columns={'bow_type': bow_type_field}, inplace=True)
data_frame = data_frame.loc[data_frame[
Constants.TOPIC_MODEL_TARGET_REVIEWS_FIELD] == Constants.SPECIFIC]
print(data_frame.describe())
print(data_frame.head())
g = seaborn.barplot(
x='num_topics', y='probability_score', hue=bow_type_field, data=data_frame)
g.set(xlabel='Number of topics', ylabel='Context richness score')
plt.ylim(0, 0.14)
g.figure.savefig(prefix + '_pos_types.pdf')
示例11: plot_context_richness_score_specific_vs_generic
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def plot_context_richness_score_specific_vs_generic():
prefix = Constants.RESULTS_FOLDER + Constants.ITEM_TYPE + \
'_topic_model_context_richness'
csv_file_path = prefix + '.csv'
json_file_path = prefix + '.json'
review_type_field = 'Review type'
data_frame = pandas.read_csv(csv_file_path)
data_frame.drop(columns=['cycle_time'], inplace=True)
data_frame['num_topics'].astype('category')
data_frame['bow_type'].fillna('All', inplace=True)
data_frame.rename(columns=
{Constants.TOPIC_MODEL_TARGET_REVIEWS_FIELD: review_type_field}, inplace=True)
data_frame = data_frame.loc[data_frame['bow_type'] == 'NN']
print(data_frame.describe())
print(data_frame.head())
g = seaborn.barplot(
x='num_topics', y='probability_score', hue=review_type_field,
data=data_frame)
g.set(xlabel='Number of topics', ylabel='Context-richness')
plt.ylim(0, 0.14)
g.figure.savefig(prefix + '_specific_vs_generic.pdf')
# plt.show()
示例12: save_evaluation_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def save_evaluation_plot(x, y, metric, filename):
plt.figure()
sns.set()
ax = sns.barplot(y=x, x=y)
for n, (label, _y) in enumerate(zip(x, y)):
ax.annotate(
s='{:.4g}'.format(abs(_y)),
xy=(_y, n),
ha='left',
va='center',
xytext=(5, 0),
textcoords='offset points',
color='gray')
plt.title('Performance on qm9: {}'.format(metric))
plt.xlabel(metric)
plt.savefig(filename)
plt.close()
示例13: save_evaluation_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def save_evaluation_plot(x, y_mean, metric, dataset_name, filename):
plt.figure()
sns.set()
ax = sns.barplot(y=x, x=y_mean)
# If "text" does not work, change the attribute name to "s"
for n, (label, _y) in enumerate(zip(x, y_mean)):
ax.annotate(
s='{:.3f}'.format(abs(_y)),
xy=(_y, n),
ha='right',
va='center',
xytext=(-5, 0),
textcoords='offset points',
color='white')
plt.title('Performance on ' + dataset_name)
plt.xlabel(metric)
plt.savefig(filename)
示例14: save_evaluation_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def save_evaluation_plot(x, y, metric, filename):
plt.figure()
sns.set()
ax = sns.barplot(y=x, x=y)
for n, (label, _y) in enumerate(zip(x, y)):
ax.annotate(
'{:.3f}'.format(abs(_y)),
xy=(_y, n),
ha='right',
va='center',
xytext=(-5, 0),
textcoords='offset points',
color='white')
plt.title('Performance on own dataset')
plt.xlabel(metric)
plt.savefig(filename)
示例15: bar_box_violin_dot_plots
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import barplot [as 別名]
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
sns.boxplot(
category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
)
sns.violinplot(
category_col,
numeric_col,
data=data,
kind="violin",
inner="quartile",
scale="count",
split=True,
ax=axes[3],
)
sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
sns.despine(left=True)