# Filling the histogram with Value/Sum

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided

Dear All,
I have a data file, and I want to sum all the data then fill the value/Sum.

in.open(“test.dat”);
double x;
double Sum=0.;

``````TFile *file = new TFile("test.root","RECREATE");
TH1F *hist = new TH1F("test","test",10,0.,10);

while (!in.eof())
{
in >>x;
Sum=Sum+x;
cout<<x<<"  "<<Sum<<"  "<<x/Sum<<endl;

hist->Fill(x/Sum);
}
``````

but this is wrong as I can see, because it fill before it complete the summing process.
can anyone help me in this issue please.

Hello,

I suggest using a vector to store the value of x, then fill the histogram by the vector and the sum:

``````	in.open(“test.dat”);
double x;
double Sum=0.;
TFile *file = new TFile("test.root","RECREATE");
TH1F *hist = new TH1F("test","test",10,0.,10);
std::vector<double> x_vector;
x_vector.clear( );
while (!in.eof())
{
in >>x;
Sum=Sum+x;
cout<<x<<"  "<<Sum<<"  "<<x/Sum<<endl;
x_vector . push_back( x );
}
for ( int i=0; i<x_vector.size( ); i++ )
hist -> Fill( x_vector[i]/Sum );

``````

On the other hand, if you want to scale your histogram by 1/Sum. You can fill the histogram with x, then use hist → Scale( 1/Sum );

``````	in.open(“test.dat”);
double x;
double Sum=0.;
TFile *file = new TFile("test.root","RECREATE");
TH1F *hist = new TH1F("test","test",10,0.,10);
while (!in.eof())
{
in >>x;
Sum=Sum+x;
cout<<x<<"  "<<Sum<<"  "<<x/Sum<<endl;
hist -> Fill( x );
}
hist -> Scale( 1/Sum );
``````

I missed the scaling idea.

Well, I made a mistake my explaining my issue.
After plotting the original histogram , I need to divide the total input in one bin (Y value) over the (X) value rather than the scaling factor.

Is this possible?

Can you describe a bit more. I don’t really get your idea.
Do you mean, for example, you have a histogram of 4 bins, ranging from 0 to 4, and the bins are:

``````[0-1] [1-2] [2-3] [3-4]
``````

And let assume that the 3rd bins, `[2-4]`, has the content of 5 (y=5).
The what do you want to do with it? divide the content by 2 so you will get y = 2.5?

yes, i need to do what you described.

Then you may try the `SetBinContent` function (together with `GetBinContent`)
It looks like this:

``````// Get number of bins
int n_bins = hist -> GetNbinsX( );
for ( int i=1; i<=n_bins; i++ )
{
// read the bin content, aka y value
float bcont = hist->GetBinContent( i );
// determine the x value of the bin, here I use the central x.
// here x_max and x_min is the maximum/minimum value on the x axis.
float bval = ( i-0.5 )( x_max-x_min ) / n_bins;
// then modify the bin content, be careful that bval may be zero in some cases
hist -> SetBinContent( i, bcont/bval );
}
``````