How to plot a 2d histogram?

1.3k views Asked by At

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...

1

There are 1 answers

2
Viktor Kerkez On

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.