在尝试使用 matplotlib 的hist
函数绘制累积分布函数 (CDF) 时,最后一点回到零。我阅读了一些线程,解释说这是因为直方图格式,但找不到适合我的案例的解决方案。
这是我的代码:
import matplotlib.pyplot as plt
x = [7.845419,7.593756,7.706831,7.256211,7.147965]
fig, ax=plt.subplots()
ax.hist(x, cumulative=True, normed=1, histtype='step', bins=100, label=('Label-1'), lw=2)
ax.grid(True)
ax.legend(loc='upper left')
plt.show()
Run Code Online (Sandbox Code Playgroud)
产生以下图像
如您所见,在直方图的最后一个 bin 之后阶跃函数变为零,这是不希望的。如何更改我的代码以使 CDF 不会归零?
谢谢
您始终拥有的一个选择是首先计算直方图,然后按照您喜欢的方式绘制结果,而不是依赖plt.hist
.
在这里您将用来numpy.histogram
计算直方图。然后,您可以创建一个数组,其中每个点重复,以获得类似步骤的行为。
import numpy as np
import matplotlib.pyplot as plt
x = [7.845419,7.593756,7.706831,7.256211,7.147965]
h, edges = np.histogram(x, density=True, bins=100, )
h = np.cumsum(h)/np.cumsum(h).max()
X = edges.repeat(2)[:-1]
y = np.zeros_like(X)
y[1:] = h.repeat(2)
fig, ax=plt.subplots()
ax.plot(X,y,label='Label-1', lw=2)
ax.grid(True)
ax.legend(loc='upper left')
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
628 次 |
最近记录: |