Matplotlib累积直方图 - 垂直线放置错误还是误解?

时间:2015-04-23 16:05:05

标签: python matplotlib

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

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

enter image description here

请参阅x=1.9处的第2条垂直线?鉴于X中的数据,它不应该是2.1吗?例如,在x = 3时,我将阅读&#34; 3个样本具有值x <= 3.1&#34; ...

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

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

enter image description here

编辑:

我正在使用python 3.4.3&amp; matplotlib 1.4.3

1 个答案:

答案 0 :(得分:3)

如果您未自行设置the bins parameterplt.hist将为您选择(默认情况下为10)二进制文件:

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的左边缘。

相关问题