【问题标题】:Get correct value counts for corresponding x tick label [duplicate]获取相应x刻度标签的正确值计数[重复]
【发布时间】: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


【解决方案1】:

这个错误是由于要注释的值的顺序与value_counts()得到的顺序不同造成的。所以我们可以通过聚合频率并按索引重新排序来处理它。对于数据,我使用泰坦尼克号数据来创建代码。

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

sns.set_theme(style="darkgrid")

titanic = sns.load_dataset("titanic")

fig, ax1 = plt.subplots(figsize = (15,10))

countplot_attrition = sns.countplot(data=titanic, x='class', ax=ax1)
countplot_attrition.set_xticklabels(countplot_attrition.get_xticklabels())

for k,p in enumerate(countplot_attrition.patches):
    height = p.get_height()
    countplot_attrition.text(p.get_x()+p.get_width()/2, height + 0.1,
                             titanic['class'].value_counts().sort_index()[k], ha="center")

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2011-03-28
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多