python - matplotlib 标准化直方图

标签 python matplotlib histogram

我正在尝试使用 matplotlib 绘制直方图的一部分。

我不想绘制具有大量离群值和大值的整个直方图,而是只想关注一小部分。原始直方图如下所示:

hist(data, bins=arange(data.min(), data.max(), 1000), normed=1, cumulative=False)
plt.ylabel("PDF")

enter image description here

聚焦之后是这样的:

hist(data, bins=arange(0, 121, 1), normed=1, cumulative=False)
plt.ylabel("PDF")

enter image description here

请注意,最后一个 bin 被拉伸(stretch),所有 Y 刻度中最差的被缩放,因此总和正好为 1(因此根本不考虑当前范围之外的点)

我知道我可以通过在整个可能范围内绘制直方图然后将轴限制到我感兴趣的部分来实现我想要的,但是它浪费了很多时间来计算我不会使用的 bin/无论如何都要看看。

hist(btsd-40, bins=arange(btsd.min(), btsd.max(), 1), normed=1, cumulative=False)
axis([0,120,0,0.0025])

enter image description here

是否有一种快速简便的方法来仅绘制聚焦区域,但仍能获得正确的 Y 比例?

最佳答案

为了绘制直方图的一个子集,我认为您无法计算整个直方图。

您是否尝试过使用 numpy.histogram 计算直方图,然后使用 pylab.plot 或其他工具绘制区域?即

import numpy as np
import pylab as plt

data = np.random.normal(size=10000)*10000

plt.figure(0)
plt.hist(data, bins=np.arange(data.min(), data.max(), 1000))

plt.figure(1)
hist1 = np.histogram(data, bins=np.arange(data.min(), data.max(), 1000))
plt.bar(hist1[1][:-1], hist1[0], width=1000)

plt.figure(2)
hist2 = np.histogram(data, bins=np.arange(data.min(), data.max(), 200))
mask = (hist2[1][:-1] < 20000) * (hist2[1][:-1] > 0)
plt.bar(hist2[1][mask], hist2[0][mask], width=200)

原始直方图: Original histogram

手动计算直方图: Histogram calculated manually

手动计算直方图,裁剪: Histogram calculated manually, cropped (注意:值较小是因为 bin 较窄)

关于python - matplotlib 标准化直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283921/

相关文章:

python 将文本文件解包到单独的变量中

python - 如何使用分类 sklearn 波士顿住房数据集通过 matplotlib 绘制线性图

r - 带有抖动地毯的直方图

python - 如何验证 python 的 IOBase 的实现?

python - Holoviews Label 的旋转文本

python - pyinstaller 和 matplotlib 超出最大递归深度

python - 无法使用 ffmpeg 保存 Matplotlib 动画

r - 将直方图绘制为线条

r - 将R中的多个图另存为.jpg文件,怎么办?

python - numpy C API 中的 import_array 如何工作?