Python Matplotlib binning rectangulaire
-
19-09-2019 - |
Question
J'ai une série de (x, y) des valeurs que je veux tracer un histogramme 2d de l'utilisation de matplotlib de python. En utilisant hexbin, je reçois quelque chose comme ceci: Mais je cherche quelque chose comme ceci: Exemple de code:
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()
Il semble que il devrait déjà être un moyen de le faire sans écrire ma propre méthode « binning » et en utilisant imshow.
La solution
Numpy a une fonction appelée histogram2d , dont docstring vous montre également comment le visualiser en utilisant Matplotlib. Ajouter interpolation=nearest
à l'appel imshow pour désactiver l'interpolation.
Autres conseils
Je me rends compte qu'il ya un patch soumis à Matplotlib, mais j'adopté le code de l'autre exemple pour accomoder quelques besoins que j'avais.
maintenant l'histogramme est tracée à partir du coin inférieur gauche, comme dans les mathématiques classiques (non informatique)
En outre, les valeurs en dehors de la plage de binning sont ignorés et j'utiliser un tableau 2d numpy pour le tableau à deux dimensions
I changé l'entrée de données à partir de paires de deux tableaux 1D puisque ceci est la quantité de données est fourni à disperser (x, y) et des fonctions semblables
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
Je viens de soumettre une demande de traction pour cette https://github.com/matplotlib/matplotlib/ tirer / 805 . Si tout va bien, il sera accepté.
est matplotlib.pyplot.hist
ce que vous cherchez?
>>> 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.
Utilisez xlim
et ylim
pour définir les limites de la parcelle. xlim(-3, 3)
et ylim(-3, 3)
devraient le faire.