Histogram trouble -only works in root command line

Hi all, I’m picking up root again after years not using it and I’m stumped as to why my code only works sometimes. I have a histogram saved in a root file and I need to adjust the scaling, etc. on it. I have written the following code:

[quote]#include <TFile.h>
#include <TCanvas.h>
#include <TH1D.h>
#include <TStyle.h>
using namespace std;

void histcreator(){
TFile f(“pdf_25bin.root”);
TH1D h = (TH1D)f.Get(“Primaryenergy”);
cout << h->GetEntries() << endl;
double scalingfactor = 1.0/h->GetEntries();
cout << scalingfactor << endl;

I have this saved as a .C file, which I have been executing in root by using the .X command. When I do this, the couts display the correct information, but the histogram doesn’t draw - it just displays a blank canvas with absolutely nothing on it. Strangely enough, when I copy and paste these commands into the root command line one at a time, the histogram displays perfectly. What is the difference between the command line and saving it as a file and why won’t my histogram draw in the latter case? It’s not a big deal to do this interactively once but I anticipate needing to scale a bunch of different histograms in the future so it would be handy to have a nice little macro to do it.


After “Get”, try to add:
h->SetDirectory(gROOT); // make sure “h” is “retained” when the file is closed or deleted

After “Draw”, try to add:
gPad->Modified(); gPad->Update(); // enforce “physical” drawing

#include “TROOT.h” // for gROOT
#include “TPad.h” // for gPad

See more discussion here: [url]TPad::Update() vs. TPad::Modified()

Basically when using the interpreter, pressing Enter makes the canvases update (as does clicking on a canvas). When running code non-interactively, the canvases only update when certain things happen (e.g. drawing something), so you will generally want to manually call the TPad::Update() method when doing graphical stuff in batch mode.