【发布时间】:2016-01-15 17:12:10
【问题描述】:
我有一个 Pandas DataFrame,其中有一列名为“AXLES”,它可以取 3-12 之间的整数值。我正在尝试使用 Seaborn 的 countplot() 选项来实现以下情节:
- 左 y 轴显示这些值在数据中出现的频率。轴延伸为 [0%-100%],每 10% 处有刻度线。
- 右 y 轴显示实际计数,值对应于左 y 轴确定的刻度线(每 10% 标记一次。)
- x 轴显示条形图的类别 [3、4、5、6、7、8、9、10、11、12]。
- 条形顶部的注释显示该类别的实际百分比。
以下代码为我提供了下面的图,其中包含实际计数,但我找不到将它们转换为频率的方法。我可以使用 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))
编辑:
使用 Pandas 的条形图,抛弃 Seaborn,我更接近于我需要的代码。感觉就像我使用了很多解决方法,并且必须有一种更简单的方法来做到这一点。这种方法的问题:
- Pandas 的条形图函数中没有
order关键字,因为 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))
【问题讨论】:
-
为什么不将刻度标签除以总数来获得频率?
-
我尝试使用
vals = ax.get_yticks()和ax.set_yticks(vals/len(df))。但是,一旦我这样做了,由于绘图的实际 y 比例,所有标签最终都位于原点附近的最底部。显然我的方法是错误的。你会怎么做? -
你救了我的命 :D :D :D
标签: python pandas matplotlib data-visualization seaborn