THStack not working

ROOT Version: 6.24/06
Platform: Ubuntu
Compiler: Not Provided


I want to save a single object that contains multiple histograms that are overlayed. To be specific:

  • I do not want to DRAW them with ->Draw(“same”), I want to WRITE them, so that I can access them later.
  • I do not want to add or stack them, I want them to be overlayed, analogous to what ->Draw(“same”) does

I tried using a THStack, but either I am using it wrong, or there is a bug. Example code (sorry for the format, I don’t see the setting to use code formating) “test.C”:

// Include header files
#include <TH1.h>
#include <TH2.h>
#include <TH3.h>
#include "TFile.h"
#include "THStack.h"

// Main function
void test(){
	
	// Initialize output file
    TFile * file_out0 = new TFile("test.root","recreate");
   
	// Initialize histograms
	TH1F * histo_one = new TH1F("one","one",100,0,100);
	TH1F * histo_two = new TH1F("two","two",100,0,100);
				
	// Fill histograms
	for(int i=1; i <= 100; i++){
		histo_one->SetBinContent(i,1);
		histo_two->SetBinContent(i,2);
	}
	
	// For diagnosis, write the histograms individually		
	histo_one->Write();
	histo_two->Write();					
	
	// Initialize a THStack
	THStack * histo_multipleDrawnHistos = new THStack("histo_multipleDrawnHistos","histo_multipleDrawnHistos");
	// Add the histograms using the option "NOSTACK"
	histo_multipleDrawnHistos->Add(histo_one,"NOSTACK");
	histo_multipleDrawnHistos->Add(histo_two,"NOSTACK");
	
	// Write THStack
	histo_multipleDrawnHistos->Write();
	
	// Close and return
	file_out0->Close();			
	return;
	
	// Error description: In the THStack, the histograms are stacked, although the option "NOSTACK" is provided.
		
}

What am I doing wrong?

When you create a new post, this link is automatically added (you deleted it, since it’s not showing), where you can see that to write code here, you enclose it in ``` (three single left quotation marks).
As for your question, you need to add the “nostack” option when you Draw the THStack; do not include “nostack” when adding the histograms to the THStack, I think that is simply ignored as it is not a valid option for drawing histograms.
When Adding to a THStack, you can specify formatting options like showing markers, line, fill… for any/all of the histos if you want (for example if you want different options for each histogram; otherwise you can specify these options later when drawing the stack --in addition to nostack–, and all will look the same).

Thanks for the answer!

The official THStack class reference (not allowed to post link here, sorry) specifies that “NOSTACK” is a drawing option and that the member function

void THStack::Add(TH1* h1, Option_t * ="")

can take a drawing option as an argument, so it should work.

Nevertheless - if there is any other handy method to do this, I will take it.