在海运条形图顶部显示计数 [英] Display count on top of seaborn barplot

查看:34
本文介绍了在海运条形图顶部显示计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,如下所示:

  User   A       B     C
   ABC   100    121   OPEN
   BCD   200    255   CLOSE
   BCD   500    134   OPEN
   DEF   600    125   CLOSE
   ABC   900    632   OPEN
   ABC   150    875   CLOSE
   DEF   690    146   OPEN

我正在尝试显示列‘user’上的计数图。代码如下:

fig, ax1 = plt.subplots(figsize=(20,10))
graph = sns.countplot(ax=ax1,x='User', data=df)
graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
for p in graph.patches:
    height = p.get_height()
    graph.text(p.get_x()+p.get_width()/2., height + 0.1,
        'Hello',ha="center")

输出如下:

但是,我想用列"user"的value_counts替换字符串"Hello"。当我添加代码以将标签添加到图表时:

for p in graph.patches:
    height = p.get_height()
    graph.text(p.get_x()+p.get_width()/2., height + 0.1,
        df['User'].value_counts(),ha="center")

我获得的输出为:

推荐答案

matplotlib 3.4.0中的新增功能

我们现在可以使用内置的automatically annotate bar plotsAxes.bar_label,因此我们只需访问/提取海运绘图的Axes

Seborn提供了几种绘制计数的方法,每种方法的计数聚合和Axes处理略有不同:

  • seaborn.countplot(最简单)

    这会自动聚合计数并返回Axes,因此只需直接标记ax.containers[0]

    ax = sns.countplot(x='User', data=df)
    ax.bar_label(ax.containers[0])
    
  • seaborn.catplotkind='count'

    这会将countplot绘制到FacetGrid上,因此在标记ax.containers[0]之前,请先从网格中提取Axes

    grid = sns.catplot(x='User', kind='count', data=df)
    ax = grid.axes[0, 0]
    ax.bar_label(ax.containers[0])
    
  • seaborn.barplot

    这将返回Axes,但不汇总计数,因此在标记之前先计算Series.value_countsax.containers[0]

    counts = df.User.value_counts().rename_axis('user').reset_index(name='count')
    
    ax = sns.barplot(x='user', y='count', data=counts)
    ax.bar_label(ax.containers[0])
    

如果您使用的是hue

  • hue曲线图将包含在多个条形组中,因此需要迭代ax.containers

    ax = sns.countplot(x='User', hue='C', data=df)
    for container in ax.containers:
        ax.bar_label(container)
    

这篇关于在海运条形图顶部显示计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆