【问题标题】:Unequal width binned histogram in pythonpython中不等宽的分箱直方图
【发布时间】:2017-01-08 09:59:39
【问题描述】:

我有一个数组,其中存储了概率值。有些值为 0。我需要绘制一个直方图,以便每个 bin 中有相同数量的元素。我尝试使用 matplotlibs hist 函数,但这让我决定垃圾箱的数量。我该如何绘制这个?(正常的情节和历史工作,但它不是需要的)

我有 10000 个条目。只有 200 的值大于 0 并且介于 0.0005 和 0.2 之间。这种分布甚至不是 0.2 只有一个元素具有,而 2000 大约具有 0.0005 的值。所以绘制它是一个问题,因为箱子的宽度必须不等且元素数量相同

【问题讨论】:

  • 向我们展示您的代码,以便我们为您提供帮助。
  • eq_bins = [np.percentile(data, q) for q in range(0,100)] 是我最初尝试进行分箱的方法。

标签: python matplotlib histogram probability bins


【解决方案1】:

这个任务对我来说没有多大意义,但是下面的代码可以,我理解为要做的事情。

我还认为代码的最后几行是您真正想要做的。使用不同的 bin-width 来提高可视化效果(但不要针对每个 bin 内等量样本的分布)!我用astroml's hist with method='blocks' (astropy supports this too)

代码

# Python 3 -> beware the // operator!

import numpy as np
import matplotlib.pyplot as plt
from astroML import plotting as amlp

N_VALUES = 1000
N_BINS = 100

# Create fake data
prob_array = np.random.randn(N_VALUES)
prob_array /= np.max(np.abs(prob_array),axis=0)  # scale a bit

# Sort array
prob_array = np.sort(prob_array)

# Calculate bin-borders,
bin_borders = [np.amin(prob_array)] + [prob_array[(N_VALUES // N_BINS) * i] for i in range(1, N_BINS)] + [np.amax(prob_array)]

print('SAMPLES: ', prob_array)
print('BIN-BORDERS: ', bin_borders)

# Plot hist
counts, x, y = plt.hist(prob_array, bins=bin_borders)
plt.xlim(bin_borders[0], bin_borders[-1] + 1e-2)
print('COUNTS: ', counts)
plt.show()


# And this is, what i think, what you really want

fig, (ax1, ax2) = plt.subplots(2)
left_blob = np.random.randn(N_VALUES/10) + 3
right_blob = np.random.randn(N_VALUES) + 110
both = np.hstack((left_blob, right_blob))  # data is hard to visualize with equal bin-widths

ax1.hist(both)
amlp.hist(both, bins='blocks', ax=ax2)
plt.show()

输出

【讨论】:

  • 澄清问题。我有 10000 个条目。只有 200 的值大于 0 并且介于 0.0005 和 0.2 之间。这种分布甚至不是 0.2 只有一个元素具有,而 2000 大约具有 0.0005 的值。所以绘制它是一个问题,因为箱子的宽度必须不相等,元素数量相等。
  • 上面绘制了元素数量相等的不等箱,但我怀疑这是否有用。你的问题措辞真的很糟糕。我现在假设,你想要一个经典的直方图(没有每个 bin 中元素数量相等的约束;但是不等 bin 以提高可视化质量。如果是这样的话,你应该这么说......这有点可悲因为措辞不好而做不必要的工作,但是……看看第二种方法,使用 astroml(这也在 astropy 中实现)。
  • 抱歉措辞。谢谢
  • @duckvader Sooo... 我更新了代码以显示经典直方图和 method='blocks' 的 astroml 直方图之间的不同行为!这就是你想要达到的目标吗?
  • 好的。 Google 贝叶斯块直方图以获取更多信息(并了解它是否是解决您问题的有效方法)。
猜你喜欢
  • 2022-12-21
  • 2012-09-05
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2021-10-29
相关资源
最近更新 更多