4

How do I code data labels in a seaborn barplot (or any plot for that matter) to show two decimal places?

I learned how to show data labels from this post: Add data labels to Seaborn factor plot

But I can't get the labels to show digits.

See example code below:

#make the simple dataframe
married = ['M', "NO DATA", 'S']
percentage = [68.7564554, 9.35558, 21.8879646]
df = pd.DataFrame(married, percentage)
df.reset_index(level=0, inplace=True)
df.columns = ['percentage', 'married']

#make the bar plot
sns.barplot(x = 'married', y = 'percentage', data = df)
plt.title('title')
plt.xlabel('married')
plt.ylabel('Percentage')

#place the labels
ax = plt.gca()
y_max = df['percentage'].value_counts().max() 
ax.set_ylim(1)
for p in ax.patches:
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' % 
    int(p.get_height()), 
        fontsize=12, color='red', ha='center', va='bottom')

Thank you for any help you can provide

Jordan
  • 1,415
  • 3
  • 18
  • 44

1 Answers1

3

Use, string formatting with https://docs.python.org/3.4/library/string.html#format-specification-mini-language:

married = ['M', "NO DATA", 'S']
percentage = [68.7564554, 9.35558, 21.8879646]
df = pd.DataFrame(married, percentage)
df.reset_index(level=0, inplace=True)
df.columns = ['percentage', 'married']

#make the bar plot
sns.barplot(x = 'married', y = 'percentage', data = df)
plt.title('title')
plt.xlabel('married')
plt.ylabel('Percentage')

#place the labels
ax = plt.gca()
y_max = df['percentage'].value_counts().max() 
ax.set_ylim(1)
for p in ax.patches:
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), '{0:.2f}'.format(p.get_height()), 
        fontsize=12, color='red', ha='center', va='bottom')

Output: enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • Thank you @ScottBoston. I couldn't find anything in the seaborn docs. Did I miss it? Do you have some docs to point me to learn what you just did? – Jordan Jun 18 '18 at 14:07
  • @Jordan Well, this isn't really a Seaborn issue. It is doing string formatting in python. – Scott Boston Jun 18 '18 at 14:13