Skip to content

Instantly share code, notes, and snippets.

@yuasatakayuki
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuasatakayuki/980e8af9c7f49e8ebe0f to your computer and use it in GitHub Desktop.
Save yuasatakayuki/980e8af9c7f49e8ebe0f to your computer and use it in GitHub Desktop.
RubyROOT example: fill histogram then fit with gaussian+pol1
require "RubyROOT"
include Root
include RootApp
inputFile="histogram_sample.data"
outputPDFFile="histogram_sample.pdf"
#create an instance of histogram
hist=TH1D.create("hist","Histogram",512,0,512)
#read text data that contains counts of each histogram bin
open(inputFile).each_with_index(){|line,i|
binIndex=hist.GetXaxis().FindBin(i)
hist.SetBinContent(binIndex,line.to_i)
}
#draw with statistical error
canvas=TCanvas.create("c","Canvas",600,600)
hist.Draw("e")
#fit the 40K line
f_pol1_gaus=TF1.new("f_pol1_gaus","gaus(0)+pol1(3)",150,200)
f_pol1_gaus.SetParameter(0,200)
f_pol1_gaus.SetParameter(1,180)
f_pol1_gaus.SetParameter(2,10)
f_pol1_gaus.SetParameter(3,200)
f_pol1_gaus.SetParameter(4,-1)
f_pol1_gaus.SetLineColor(KOrange)
hist.Fit("f_pol1_gaus","","",150,200)
#save as pdf
hist.SaveAs(outputPDFFile)
#print fit statistics
puts "NDF = #{f_pol1_gaus.GetNDF()}"
puts "Chi2 = #{"%.2f"%f_pol1_gaus.GetChisquare()}"
#run ROOT GUI event loop
canvas.Update
run_app
@yuasatakayuki
Copy link
Author

See http://ytkyk.info/blog/2015/06/22/rubyroot_example_fit_histogram/ for Japanese description of this example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment