0

I'm plotting a set of sns countplots with 6 different plots, and I'd like to add data labels to all of them without repeating the process. All of the other questions solve the problem for only one plot.

At the last part of the code (for p in ax.patches...) I'd expect the labels to appear on the top of the bars. But nothing happened. It works with only one plot, but not with several plots. This is the result I wanted, but for all of them at once:

enter image description here

This is the result I get (no data labels for any plot):

enter image description here

What am I doing wrong? Is there any easier way of doing it?

# creating the plots
fig, ([ax1, ax2], [ax3, ax4], [ax5, ax6]) = plt.subplots(nrows=3, ncols=2, figsize=(20,15))

sns.countplot(x='sex', data=df, order=df['sex'].value_counts().index, ax=ax1).set(title='Clients by Gender')
sns.countplot(x='age_range', data=df, ax=ax2).set(title='Clients by Age')
sns.countplot(x='children', data=df, ax=ax3).set(title='Clients by Children')
sns.countplot(x='region', data=df, order=df['region'].value_counts().index, ax=ax4).set(title='Clients by Region')
sns.countplot(x='smoker', data=df, order=df['smoker'].value_counts().index, ax=ax5).set(title='Clients by Smoker Option')
sns.countplot(x='bmi_range', data=df, order=df['bmi_range'].value_counts().index, ax=ax6).set(title='Clients by BMI')


for p in ax.patches:
  height = p.get_height()
  ax.text(x=p.get_x()+p.get_width()/2, y=height+20, s='{:.0f}'.format(height), ha='center')

plt.show()



0 Answers0