Take a part of a TH2F

Dear experts,
I have a filled TH2F and I want to take only a subset of it. This subset is defined as a rectangular region in bin space, for example I want a new histogram that is equal to the original but with x bins from firstbinx to lastbinx, and y bins from firstbiny to lastbiny of the original one.

What is the best implementation? Is it already implemented somewhere?

see example below

Rene

void t2d() { TH2F *h1 = new TH2F("h1","source",40,-4,4,40,-40,40); h1->FillRandom("gaus"); Int_t firstx = 12, lastx=22, firsty=11, lasty=25; Int_t nx = lastx-firstx+1, ny = lasty-firsty+1; Double_t xmin = h1->GetXaxis()->GetBinLowEdge(firstx); Double_t xmax = h1->GetXaxis()->GetBinUpEdge(lastx); Double_t ymin = h1->GetYaxis()->GetBinLowEdge(firsty); Double_t ymax = h1->GetYaxis()->GetBinUpEdge(lasty); TH2F *h2 = new TH2F("h2","subset",nx,xmin,xmax,ny,ymin,ymax); for (Int_t i=0;i<nx;i++) { for (Int_t j=0;j<ny;j++) { h2->SetBinContent(i+1,j+1,h1->GetBinContent(firstx+i,firsty+j)); } } TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->Divide(1,2); c1->cd(1); h1->Draw("box"); c1->cd(2); h2->Draw("box"); }

[quote=“brun”]see example below

Rene

void t2d() { TH2F *h1 = new TH2F("h1","source",40,-4,4,40,-40,40); h1->FillRandom("gaus"); Int_t firstx = 12, lastx=22, firsty=11, lasty=25; Int_t nx = lastx-firstx+1, ny = lasty-firsty+1; Double_t xmin = h1->GetXaxis()->GetBinLowEdge(firstx); Double_t xmax = h1->GetXaxis()->GetBinUpEdge(lastx); Double_t ymin = h1->GetYaxis()->GetBinLowEdge(firsty); Double_t ymax = h1->GetYaxis()->GetBinUpEdge(lasty); TH2F *h2 = new TH2F("h2","subset",nx,xmin,xmax,ny,ymin,ymax); for (Int_t i=0;i<nx;i++) { for (Int_t j=0;j<ny;j++) { h2->SetBinContent(i+1,j+1,h1->GetBinContent(firstx+i,firsty+j)); } } TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->Divide(1,2); c1->cd(1); h1->Draw("box"); c1->cd(2); h2->Draw("box"); } [/quote]

thanks, do you think it is so userfull to implement it in a GetSlice class method?

you can also do it this way (simply setting a range)

Rene

void t2da() { TH2F *h1 = new TH2F("h1","source",40,-4,4,40,-40,40); h1->FillRandom("gaus"); TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->Divide(1,2); c1->cd(1); h1->Draw("box"); Int_t firstx = 12, lastx=22, firsty=11, lasty=25; TH2F *h2 = (TH2F*)h1->Clone("h2"); h2->GetXaxis()->SetRange(firstx,lastx); h2->GetYaxis()->SetRange(firsty,lasty); c1->cd(2); h2->Draw("box"); }

[quote=“brun”]you can also do it this way (simply setting a range)

Rene

void t2da() { TH2F *h1 = new TH2F("h1","source",40,-4,4,40,-40,40); h1->FillRandom("gaus"); TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->Divide(1,2); c1->cd(1); h1->Draw("box"); Int_t firstx = 12, lastx=22, firsty=11, lasty=25; TH2F *h2 = (TH2F*)h1->Clone("h2"); h2->GetXaxis()->SetRange(firstx,lastx); h2->GetYaxis()->SetRange(firsty,lasty); c1->cd(2); h2->Draw("box"); } [/quote]

no, this is not my case, I need a real slice of the original histogram, not only a visual zooming