【问题标题】:Plotting histrogram from numpy array从numpy数组绘制直方图
【发布时间】:2015-10-14 07:04:27
【问题描述】:

我需要从通过卷积输入数组和过滤器获得的二维数组创建直方图。 bins 应该是数组中值的范围。

我试着按照这个例子:How does numpy.histogram() work? 代码是这样的:

import matplotlib.pyplot as plt
import numpy as np
plt.hist(result, bins = (np.min(result), np.max(result),1))
plt.show()

我总是收到此错误消息:

AttributeError: bins must increase monotonically.

感谢您的帮助。

【问题讨论】:

  • 如果你看(np.min(result), np.max(result),1),值会单调增加吗?
  • 我的例子的最小值/最大值是:'(0.0, 254.999999745)'

标签: python arrays numpy histogram


【解决方案1】:

您实际上是在指定三个 bin,其中第一个 bin 是 np.min(result),第二个 bin 是 np.max(result),第三个 bin 是 1。您需要做的是提供您希望 bin 在直方图中的位置,并且此必须按递增顺序排列。我的猜测是你想从np.min(result)np.max(result) 中选择垃圾箱。 1 似乎有点奇怪,但我会忽略它。此外,您想绘制一维值的直方图,但您的输入是二维的。如果您想在一维中绘制数据在所有唯一值上的分布,则需要在使用np.histogram解开您的二维数组。为此使用np.ravel

现在,我想向您推荐np.linspace。您可以指定最小值和最大值以及在均匀间隔之间的任意数量的点。所以:

bins = np.linspace(start, stop)

startstop 之间的默认点数是 50,但您可以覆盖它:

bins = np.linspace(start, stop, num=100)

这意味着我们在 startstop 之间产生 100 个点。

因此,请尝试这样做:

import matplotlib.pyplot as plt
import numpy as np
num_bins = 100 # <-- Change here - Specify total number of bins for histogram
plt.hist(result.ravel(), bins=np.linspace(np.min(result), np.max(result), num=num_bins)) #<-- Change here.  Note the use of ravel.
plt.show()

【讨论】:

  • 我在实现您的示例时收到此错误消息:'UserWarning: 2D hist input should be nsamples x nvariables.这看起来是转置的(形状为 212 x 254)'。
  • 我补充说最小/最大值是浮点类型。
  • @Litwos 你没有说你的输入是二维的。你没有提到这一点。您要绘制 2D 直方图还是 1D?
  • 这是一个二维数组,我在第一篇文章中提到过。
  • 那么您想要二维直方图还是一维直方图?
猜你喜欢
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多