gpt4 book ai didi

Python Matplotlib 矩形分箱

转载 作者:IT老高 更新时间:2023-10-28 20:55:18 26 4
gpt4 key购买 nike

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

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。

最佳答案

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

关于Python Matplotlib 矩形分箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2030970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com