TTree::Draw with Same Option

I have a collection of TTrees with the same branch names. I am trying to loop over the trees and make one histogram per branch showing the values from each TTree for that branch, overlaid on the same plot.

Here is an example that shows what I am trying to do (but does not work):

#include <vector>

void macro() {
    std::vector<TTree*> trees;

    float v1;
    float v2;
    TRandom* generator = new TRandom();

    for (int i = 0; i < 5; i++) {
        // make a new tree
        TTree* atree = new TTree("t1", "a tree");
        atree->Branch("v1", &v1);
        atree->Branch("v2", &v2);

        // fill tree with some values
        for (int j = 0; j < 100; j++) {
            v1 = generator->Gaus(i, 1.0);
            v2 = generator->Gaus(i, 1.0);
            atree->Fill();
        }

        // add tree to list of trees
        trees.push_back(atree);
    }

    // make distributions comparing v1, v2 from each tree
    // define binning for each variable 
    TH1F* hv1 = new TH1F("hv1", "histogram1", 10, 0, 10.0);
    TH1F* hv2 = new TH1F("hv2", "histogram2", 5, 0, 10.0);

    // hv1 and hv2 should have a curve from each tree!
    for (size_t i = 0; i != trees.size(); i++) {
        if (i == 0) {
            trees[i]->Draw("v1>>hv1", "", "goff");
            trees[i]->Draw("v2>>hv2", "", "goff");
        }
        else {
            trees[i]->Draw("v1>>hv1", "", "goff sames");
            trees[i]->Draw("v2>>hv2", "", "goff sames");
        }
    }
    hv1->Draw();
    hv2->Draw();
}

Typically hv1 and hv2 contain only one curve. What is the proper way to do this?

Hi,
I think the problem is you don’t change the name of the histograms so you overwrite them, and you only plot the last one.
I changed a bit your code using the Form() method and two TH1F vectors.

I don’t know if is the smartest way to do it

Cheers,
Stefano

.macro.c (1.6 KB)

Otherwise if you want just draw and don’t have the histograms saved, just remove the goff option, draw the first histogram on hv1 then superimpose the other histograms.

S

 // hv1 and hv2 should have a curve from each tree!
    for (size_t i = 0; i != trees.size(); i++) {
        if (i == 0) {
            trees[i]->Draw("v1>>hv1", "", "");
        }
        else {
            trees[i]->Draw("v1", "", " same");
        }
    }

Thanks, I ended up using Form() for histogram names and making vectors of histograms. It seems there is no way to do it without storing intermediate histograms.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.