Home | News | Documentation | Download

Fitting root histo of existing rootfile

Hi!
Say I want to fit a gaussian to a histogram which is contained in a rootfile and is named h1.
The code I use is the following (using pyroot):

file = rt.TFile(rootfile, "UPDATE")
file.ls()

histo = file.Get("h1")
histo.Fit("gaus")

file.Write()
file.Close()

This works but it always creates a new histogram with the fit. So I get the original histogram called h1;1 and a copy of the histogram where the fit is shown called h1;2. When I rerun the code with the same rootfile again I get another copy plus the fit h1;3.
How can I write the code so that no copy is created but the fit is shown in the original histogram. And ideally, when I rerun the code, the previous fit should get deleted and the new fit should show (say that in the second run I want to try a landau fit and not a gaussian).

@jonas can you please take look whenever you will have time?

Hi @Jailbone!

You could use TFile::Delete before writing your histogram to delete the existing object cycle from the file:

file = rt.TFile(rootfile, "UPDATE")
file.ls()

histo = file.Get("h1")
histo.Fit("gaus")

file.Delete("histo;1")

file.Write()
file.Close()

Does this give you the desired behavior?

Cheers,
Jonas

PS:
This is how I created a file with a histogram to test the solution with:

void create_histo() {

    TFile f("test.root","RECREATE");

    TH1D h("histo", "histo", /*nbins=*/100, /*xmin=*/-3, /*xmax=*/3);
    h.FillRandom("gaus", /*nsamples=*/5000);

    f.Write();
}