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.
CodePudding user response:
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:
# Imports.
import matplotlib.pyplot as plt
import seaborn as sns
# Load a dataset and replicate what you have in the question, since you did
# not provide any data to help us help you.
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)
CodePudding user response: