No bin labels shown

This script:

TH1 *h = new TH1F("h", "title; x; y", 3, 0.5, 3.5);
  h -> Fill(1.0);
  for (unsigned char bin_ind = 1; bin_ind < h -> GetNbinsX() + 1; bin_ind ++)
      h -> GetXaxis() -> SetBinLabel(bin_ind, TString(bin_ind));
  TCanvas * c = new TCanvas("c", "c");
  h -> Draw();

produces the output:

Why are the bin labels not shown?

I’m not 100% sure what you are attempting, but I can tell you what your code does and why there are no bin labels drawn:

Your code loops over all bins with bin numbers smaller than 256 because this is the maximum value of the data type “unsigned char” which you are using. Generally this works but it’s not really a good idea because of problems with higher bin numbers. It would be much better to use a data type with a higher maximum like “int”.

For each bin the bin number is being interpreted as a chararcter according to the standard ASCII table which you can look up here:
As you can see there the first 32 characters correspond to control characters which are not being displayed in a string which is why there are no labels drawn.

I assume you tried to display a string with “1”, “2”, … for each bin. This can be achieved making use of the Form function, which formats a string according to sprintf syntax. Therefore you should change your code to:

h -> GetXaxis() -> SetBinLabel(bin_ind, Form("%d", bin_ind));

In this case the data type of bin_id can be changed to “int” without any further changes, which I suggest too.

1 Like

I imagined TString(2) would produce “2”.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.