如何更改Seaborn数据标签以显示两位小数

时间:2018-06-18 13:46:56

标签: python-3.x seaborn

如何在seaborn barplot(或任何情节)中编码数据标签以显示两位小数?

我学会了如何从这篇文章中显示数据标签: Add data labels to Seaborn factor plot

但我无法获得显示数字的标签。

请参阅下面的示例代码:

#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')

感谢您提供的任何帮助

1 个答案:

答案 0 :(得分:1)

使用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')

输出: enter image description here