I have a TH2D which I’m fitting by first getting the ProfileX, and then fitting this. I want to access the stats box from this fit and draw it on the plot where I want, but I can’t work out how to do this.
Here’s my MWE, I tried TPaveStats *s = (TPaveStats*)p->FindObject("stats"); but it doesn’t find anything.
void MWE(){
gStyle->SetOptStat(1110);
gStyle->SetOptFit(0001);
double x1=0.08;
double x2=0.26;
double y1=0.80;
double y2=0.98;
TH2F* h = new TH2F("h","h",100,50,150,200,100,300);
TRandom3 *myRNG=new TRandom3();
myRNG->SetSeed(1);
for(int ii=0;ii<1000;ii++)
{
double rand = myRNG->Gaus(100,10);
double rand2 = myRNG->Gaus(2,0.01);
h->Fill(rand,rand2*rand);
}
TCanvas* c = new TCanvas("c","c",900,700);
h->Draw("colz");
TProfile* p = h->ProfileX();
p->Draw("same");
TF1* f = new TF1("f","[0]*x+[1]",50,150);
p->Fit(f);
f->SetLineWidth(5);
f->Draw("same");
/*
TPaveStats *s = (TPaveStats*)p->FindObject("stats");
s->SetName("29");
s->SetX1NDC(x1);
s->SetX2NDC(x2+0.06);
s->SetY1NDC(y1-0.01);
s->SetY2NDC(y2);
s->SetOptStat(0);
s->SetOptFit(1);
c->Modified();
c->Update();*/
}
thank you for your question. You have to change: f->Draw(“same”); to option “sames” and it should work.
Here is the documentation for your future reference: ROOT: TPaveStats Class Reference
and: “When a histogram is drawn with the option “SAME”, the statistics box is not drawn. To force the statistics box drawing with the option “SAME”, the option “SAMES” must be used.”
To get the stats box, this works perfectly but it leaves the stats box when I only want the fit box. I don’t want to change the gStyle at the beginning because it’s part of a longer macro that produces a lot of plots
void MWE(){
gStyle->SetOptStat(1110);
gStyle->SetOptFit(0001);
double x1=0.08;
double x2=0.26;
double y1=0.80;
double y2=0.98;
TH2F* h = new TH2F("h","h",100,50,150,200,100,300);
TRandom3 *myRNG=new TRandom3();
myRNG->SetSeed(1);
for(int ii=0;ii<1000;ii++)
{
double rand = myRNG->Gaus(100,10);
double rand2 = myRNG->Gaus(2,0.01);
h->Fill(rand,rand2*rand);
}
TCanvas* c = new TCanvas("c","c",900,700);
h->Draw("colz");
TProfile* p = h->ProfileX();
// p->Draw("sames");
TF1* f = new TF1("f","[0]*x+[1]",50,150);
f->SetLineWidth(5);
p->Fit(f,"","sames");
c->Modified();
c->Update();
TPaveStats *s = (TPaveStats*)p->FindObject("stats");
s->SetName("29");
s->SetX1NDC(x1);
s->SetX2NDC(x2+0.06);
s->SetY1NDC(y1-0.01);
s->SetY2NDC(y2);
s->SetOptStat(0);
s->SetOptFit(1);
c->Modified();
c->Update();
}