Histogram to ascii

Dear root users and developers,

I’m surprised that there is no standard feature in root of converting at least 1d histograms into plain ascii file. I would expect that such a feature would be very much appreciated by many physicists especially of old generation who are not familiar with C++ and with root itself, but may still use it for simple analysis by dumping histograms into an ascii file and then processing it as they are used to with gnuplot or Origin or whatever other data plotting programs.

Why not to add, for example, an option “ASCII” to “SaveAs” context menu entry for a histogram which would save plain two columns: x and y without any additional text like “fsumw” etc?

Of course it’s easy for any programmer to write a simple macro which does it, but why not to make it a part of root?

Another question to all: does anybody have a macro which reads all 1D histograms from a .root file and writes each of them to a separate ascii file as described above: just two columns x and y?

Thanks for help…
Yuri.

1 Like

Hi,

hist->Print("all"); > somefile.txt

(Pay attention to space between ; and >)

Will dump out all the bin contents. As far as a script that does this automatically, that’s a little more tricky as I don’t know how to redirect output to a file named in a variable.

Cheers,
Charles

Thanks, I know about this command. However, it does not what I want. The output is like:

...
 fSumw[196]=972, x=195.5
 fSumw[197]=1208, x=196.5
 fSumw[198]=1579, x=197.5
 fSumw[199]=1833, x=198.5
 ...

whereas I want:

...
972 195.5
1208 196.5
1579 197.5
1833 198.5
...

Regards,
Yuri.

I think it’s time to learn a bit of perl/sed etc…

Here is the macro you are looking for:

void h12ascii (TH1* h)
{
   Int_t n = h->GetNbinsX();
   
   for (Int_t i=1; i<=n; i++) {
      printf("%g %g\n",
             h->GetBinLowEdge(i)+h->GetBinWidth(i)/2,
             h->GetBinContent(i));
   }
}

Use it this way:

root [0] .x h12ascii.C(hpx); > h2ascii.dat
2 Likes

I vote for including couet’s little code as part of TH1 and TH2 (need to add another loop) classes.
We really do need such a functionality.

Better yet, write a method which will output into a csv format – including a header with histogram
metadata.

Naïvely, if someone asked me to write a function that printed a histogram “in ascii”, I would write one that prints an ascii-art histogram, with little stacks of symbols for the height of each bin. If printing to a csv (or other tabular text) format, I would like it not to have a more specific name than “ascii”.

While I’m talking about it, an ascii-art mode for printing would actually be useful sometimes. I’ve used the gnuplot “dumb” terminal to make quick plots through non-X-forwarded ssh connections. Something similar for ROOT was talked about enthusiastically 4 years ago: [url]lsRoot to dump root contents to terminal

Jean-François