【问题标题】:Matplotlib cumulative histogram - vertical line placement bug or misinterpretation?Matplotlib 累积直方图 - 垂直线放置错误或误解?
【发布时间】:2015-04-24 00:26:58
【问题描述】:

我不确定这是否是一个错误,或者我只是误解了 matplotlib 累积直方图的输出。例如,我期望的是“在某个 x 值处,相应的 y 值告诉我有多少个样本

import matplotlib.pyplot as plt

X = [1.1, 3.1, 2.1, 3.9]
n, bins, patches = plt.hist(X, normed=False, histtype='step', cumulative=True)
plt.ylim([0, 5])
plt.grid()
plt.show()

看到x=1.9 的第二条垂直线了吗?考虑到X 中的数据,它不应该是 2.1 吗?例如,在 x=3 时,我会读到“3 个样本的值 x

所以,基本上我所期望的是类似于这个步骤图的东西。

plt.step(sorted(X), range(1, len(X)+1), where='post')
plt.ylim([0, 5])
plt.grid()

编辑:

我正在使用 python 3.4.3 和 matplotlib 1.4.3

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果您没有自己设置the bins parameterplt.hist 将为您选择(默认情况下,10 个)bin:

    In [58]: n, bins, patches = plt.hist(X, normed=False, histtype='step', cumulative=True)
    
    In [59]: bins
    Out[59]: 
    array([ 1.1 ,  1.38,  1.66,  1.94,  2.22,  2.5 ,  2.78,  3.06,  3.34,
            3.62,  3.9 ])
    

    返回值bins 显示了 matplotlib 选择的 bin 的边缘。

    听起来您希望 X 中的值用作 bin 边缘。使用 bins=sorted(X)+[np.inf]:

    import numpy as np
    import matplotlib.pyplot as plt
    
    X = [1.1, 3.1, 2.1, 3.9]
    bins = sorted(X) + [np.inf]
    n, bins, patches = plt.hist(X, normed=False, histtype='step', cumulative=True, 
                                bins=bins)
    plt.ylim([0, 5])
    plt.grid()
    plt.show()
    

    产量

    [np.inf] 使最终 bin 的右边缘延伸到无穷大。 Matplotlib 足够聪明,不会尝试绘制非有限值,所以你看到的只是最后一个 bin 的左边缘。

    【讨论】:

    • 哦,我明白了,这是有道理的——我不知何故错误地认为这将/应该是默认行为。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 2012-12-07
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2012-07-31
    • 2021-08-10
    相关资源
    最近更新 更多