【问题标题】:How do you select a custom bin size for a 2D histogram?如何为 2D 直方图选择自定义 bin 大小?
【发布时间】:2018-11-18 06:52:45
【问题描述】:

在查看this answer 之后,我已经知道如何设置一维直方图的 bin 大小,但我不知道如何为二维直方图执行此操作。我已经参考了二维直方图的 NumpyMatplotlib 页面,但是我所有调整 bin 大小的尝试都不起作用/运行。我希望我的 bin 的长度为 20,宽度为 2。

示例代码:

import numpy as np
import matplotlib.pyplot as plt
import math

dataX = np.random.uniform(-50,50,100)
dataY = np.random.uniform(-50,50,100)

binWidth = 2.0
binLength = 20.0

xMin = min(dataX)
xMax = max(dataX)
yMin = min(dataY)
yMax = max(dataY)

#this and all other similar attempts that I have tried did not run
np.histogram2d(dataX, dataY, bins = np.arange((xMin,xMax + binWidth),(yMin,yMin +binLength),(binWidth,binLength)))

期待您的提示/帮助/建议。

【问题讨论】:

  • 您对np.arange 的使用是错误的。对于hist2d,您可以提供数组而不是元组:bins = [x,y]

标签: python numpy matplotlib


【解决方案1】:

你可以这样做,例如

plt.hist2d(dataX, dataY, bins = [np.arange(xMin, xMax, binWidth), np.arange(yMin, yMax, binLength)])

bins 接受整数或数组来定义 bin 的数量或它们的边,每个它要么在两个维度上一次,要么在一个包含两个条目的列表中,为 x 和 y 提供两个不同的定义。

来自文档:

bins : int or array_like or [int, int] or [array, array], optional

bin 规格:

   If int, the number of bins for the two dimensions (nx=ny=bins).
   If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).
   If [int, int], the number of bins in each dimension (nx, ny = bins).
   If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).
   A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2017-07-05
    • 2011-10-22
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多