Draw histograms on the same canvas with random colors


ROOT Version: 6.18/04
Platform: f30
Compiler: 9.2.1 20190827


Dear co-rooters,

I am trying to plot histograms from a root file on the same canvas. The histograms should have a random colour, using TRandom, however I can only draw them with one color. I guess I should somehow change the seed, but I have no idea how to do it. Any idea?

My code is the following

void plot_histos(TString filename_in, TString histo_name, TString filename_out){

	TFile *fin = new TFile(filename_in, "OPEN");
	TCanvas *c = new TCanvas();
	
	//string h_name = filename_in;
	for (int i=1; i<11; ++i){
	    
        //TH1F *h = (TH1F*) fin->Get(histo_name);
        TH1F *h = (TH1F*) fin->Get(TString::Format("%s_%03i", histo_name.Data(), i) );	
	
	    TRandom *r = new TRandom();
	    int color = (int) ((113-51)*r->Rndm()+51);
	    h->SetLineColor(color);
	
	    h->Draw("histo same");
	
	}
}

An the result that I get is this

Imgur

Any idea on how to plot in different and random colours?

Thanks in advance!

P.S.: I am attaching a root file with the histograms

background_2205_h58_dummy_pi_adc.root (28.4 KB)

Hi,
put the TRandom initialization outside the for loop, otherwise you reset the seed every time.
In the declaration of the TRandom you can set the seed. If you use 0 is chosen randomly at every launch of the program.

Cheers
Stefano

Thank you very much for your help!!!
It works!!

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