Hello everyone
I’m trying to draw three histograms on one Canvas. Unfortunately, the resulting histogram is empty. There are no errors in the console. I checked and the original histograms contain correct data, the X axis is in the same range. The titles of the X and Y axis are the same.
Do you have any advice?
Cheers,
Rafal
#include <TFile.h>
#include <TH1.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TStyle.h>
#include <iostream>
#include <vector>
#include <TApplication.h>
#include <TKey.h>
#include <TClass.h>
void drawHistograms() {
// ROOT file list
std::vector<std::string> fileNames = {
"Electron1MeV.root", "Electron2MeV.root", "Electron5MeV.root"
};
// Histogram names in ROOT files
std::vector<std::string> histNames = {
"E e- 1MeV", "E e- 2MeV", "E e- 5MeV"
};
// Creating canvas
TCanvas *c = new TCanvas("c", "Combined Histograms", 800, 600);
// Colors for histograms
int colors[] = {kRed, kBlue, kGreen};
// Loop over files
for (size_t i = 0; i < fileNames.size(); ++i) {
// Open ROOT file
TFile *file = TFile::Open(fileNames[i].c_str());
if (!file || file->IsZombie()) {
std::cerr << "Cannot open file: " << fileNames[i] << std::endl;
continue;
}
// Get histogram
TH1 *hist = dynamic_cast<TH1*>(file->Get(histNames[i].c_str()));
if (!hist) {
std::cerr << "Cannot find histogram in file: " << fileNames[i] << std::endl;
file->Close();
continue;
}
// Set histogram attributes
hist->SetLineColor(colors[i]);
hist->SetLineWidth(2);
// Draw histogram
if (i == 0) {
hist->Draw();
hist->GetXaxis()->SetTitle("The value of the angle in degrees");
hist->GetYaxis()->SetTitle("Number of Cherenkov photons");
} else {
hist->Draw("SAME");
}
// Close file
file->Close();
}
// Update canvas
c->Update();
}
int main(int argc, char **argv) {
TApplication theApp("App", &argc, argv);
drawHistograms();
theApp.Run();
return 0;
}
Thank you. I am already drawing, but unfortunately not correctly. Only one histogram from the last loaded file is drawn. The Y axis is filled incorrectly.
I don’t know that. My goal was to draw three histograms simultaneously on one Canvas to visually compare them. Each energy was supposed to be represented by a different color of the lines.
Thank you very much. You are very helpful!
If I understand correctly, the first histogram is drawn on the Canvas first, then the second, and finally the third? That is why only the legend of the third histogram is visible because the third one has covered the previous ones?
Cheers,
Rafal