Reputation: 1495
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
Upvotes: 4
Views: 7101
Reputation: 153460
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')
Upvotes: 3