【问题标题】:Display count on top of seaborn barplot在 seaborn 条形图顶部显示计数
【发布时间】:2019-08-01 22:36:25
【问题描述】:

我有一个看起来像这样的数据框:

  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

我正在尝试在“用户”列上显示计数图。代码如下:

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")

输出如下:

但是,我想将字符串“Hello”替换为“用户”列的 value_counts。当我添加代码以将标签添加到图形时:

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")

我得到的输出为:

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    df['User'].value_counts() 将返回一个包含用户列唯一值计数的系列。

    无需详细分析您的代码,您可以通过使用计数器索引 value_counts 的结果来纠正它:

    fig, ax1 = plt.subplots(figsize=(20,10))
    graph = sns.countplot(ax=ax1,x='User', data=df)
    graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
    i=0
    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()[i],ha="center")
        i += 1
    

    使用您的样本数据,它会生成以下图表:

    根据@ImportanceOfBeingErnest 的建议,以下代码使用更简单的代码生成相同的输出,使用高度变量本身而不是索引的 value_counts:

    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,height ,ha="center")
    

    【讨论】:

    • 你可以直接用height代替df['User'].value_counts()[i]
    • 是的,它会使代码更简单。感谢您指出这一点,@ImportanceOfBeingErnest
    【解决方案2】:

    其他解决方案

    #data
    labels=data['Sistema Operativo'].value_counts().index
    values=data['Sistema Operativo'].value_counts().values
    
    plt.figure(figsize = (15, 8))
    ax = sns.barplot(x=labels, y=values)
    for i, p in enumerate(ax.patches):
        height = p.get_height()
        ax.text(p.get_x()+p.get_width()/2., height + 0.1, values[i],ha="center")
    

    Chart Image

    【讨论】:

      【解决方案3】:

      matplotlib 3.4.0 中的新功能

      我们现在可以使用内置的Axes.bar_labelautomatically annotate bar plots,所以我们需要做的就是访问/提取seaborn plot的Axes

      Seaborn 提供了几种绘制计数的方法,每种方法的计数聚合和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,但不会汇总计数,因此在标记ax.containers[0]之前首先计算Series.value_counts

        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)
        

      【讨论】:

        【解决方案4】:

        注意:此解决方案不会尝试在条形顶部显示计数。相反,这个简单的解决方案将打印条内的值。在某些情况下,这可能是一个优雅的解决方案。

        import seaborn as sns
        
        ax=sns.countplot(x=df['category'], data=df);
        for p in ax.patches:
            ax.annotate(f'\n{p.get_height()}', (p.get_x()+0.2, p.get_height()), ha='center', va='top', color='white', size=18)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-06-28
          • 2014-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-10
          相关资源
          最近更新 更多