【发布时间】:2021-10-22 23:37:24
【问题描述】:
我正在尝试在 Seaborn 的酒吧顶部添加计数。
我尝试了一个数字,下面的代码有效。
fig, ax = plt.subplots(figsize=(20,10))
countplot_age = sns.countplot(ax=ax,x='Age', data=data4cap)
countplot_age.set_xticklabels(countplot_age.get_xticklabels(),rotation=90)
i=18
for p in countplot_age.patches:
height = p.get_height()
countplot_age.text(p.get_x()+p.get_width()/2, height + 0.1, data4cap['Age'].value_counts()[i],ha="center")
i += 1
plt.show()
Countplot with values on top of bar
但是,在下一个情节中,我遇到了问题,因为 X 刻度标签按顺序返回 'Yes', 'No' while value_counts 返回 - No 2466 和 Yes 474。
[返回唯一值(也是 x-tick 标签)和 value_counts 函数][2]
并且使用相同的代码,我现在在条形顶部得到了错误的 value_counts。
fig,ax1 = plt.subplots(figsize = (15,10))
countplot_attrition = sns.countplot(data = data4cap, x = 'Attrition', ax= ax1)
countplot_attrition.set_xticklabels(countplot_attrition.get_xticklabels())
i=0
for p in countplot_attrition.patches:
height = p.get_height()
countplot_attrition.text(p.get_x()+p.get_width()/2, height + 0.1,
data4cap.Attrition.value_counts()[i], ha="center")
i += 1
plt.show()
[条形顶部的值不正确][3]
在这个实例中,我很容易通过在 value_counts 中将“升序”参数指定为 True 来解决这个问题。
但这让我想知道,如果在其他情况下不只有两个值,我必须以某种方式将 ticklabels 映射到 value_counts。刻度标签返回不可下标的文本对象。
我该怎么做?
Correct counts on top of bars, unique and value_count returns, incorrect counts on top of bars
【问题讨论】:
-
这个answer 在副本中是当前应该完成的方式。更新到
matplotlib 3.4.2,然后在剧情之后你只需要countplot_attrition.bar_label(countplot_attrition.containers[0])。
标签: python pandas matplotlib seaborn