【问题标题】:Matplotlib CDF goes back to zeroMatplotlib CDF 归零
【发布时间】:2017-09-04 16:00:06
【问题描述】:

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

生成以下图像

如您所见,阶跃函数在直方图的最后一个 bin 之后变为零,这是不希望的。如何更改我的代码以使 CDF 不会回到零?

谢谢

【问题讨论】:

  • 嗨@ImportanceOfBeingErnest。感谢您的回答。我在问题中添加了完整的代码。
  • 我明白了。我以minimal reproducible example 的形式编辑了问题,使问题变得清晰。 (而且我想请您下次提问时提供这种形式的问题,因为这样可以节省大家很多时间。)
  • 查看 OP stackoverflow.com/q/10690094/3797285 给出的 hack

标签: python pandas matplotlib


【解决方案1】:

您始终有一个选择是先计算直方图,然后按照您喜欢的方式绘制结果,而不是依赖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()

【讨论】:

  • 这个问题看起来更容易理解。谢谢。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 2012-03-11
  • 2017-12-13
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
相关资源
最近更新 更多