首页 > 解决方案 > seaborn 分布图为每个直方图 bin 的计数添加标签

问题描述

如何让 seaborn 为包含每个 bin 的元素数量的分布图添加标签?

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

应该为每个条添加一个标签,而不是默认分布图: 在此处输入图像描述

标签: pythonlabelhistogramseaborndistribution

解决方案


一个粗略的解决方案可能是:

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()

你得到:

在此处输入图像描述


推荐阅读