Python Matplotlib прямоугольный binning

У меня есть серия (x, y) значения, что я хочу вывести 2-ю гистограмму на печать использования matplotlib Python. Используя 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()

Кажется, что должен уже быть способ сделать это, не пишущий мой собственный "binning" метод и с помощью imshow.

19
задан Glorfindel 31 May 2019 в 04:08
поделиться

2 ответа

NUMPY имеет функцию под названием Histogram2d , чья DOCSTRING также показывает, как визуализировать его с помощью MATPLOTLIB. Добавить Интерполяцию = ближайший на Imshow Call для отключения интерполяции.

12
ответ дан 30 November 2019 в 05:06
поделиться

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.
0
ответ дан 30 November 2019 в 05:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: