【问题标题】:Python Matplotlib rectangular binningPython Matplotlib 矩形分箱
【发布时间】:2011-01-03 02:39:15
【问题描述】:

我有一系列 (x,y) 值,我想绘制一个使用 python 的 matplotlib 的二维直方图。使用 hexbin,我得到如下信息: 但我正在寻找这样的东西: 示例代码:

from matplotlib import pyplot as plt
import random

foo = lambda : random.gauss(0.0,1.0)

x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]

pairs = zip(x,y)

#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)

#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
    if (ybins == None): ybins = xbins
    xdata, ydata = zip(*pairsData)
    xmin,xmax = min(xdata),max(xdata)
    xwidth = xmax-xmin
    ymin,ymax = min(ydata),max(ydata)
    ywidth = ymax-ymin
    def xbin(xval):
        xbin = int(xbins*(xval-xmin)/xwidth)
        return max(min(xbin,xbins-1),0)
    def ybin(yval):
        ybin = int(ybins*(yval-ymin)/ywidth)
        return max(min(ybin,ybins-1),0)
    hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
    for x,y in pairsData:
        hist[ybin(y)][xbin(x)] += 1
    extent = (xmin,xmax,ymin,ymax)
    return hist,extent

#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')

plt.draw()
plt.show()

似乎应该已经有一种方法可以做到这一点,而无需编写我自己的“分箱”方法并使用 imshow。

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    Numpy 有一个名为 histogram2d 的函数,它的文档字符串还向您展示了如何使用 Matplotlib 对其进行可视化。在 imshow 调用中添加 interpolation=nearest 以禁用插值。

    【讨论】:

      【解决方案2】:

      我意识到有一个补丁提交到 matplotlib,但我采用了另一个示例中的代码来满足我的一些需求。

      现在直方图是从左下角绘制的,就像在传统数学中一样(不是计算)

      此外,分箱范围之外的值将被忽略,我使用 2d numpy 数组作为二维数组

      我将数据输入从对更改为两个一维数组,因为这是将数据提供给 scatter(x,y) 和类似函数的方式

      def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
          """ Helper function to do 2D histogram binning
              x, y are  lists / 2D arrays 
              x_range and yrange define the range of the plot similar to the hist(range=...) 
              xbins,ybins are the number of bins within this range.
          """
      
          pairsData = zip(x,y)
      
          if (ybins == None):
              ybins = xbins
          xdata, ydata = zip(*pairsData)
          xmin,xmax = x_range
          xmin = float(xmin)
          xmax = float(xmax)
      
          xwidth = xmax-xmin
          ymin,ymax = y_range    
          ymin = float(ymin)
          ymax = float(ymax)
          ywidth = ymax-ymin
      
          def xbin(xval):
              return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval  < xmax else xbins-1 if xval ==xmax else None
      
      
          def ybin(yval):
              return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval  < ymax else ybins-1 if yval ==ymax else None
      
          hist = numpy.zeros((xbins,ybins)) 
          for x,y in pairsData:
              i_x,i_y = xbin(x),ybin(ymax-y)
              if i_x is not None and i_y is not None:
                  hist[i_y,i_x] += 1 
      
          extent = (xmin,xmax,ymin,ymax)
      
          return hist,extent
      

      【讨论】:

        【解决方案3】:

        我刚刚为此 https://github.com/matplotlib/matplotlib/pull/805 提交了拉取请求。希望它会被接受。

        【讨论】:

          【解决方案4】:

          matplotlib.pyplot.hist 是您要查找的内容吗?

          >>> help(matplotlib.pyplot.hist)
          Help on function hist in module matplotlib.pyplot:
          
          hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto
          m=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=Fa
          lse, hold=None, **kwargs)
              call signature::
          
                hist(x, bins=10, range=None, normed=False, cumulative=False,
                     bottom=None, histtype='bar', align='mid',
                     orientation='vertical', rwidth=None, log=False, **kwargs)
          
              Compute and draw the histogram of *x*. The return value is a
              tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
              [*patches0*, *patches1*,...]) if the input contains multiple
              data.
          

          【讨论】:

          • 这是一维的。我正在寻找一个二维直方图,类似于 imshow() 或 hexbin()
          • hist 可以做二维数据,除非我不明白你的意思。如果您发布了一些示例数据,那可能会有所帮助。
          • Hist 适用于 2D 数据,但它只是创建两个交错的 1D 直方图。
          【解决方案5】:

          使用xlimylim 设置绘图的限制。 xlim(-3, 3)ylim(-3, 3) 应该这样做。

          【讨论】:

            猜你喜欢
            • 2010-12-03
            • 2021-09-10
            • 1970-01-01
            • 1970-01-01
            • 2013-05-11
            • 2013-12-15
            • 2017-06-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多