如何在条形图顶部添加总数

Huz*_*had 2 python annotations bar-chart dataframe pandas

我想制作数据框的性别列的条形图(有很多行),并且我想在条形顶部显示零和一的计数。我的数据框看起来像这样。

人力资源 舒张压 响应 性别
110.9 64.0 15.2 0
97.0 72.0 19.0 1
89.0 62.5 22.0 0
90.0 105.0 30.0 1
103.0 104.0 24.5 1
100.0 125.0 35.0 0
113.0 102.0 26.5 1

另外,我想将0更改为女性,1更改为男性,如下图所示。我在这个网站上看过类似的问题,但我无法理解其中的逻辑。有人可以帮我吗?

图形

我用来制作此图的代码:

ax = df_1['Gender'].value_counts().plot(kind='bar', figsize=(7, 6), rot=0)
plt.xlabel("Gender")
plt.ylabel("Number of People")
plt.title("Bar Graph of Gender from Training Set A", y = 1.02)
ax.set_xticklabels(('Male', 'Female'))
Run Code Online (Sandbox Code Playgroud)

Huz*_*had 6

尝试这个:

gender = df1['Gender'].value_counts()
plt.figure(figsize=(7, 6))
ax = gender.plot(kind='bar', rot=0, color="b")
ax.set_title("Bar Graph of Gender in Training Set A", y = 1)
ax.set_xlabel('Gender')
ax.set_ylabel('Number of Patients')
ax.set_xticklabels(('Male', 'Female'))

for rect in ax.patches:
    y_value = rect.get_height()
    x_value = rect.get_x() + rect.get_width() / 2
    space = 1
    label = "{:.0f}".format(y_value)
    ax.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va='bottom')
plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

条状图