void histcomp() { gROOT->SetBatch(kTRUE); // Open file TFile *f = new TFile("SimAnasen1.root"); // Get trees (MAKE SURE names are correct) TTree *tree1 = (TTree*)f->Get("tree"); TTree *tree2 = (TTree*)f->Get("tree2"); if (!tree1 || !tree2) { printf("Error: could not find trees. Check names!\n"); return; } // Create output directory (overwrite-safe) gSystem->Exec("mkdir -p plots"); // Get list of branches TObjArray *branches = tree1->GetListOfBranches(); int nBranches = branches->GetEntries(); //int nBranches = 1; // Loop over branches for (int i = 0; i < nBranches; i++) { TBranch *br = (TBranch*)branches->At(i); TString name = br->GetName(); //printf("Processing branch: %s\n", name.Data()); // Create histograms (auto-range using Draw first) TString h1name = "h1_" + name; TString h2name = "h2_" + name; // Temporary draw to get range tree1->Draw(name, "", "goff"); double min = fmax(tree1->GetMinimum(name), tree2->GetMinimum(name)); double max = fmin(tree1->GetMaximum(name), tree2->GetMaximum(name)); //if (min == max) continue; // skip constant branches // Expand range slightly double margin = 0.1 * (max - min); min -= margin; max += margin; TH1D *h1 = new TH1D(h1name, name, 100, min, max); TH1D *h2 = new TH1D(h2name, name, 100, min, max); // Fill histograms tree1->Draw(name + ">>" + h1name, "", "goff"); tree2->Draw(name + ">>" + h2name, "", "goff"); // Style h1->SetLineColor(kRed); h1->SetLineWidth(2); h2->SetLineColor(kBlue); h2->SetLineWidth(2); // Normalize (optional but useful) //if (h1->GetEntries() > 0) h1->Scale(1.0 / h1->GetEntries()); //if (h2->GetEntries() > 0) h2->Scale(1.0 / h2->GetEntries()); // Canvas TCanvas *c = new TCanvas("c", name, 900, 600); c->SetRightMargin(0.18); c->Modified(); c->Update(); h1->SetTitle(name + ";"+name+";Counts"); h1->Draw("HIST"); h2->Draw("HIST SAME"); gPad->Update(); TPaveStats *st = (TPaveStats*)h1->FindObject("stats"); st->SetX1NDC(0.85); // New X start (left) st->SetY1NDC(0.5); // New Y start (bottom) st->SetX2NDC(0.98); // New X end (right) st->SetY2NDC(0.8); // New Y end (top) st->Draw(); gPad->Modified(); gPad->Update(); // Legend TLegend *leg = new TLegend(0.65 + .2,0.75 + .1,0.88 + .1,0.88 + .1); leg->AddEntry(h1, "tree1", "l"); leg->AddEntry(h2, "tree2", "l"); leg->Draw(); // Save plot (overwrite each run) TString filename = "plots/" + name + ".png"; c->SaveAs(filename); //c->SetLogx(0); //c->SetLogy(0); // Optional: save log plots as well c->SetLogx(1); c->SetLogy(1); h1->SetTitle(name + " (log);"+name+";Counts"); c->SaveAs("plots/" + name + "_log.png"); // Clean up delete c; delete h1; delete h2; } printf("Done! Plots saved in ./plots/\n"); }