相关疑难解决方法(0)

Seaborn:带有频率的countplot()

我有一个带有名为"AXLES"的列的Pandas DataFrame,它可以取3-12之间的整数值.我试图使用Seaborn的countplot()选项来实现以下情节:

  1. 左侧y轴显示数据中出现的这些值的频率.轴延伸为[0%-100%],每10%刻度线.
  2. 右y轴显示实际计数,值对应于由左y轴确定的刻度标记(每10%标记一次).
  3. x轴显示条形图的类别[3,4,5,6,7,8,9,10,11,12].
  4. 条形顶部的注释显示该类别的实际百分比.

下面的代码给出了下面的图表,其中包含实际计数,但我找不到将它们转换为频率的方法.我可以使用频率,df.AXLES.value_counts()/len(df.index)但我不知道如何将这些信息插入Seaborn countplot().

我还找到了注释的解决方法,但我不确定这是否是最佳实现.

任何帮助,将不胜感激!

谢谢

plt.figure(figsize=(12,8))
ax = sns.countplot(x="AXLES", data=dfWIM, order=[3,4,5,6,7,8,9,10,11,12])
plt.title('Distribution of Truck Configurations')
plt.xlabel('Number of Axles')
plt.ylabel('Frequency [%]')

for p in ax.patches:
        ax.annotate('%{:.1f}'.format(p.get_height()), (p.get_x()+0.1, p.get_height()+50))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:

我使用以下代码更接近我需要的东西,使用Pandas的条形图,抛弃Seaborn.感觉就像我使用了很多变通方法,并且必须有一种更简单的方法来实现它.这种方法的问题:

  • orderPandas的条形图功能中没有关键字,因为Seaborn的countplot()有,所以我不能像在countplot()中那样绘制3-12中的所有类别.即使该类别中没有数据,我也需要显示它们.
  • 由于某种原因,辅助y轴会使条形和注释混乱(请参阅在文本和条形图上绘制的白色网格线).

    plt.figure(figsize=(12,8))
    plt.title('Distribution of Truck Configurations')
    plt.xlabel('Number of Axles')
    plt.ylabel('Frequency [%]')
    
    ax = (dfWIM.AXLES.value_counts()/len(df)*100).sort_index().plot(kind="bar", rot=0)
    ax.set_yticks(np.arange(0, 110, 10))
    
    ax2 = ax.twinx()
    ax2.set_yticks(np.arange(0, 110, 10)*len(df)/100)
    
    for p in ax.patches:
        ax.annotate('{:.2f}%'.format(p.get_height()), (p.get_x()+0.15, p.get_height()+1))
    
    Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

python data-visualization matplotlib pandas seaborn

26
推荐指数
3
解决办法
4万
查看次数

标签 统计

data-visualization ×1

matplotlib ×1

pandas ×1

python ×1

seaborn ×1