Python matplotlib 직사각형 비닝
-
19-09-2019 - |
문제
Python의 Matplotlib를 사용하는 2D 히스토그램을 플로팅하려는 일련의 (x, y) 값이 있습니다. 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()
내 자신의 "Binning"방법을 쓰지 않고 Imshow를 사용하지 않고 이미이 작업을 수행 할 수있는 방법이 있어야합니다.
해결책
Numpy에는 호출 된 기능이 있습니다 히스토그램 2D, DocString은 Matplotlib를 사용하여 시각화하는 방법을 보여줍니다. 추가하다 interpolation=nearest
보간을 비활성화하기 위해 imshow 호출에.
다른 팁
나는 matplotlib에 제출 된 패치가 있다는 것을 알고 있지만, 다른 예제에서 코드를 채택하여 내가 가진 몇 가지 요구 사항을 추정했습니다.
이제 히스토그램은 기존 수학에서와 같이 왼쪽 하단 모서리에서 플롯됩니다 (컴퓨팅 아님)
또한 비닝 범위 외부의 값은 무시되고 2D 차원 배열에 2D Numpy 배열을 사용합니다.
데이터 입력을 쌍에서 2 개의 1D 어레이로 변경했습니다. 이것은 데이터가 산란 (x, y) 및 alkike 함수에 제공되는 방법이므로
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
방금 이에 대한 풀 요청을 제출했습니다 https://github.com/matplotlib/matplotlib/pull/805 . 바라건대, 그것은 받아 들여질 것입니다.
~이다 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.
사용 xlim
그리고 ylim
줄거리의 한계를 설정합니다. xlim(-3, 3)
그리고 ylim(-3, 3)
해야합니다.