gpt4 book ai didi

python - Matplotlib CDF 回到零

转载 作者:行者123 更新时间:2023-12-02 00:03:56 29 4
gpt4 key购买 nike

尝试使用 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()

生成以下图像

enter image description here

如您所见,阶跃函数在直方图的最后一个 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()

enter image description here

关于python - Matplotlib CDF 回到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040683/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com