python bar chart total label on bar

Viewed 44
plt.figure(figsize = (8,5))
sns.countplot(data = HRdfMerged, x = 'Gender', hue='Attrition').set_title('Gender vs Attrition')

I'm having a hard time adding a label to the top of my bar that states the total number. I have tried many different ways but can't get it right. Im using matplotlib. Picture of bar chart added.

bar chart image

2 Answers

Once you have called sns.countplot, we will explore the list ax.patches to get information from the bars and place the texts you want:

enter image description here


# Imports.
import matplotlib.pyplot as plt
import seaborn as sns

# Load a dataset to replicate what you have in the question.
data = sns.load_dataset("titanic")
fig, ax = plt.subplots() # Use the object-oriented approach with Matplotlib when you can.
sns.countplot(data=data, x="class", hue="who", ax=ax)
ax.set_title("title goes here")
fig.show()

# For each bar, grab its coordinates and colors, find a suitable location
# for a text and place it there.
for patch in ax.patches:
    x0, y0 = patch.get_xy()   # Bottom-left corner. 
    x0 += patch.get_width()/2 # Middle of the width.
    y0 += patch.get_height()  # Top of the bar
    color = patch.get_facecolor()
    ax.text(x0, y0, str(y0), ha="center", va="bottom", color="white", clip_on=True, bbox=dict(ec="black",
                                                                                              fc=color))

Play around with the kwargs of ax.text to get the result you prefer. An alternative:

ax.text(x0, y0, str(y0), ha="center", va="bottom", color=color, clip_on=True)

enter image description here

You can also use the convenient Axes.bar_label method here to do this in just a couple lines.

Since seaborn does not return the BaContainer objects to us, we will need to access them from the Axes object via Axes.containers attribute.

import matplotlib.pyplot as plt
import seaborn as sns

data = sns.load_dataset("titanic")
fig, ax = plt.subplots()
sns.countplot(data=data, x="class", hue="who", ax=ax)

for bar_contain in ax.containers:
    ax.bar_label(bar_contain)

enter image description here

Related