【问题标题】:Counts of each bin in a distplotdistplot 中每个 bin 的计数
【发布时间】:2020-09-29 07:40:31
【问题描述】:

有什么方法可以获取 sns.distplot 中每个 bin 的计数吗?比如,

sns.distplot(df.intervalL, kde=False, bins=[0,25,50,75,100], color='navy',rug=False, norm_hist=False) 

我想获取每个 bin 中的计数。 谢谢

【问题讨论】:

    标签: python seaborn histogram


    【解决方案1】:

    sns.distplot 返回创建绘图的ax。这些条形可在ax.containers[0] 中作为矩形访问,您可以调查它们的高度。

    请注意,在 Seaborn 0.11 中,sns.distplot 已替换为 sns.histplot。 (下面的代码仍然适用于 sns.distplot,显示该函数已被弃用的警告。)

    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    data = np.random.randn(100, 10).cumsum(axis=1).ravel()
    data -= data.min()
    data  *= 100 / data.max()
    bins = [0,25,50,75,100]
    ax = sns.histplot(data, kde=False, bins=bins, color='navy')
    for bar, b0, b1 in zip(ax.containers[0], bins[:-1], bins[1:]):
        print(f'{b0:3d} - {b1:3d}: {bar.get_height():4.0f}')
    

    输出:

      0 -  25:   57
     25 -  50:  513
     50 -  75:  382
     75 - 100:   48
    

    如果您只想要没有绘图的值,您也可以调用counts, _ = np.histogram(data, bins=bins) (docs)。

    【讨论】:

    • 是的。我想将计数值和绘图作为 3D 条形图。非常感谢!
    猜你喜欢
    • 2015-10-22
    • 2018-06-22
    • 1970-01-01
    • 2017-10-12
    • 2023-03-26
    • 2018-04-19
    • 2020-12-10
    • 2019-07-24
    • 1970-01-01
    相关资源
    最近更新 更多