#include#include void plot_histos() { // Create two histograms with some data TH1D* h1 = new TH1D("h1", "Histogram 1", 100, 0, 10); TH1D* h2 = new TH1D("h2", "Histogram 2", 100, 0, 10); for (int i=0; i<10000; i++) { h1->Fill(gRandom->Gaus(5, 1)); h2->Fill(gRandom->Gaus(5, 1.5)); } // Create a canvas to draw on TCanvas* canvas = new TCanvas("canvas", "My Canvas"); // Draw the first histogram h1->Draw(); // Draw the second histogram on top of the first h2->SetLineColor(kRed); h2->DrawCopy("same"); // Save the canvas to a file canvas->SaveAs("histos.png"); }
#includeIn this example, we create two histograms and fill them with some random data. We then create a THStack object and add the two histograms to it. We create a canvas and draw the stacked histogram on it using the DrawCopy method with the "nostack" option to ensure that the histograms are not stacked on top of each other. Finally, we save the canvas as a PNG file. Package library: ROOT#include #include void stack_histos() { // Create two histograms with some data TH1D* h1 = new TH1D("h1", "Histogram 1", 100, 0, 10); TH1D* h2 = new TH1D("h2", "Histogram 2", 100, 0, 10); for (int i=0; i<10000; i++) { h1->Fill(gRandom->Gaus(5, 1)); h2->Fill(gRandom->Gaus(5, 1.5)); } // Create a stacked histogram THStack* stack = new THStack("stack", "Stacked Histogram"); stack->Add(h1); stack->Add(h2); // Create a canvas to draw on TCanvas* canvas = new TCanvas("canvas", "My Canvas"); // Draw the stacked histogram stack->Draw("nostack"); // Save the canvas to a file canvas->SaveAs("stacked.png"); }