import numpy as np
import matplotlib.pyplot as plt
# some fake data
data = np.random.randn(1000)
# evaluate the histogram
values, base = np.histogram(data, bins=40)
#evaluate the cumulative
cumulative = np.cumsum(values)
# plot the cumulative function
plt.plot(base[:-1], cumulative, c='blue')
#plot the survival function
plt.plot(base[:-1], len(data)-cumulative, c='green')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Some fake data:
data = np.random.randn(1000)
sorted_data = np.sort(data) # Or data.sort(), if data can be modified
# Cumulative counts:
plt.step(sorted_data, np.arange(sorted_data.size)) # From 0 to the number of data points-1
plt.step(sorted_data[::-1], np.arange(sorted_data.size)) # From the number of data points-1 to 0
plt.show()
你很亲密。您不应该使用plt.hist作为numpy.histogram,它提供值和存储箱,这样您就可以轻松地绘制累积:
使用直方图确实是不必要的繁重和不精确(binning使数据变得模糊):您可以对所有x值进行排序:每个值的索引是较小的值的数目。这个更短更简单的解决方案如下:
此外,更合适的绘图样式实际上是
plt.step()
,而不是plt.plot()
,因为数据位于离散位置。结果是:
您可以看到,它比EnricoGiampieri的答案的输出更粗糙,但这是真正的直方图(而不是它的近似、模糊版本)。
PS:正如SebastianRaschka所指出的,理想情况下,最后一点应该显示总计数(而不是总计数-1)。这可以通过以下方式实现:
在
data
中有太多的点,如果不缩放,效果是不可见的,但是当数据只包含几个点时,总计数的最后一个点确实很重要。在与@EOL进行了决定性的讨论之后,我想使用随机高斯样本作为摘要发布我的解决方案(左上角):
相关问题 更多 >
编程相关推荐