How to read a .dat file and plot as histogram

Please provide the following information:


ROOT Version (e.g. 6.12/02): 5.34
Platform, compiler (e.g. CentOS 7.3, gcc6.2):

Good evening everyone,
I am trying to open a .dat file made by two columns “energy” and “counts”. then I need to read this two columns file and draw an histogram to plot as x=energy, y=counts.
I tried something like this, but it does not work:

TString dir_inp=("path_to_file");
TString filename_germ = ("filename.dat");

TString dir_out = ("path_to_output");
TString filename_out = ("file.root");

void search_peaks(){
    Double_t x, y;
    Int_t nlines =0;
    TFile *finp = new TFile(dir_out + filename_out);
    TH1D *h1 = new TH1D("h1", "E spectrum", 20000, 0, 20000);

    while (1) {
        in >> x >>y;
        if(!in.good()) break;
        if (nlines < 5) printf("x=%8f, y=%8f, x, y);
        h1 -> Fill(x, y);
        nlines++;    
    }
    printf("found %d points\n", nlines);
    in.close
}

I suppose that I need to include some for loop to read the two column file, but I am not sure how to go ahead.
Any help is very much appreciated.
thank you


Try:

{
  TGraph *g = new TGraph("path_to_file/filename.dat");
  g->SetTitle("E spectrum;Energy;Counts");
  g->Draw("AL*");
}

and/or:

{
  TH1D *h1 = new TH1D("h1", "E spectrum;Energy;Counts", 20000, 0., 20000.);
  TTree *t = new TTree("t", "t"); // a temporary tree
  t->ReadFile("path_to_file/filename.dat", "x/D:y");
  t->Project("h1", "x", "y");
  delete t; // no longer needed
  h1->Draw("HIST");
}

Hi,

given that you are using a very recent version of ROOT, you can take advantage of the latest features, such as TDataFrame.

auto tdf = ROOT::Experimental::TDF::MakeCsvDataFrame("filename.dat",false, ' ');
auto h = tdf.Histo2D("Col0","Col1");
h->Draw();

Cheers,
Danilo

Thank you very much. it was very helpful

Thank you very much for your help