【问题标题】:seaborn distribution plot add label for counts per histogram binseaborn 分布图为每个直方图 bin 的计数添加标签
【发布时间】:2019-09-26 03:12:51
【问题描述】:

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

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

应该为每个条添加一个标签,而不是默认分布图:

【问题讨论】:

    标签: python label histogram seaborn distribution


    【解决方案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()
    

    你会得到:

    【讨论】:

    • 不幸的是,这不会为我绘制图像。看起来像添加了矩形。
    • 请再检查一次。
    • 嗯我已经有了%pylab inline Jupiter,所以它应该可以工作的。尽管 seaboard 会很乐意绘制其结果,但您的建议不会为我生成图像。
    • 如果您正在使用 jupyter notebook,请添加 %matplotlib inline