当前位置: 首页>>代码示例>>Python>>正文


Python seaborn.barplot方法代码示例

本文整理汇总了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 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:21,代码来源:chart.py

示例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() 
开发者ID:GabrielePicco,项目名称:deep-learning-flower-identifier,代码行数:24,代码来源:flower_classifier.py

示例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 
开发者ID:vwxyzjn,项目名称:cleanrl,代码行数:21,代码来源:dqn_atari_visual.py

示例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 
开发者ID:vwxyzjn,项目名称:cleanrl,代码行数:21,代码来源:ppo_atari_visual.py

示例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 
开发者ID:SUNCAT-Center,项目名称:CatLearn,代码行数:21,代码来源:site_stability.py

示例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')) 
开发者ID:igemsoftware2017,项目名称:AiGEM_TeamHeidelberg2017,代码行数:23,代码来源:helpers.py

示例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')) 
开发者ID:igemsoftware2017,项目名称:AiGEM_TeamHeidelberg2017,代码行数:18,代码来源:helpers.py

示例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() 
开发者ID:shidi1985,项目名称:L2RPN,代码行数:25,代码来源:analyze_action.py

示例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() 
开发者ID:nanoporetech,项目名称:wub,代码行数:19,代码来源:bam_multi_qc.py

示例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') 
开发者ID:melqkiades,项目名称:yelp,代码行数:26,代码来源:thesis_charts.py

示例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() 
开发者ID:melqkiades,项目名称:yelp,代码行数:27,代码来源:thesis_charts.py

示例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() 
开发者ID:chainer,项目名称:chainer-chemistry,代码行数:22,代码来源:plot.py

示例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) 
开发者ID:chainer,项目名称:chainer-chemistry,代码行数:22,代码来源:summary_eval_molnet.py

示例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) 
开发者ID:chainer,项目名称:chainer-chemistry,代码行数:21,代码来源:plot.py

示例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) 
开发者ID:eyadsibai,项目名称:brute-force-plotter,代码行数:19,代码来源:brute_force_plotter.py


注:本文中的seaborn.barplot方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。