Minimal program to create histograms from a file with root
We needed to create a histogram from some output of a python program. Therefore I wrote a minimal root program to read in the data from a file and save the histogram as a pdf.
The datafile should contain one entry per row. Save the following source code as e.g. histogram.c and then start root with
root -b -q 'histogram.C("filename")'
Here is the sourcecode:
#include <TCanvas.h>
#include <TH1.h>
#include <iostream.h>
#include <Riostream.h>
#include "Math/PdfFuncMathCore.h"
int main(){
histogram("test")
}
void histogram(char* fileName) {
gROOT->Reset();
TCanvas *c1 = new TCanvas("c1","c1",800,800);
TH1I *histo = readDataToHist(fileName);
c1->cd(1);
histo->Draw();
c1->Update();
c1->Print("histogram.pdf","Portrait pdf");
}
TH1I* readDataToHist(char* fileName)
{
ifstream in;
in.open(fileName);
Double_t bin;
Int_t nlines = 0;
Int_t x_min = 0;
Int_t x_max = 10;
TH1I *histo = new TH1I("h1","Histogram Title", 100,x_min,x_max);
while(1)
{
in >> bin;
if (!in.good()) break;
//cout << "bin: " << bin << '\n';
histo->Fill(bin);
nlines++;
}
in.close();
return histo;
}