pythonpandasdataframeannotationsbar-chart

How to add the total count on top of Bar graph


I want to make a bar graph of Gender column of my data frame (with many rows) and I want to show the count of Zeros and Ones on top of bars. My data frame looks like this.

HR DBP Resp Gender
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

Also, I want to change 0 to Female and 1 to male, as shown in fig below. I looked similar questions on this website but I am unable to understand the logic. Can someone help me out?

Graph

The code I used to make this graph:

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'))

Solution

  • Tried this:

    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()
    

    The output:

    Bar Graph