seaborn分布图,添加每个直方图bin计数的标签

时间:2019-05-08 11:33:04

标签: python histogram seaborn distribution

我如何才能为分布图添加一个标签,其中包含每个容器中的元素数?

import seaborn as sns, numpy as np
sns.set(); np.random.seed(0)
x = np.random.randn(100)
ax = sns.distplot(x)

应该为每个柱添加标签,而不是默认的分布图: enter image description here

1 个答案:

答案 0 :(得分:1)

一个大概的解决方案可能是:

import seaborn as sns, numpy as np
import matplotlib.pyplot as plt

# add the following line if working on jupyter notebook
%matplotlib inline

sns.set()
np.random.seed(0)
x = np.random.randn(100)
ax = sns.distplot(x)

s = 0

for p in ax.patches:
    s+= p.get_height()

for p in ax.patches: 
    ax.text(p.get_x() + p.get_width()/2.,
            p.get_height(),
            '{}'.format(int(p.get_height()*100/s)), 
            fontsize=14,
            color='red',
            ha='center',
            va='bottom')
plt.show()

您会得到:

enter image description here