Python Matplotlib 矩形分箱
我有一系列的 (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。
4 个回答
0
你在找的东西是 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.
2
我发现有一个补丁已经提交给matplotlib,但我根据其他示例的代码做了一些调整,以满足我自己的需求。
现在这个直方图是从左下角开始绘制的,这和传统数学中的做法一致(而不是计算机中的方式)。
另外,超出分组范围的数值会被忽略,我使用了一个二维的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
12
Numpy 有一个叫做 histogram2d 的函数,它的说明文档里还告诉你怎么用 Matplotlib 来可视化这个函数的结果。你可以在 imshow 的调用中加上 interpolation=nearest
这个参数,这样就可以关闭插值功能了。