Logo ROOT   6.07/09
Reference Guide
Namespaces
ratioplot.py File Reference

Namespaces

 ratioplot
 

Detailed Description

View in nbviewer Open in SWAN Display two histograms and their ratio.

This program illustrates how to plot two histograms and their ratio on the same canvas. Original macro by Olivier Couet.

1 
2 from ROOT import TCanvas, TColor, TGaxis, TH1F, TPad
3 from ROOT import kBlack, kBlue, kRed
4 
5 
6 def createH1():
7  h1 = TH1F("h1", ("Two gaussian plots and their ratio; x title; h1 and h2"
8  " histograms"), 100, -5, 5)
9  h1.SetLineColor(kBlue+1)
10  h1.SetLineWidth(2)
11  h1.FillRandom("gaus")
12  h1.GetYaxis().SetTitleSize(20)
13  h1.GetYaxis().SetTitleFont(43)
14  h1.GetYaxis().SetTitleOffset(1.55)
15  h1.SetStats(0)
16  return h1
17 
18 
19 def createH2():
20  h2 = TH1F("h2", "h2", 100, -5, 5)
21  h2.FillRandom("gaus")
22  h2.SetLineColor(kRed)
23  h2.SetLineWidth(2)
24  return h2
25 
26 
27 def createRatio(h1, h2):
28  h3 = h1.Clone("h3")
29  h3.SetLineColor(kBlack)
30  h3.SetMarkerStyle(21)
31  h3.SetTitle("")
32  h3.SetMinimum(0.8)
33  h3.SetMaximum(1.35)
34  # Set up plot for markers and errors
35  h3.Sumw2()
36  h3.SetStats(0)
37  h3.Divide(h2)
38 
39  # Adjust y-axis settings
40  y = h3.GetYaxis()
41  y.SetTitle("ratio h1/h2 ")
42  y.SetNdivisions(505)
43  y.SetTitleSize(20)
44  y.SetTitleFont(43)
45  y.SetTitleOffset(1.55)
46  y.SetLabelFont(43)
47  y.SetLabelSize(15)
48 
49  # Adjust x-axis settings
50  x = h3.GetXaxis()
51  x.SetTitleSize(20)
52  x.SetTitleFont(43)
53  x.SetTitleOffset(4.0)
54  x.SetLabelFont(43)
55  x.SetLabelSize(15)
56 
57  return h3
58 
59 
60 def createCanvasPads():
61  c = TCanvas("c", "canvas", 800, 800)
62  # Upper histogram plot is pad1
63  pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
64  pad1.SetBottomMargin(0) # joins upper and lower plot
65  pad1.SetGridx()
66  pad1.Draw()
67  # Lower ratio plot is pad2
68  c.cd() # returns to main canvas before defining pad2
69  pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
70  pad2.SetTopMargin(0) # joins upper and lower plot
71  pad2.SetBottomMargin(0.2)
72  pad2.SetGridx()
73  pad2.Draw()
74 
75  return c, pad1, pad2
76 
77 
78 def ratioplot():
79  # create required parts
80  h1 = createH1()
81  h2 = createH2()
82  h3 = createRatio(h1, h2)
83  c, pad1, pad2 = createCanvasPads()
84 
85  # draw everything
86  pad1.cd()
87  h1.Draw()
88  h2.Draw("same")
89  # to avoid clipping the bottom zero, redraw a small axis
90  h1.GetYaxis().SetLabelSize(0.0)
91  axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "")
92  axis.SetLabelFont(43)
93  axis.SetLabelSize(15)
94  axis.Draw()
95  pad2.cd()
96  h3.Draw("ep")
97 
98 # To hold window open when running from command line
99 # text = raw_input()
100 
101 
102 if __name__ == "__main__":
103  ratioplot()
Author
Michael Moran

Definition in file ratioplot.py.