1

Essentially i need to add several 2d histograms together but im not sure how to do this. Before when i did it for a single histogram i did it like this...

enter for i in range(0,BMI[ind_2008].shape[0]):

id_temp=ID[ind_2008[i]]     
ind_2009_temp=np.where(ID[ind_2009] == id_temp)
actual_diff=BMI[ind_2008[i]]-BMI[ind_2009[ind_2009_temp]]
diff=np.abs(BMI[ind_2008][i]-BMI_p1)
pdf_t, bins_t=np.histogram(diff,bins=range_v-1,range=(0,range_v))
if i == 0:
    pdf=pdf_t
    pdf[:]=0.0
pdf=pdf+pdf_t

bincenters = 0.5*(bins_t[1:]+bins_t[:-1])
fig3=plt.figure()
plt.plot(bincenters,pdf)

Heres the code i have for the 2d histogram.

for i in range(0,BMI[ind_2008].shape[0]):
    diff_BMI=np.abs(BMI[ind_2008][i]-BMI_p1)
    diff_DOB=np.abs(dob_j[ind_2008][i]-dob_jwp1)
    hist=np.histogram2d(diff_BMI,diff_DOB,bins=(35,1000))
    if i == 0:
        pdf=hist
        pdf[:]=0.0
        pdf=pdf+hist
fig3=plt.figure()
plt.plot(pdf)

As the code is at the moment i get an error message saying 'tuple object does not support item assignment' I understand what the error message means but im not sure how to correct it. Any help is appreciated...

blablabla
  • 304
  • 1
  • 8
  • 18

1 Answers1

1

The histogram2d function returns a triple:

H : ndarray, shape(nx, ny)
    The bi-dimensional histogram of samples `x` and `y`. Values in `x`
    are histogrammed along the first dimension and values in `y` are
    histogrammed along the second dimension.
xedges : ndarray, shape(nx,)
    The bin edges along the first dimension.
yedges : ndarray, shape(ny,)
    The bin edges along the second dimension.

So your function call should look like:

H, xedges, yedges = np.histogram2d(diff_BMI, diff_DOB, bins=(35,1000))

And then you can do your manipulation with the histogram H. But keep in mind that it's a two dimensional array, and not a one dimensional one, as in the case of the np.histogram function.

Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Im a little confused as to what the 'H, xedges, yedges =' actually does. Could you explain it to me? – blablabla Aug 29 '13 at 10:24
  • 1
    @blablabla The same thing as with the `np.histogram` does. If you take a look at your code, you have a line: `pdf_t, bins_t = np.histogram(...)` which means that the `histogram` function returns two values which you store in `pdf_t` and `bins_t` variables. `np.histogram2d` returns 3 values, which in this case get stored in `H`, `xedges` and `yedges` variables. But you can call the variables whatever you want. – Viktor Kerkez Aug 29 '13 at 10:30