forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTRatioPlot.cxx
More file actions
1748 lines (1364 loc) · 53.6 KB
/
TRatioPlot.cxx
File metadata and controls
1748 lines (1364 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @(#)root/gpad:$Id$
// Author: Paul Gessinger 25/08/2016
/*************************************************************************
* Copyright (C) 1995-2024, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TRatioPlot.h"
#include "TColor.h"
#include "TROOT.h"
#include "TBrowser.h"
#include "TH1.h"
#include "TF1.h"
#include "TPad.h"
#include "TString.h"
#include "TMath.h"
#include "TGraphAsymmErrors.h"
#include "TGraphErrors.h"
#include "TGaxis.h"
#include "TLine.h"
#include "TVirtualFitter.h"
#include "TFitResult.h"
#include "THStack.h"
#include "TStyle.h"
/** \class TRatioPlot
\ingroup gpad
Class for displaying ratios, differences and fit residuals.
RatioPlot is a helper class designed to draw ratios; it is not meant to be a persistent
object on its own. Therefore, saving a TRatioPlot in a ROOT file (or exporting it directly
as a PDF or PNG) does not make sense, because it is not a self-contained entity like a TH1
or a TGraph. TRatioPlot is specifically designed to arrange pads, which becomes evident
when inspecting the pad contents (using gPad->ls()): multiple pads and axes are created.
To save its visual output, you should print the entire canvas in formats such as PDF, SVG, or PNG.
TRatioPlot has two constructors, one which accepts two histograms, and is responsible
for setting up the calculation of ratios and differences. This calculation is in part
delegated to `TEfficiency`. A single option can be given as a parameter, that is
used to determine which procedure is chosen. The remaining option string is then
passed through to the calculation, if applicable. The other constructor uses a
fitted histogram to calculate the fit residual and plot it with the histogram
and the fit function.
## Ratios and differences
The simplest case is passing two histograms without specifying any options. This defaults to using
`TGraphAsymmErrors::Divide`. The `option` variable is passed through, as are the parameters
`c1` and `c2`, that you can set via `TRatioPlot::SetC1` and `TRatioPlot::SetC1`. If you set the
`option` to `divsym` the method `TH1::Divide` will be used instead, also receiving all the parameters.
Using the `option` `diff` or `diffsig`, both histograms will be subtracted, and in the case of diffsig,
the difference will be divided by the uncertainty. `c1` and `c2` will only be used to
scale the histograms using `TH1::Scale` prior to subtraction.
Available options are for `option`:
| Option | Description |
| ---------- | ------------------------------------------------------------ |
| divsym | uses the histogram `TH1::Divide` method, yields symmetric errors |
| diff | subtracts the histograms |
| diffsig | subtracts the histograms and divides by the uncertainty |
Begin_Macro(source)
../../../tutorials/hist/hist029_TRatioPlot_simple.C
End_Macro
## Fit residuals
A second constructor only accepts a single histogram, but expects it to have a fitted
function. The function is used to calculate the residual between the fit and the
histogram. Here, it is expected that h1 has a fit function in it's list of functions. The class calculates the
difference between the histogram and the fit function at each point and divides it by the uncertainty. There
are a few option to steer which error is used (as is the case for `diffsig`). The default is to use
the statistical uncertainty from h1 using `TH1::GetBinError`. If the `option` string contains `errasym`, asymmetric
errors will be used. The type of error can be steered by `TH1::SetBinErrorOption`. The corresponding error will be used,
depending on if the function is below or above the bin content. The third option `errfunc` uses the square root of
the function value as the error.
Begin_Macro(source)
../../../tutorials/hist/hist030_TRatioPlot_residual.C
End_Macro
## Error options for difference divided by uncertainty and fit residual
The uncertainty that is used in the calculation can be steered by providing
options to the `option` argument.
| Option | Description |
| ---------- | ------------------------------------------------------------ |
| errasym | Uses calculated asymmetric errors from `TH1::GetBinErrorUp`/`TH1::GetBinErrorLow`. Note that you need to
set `TH1::SetBinErrorOption` first | | errfunc | Uses \f$ \sqrt{f(x)} \f$ as the error |
The asymmetric error case uses the upper or lower error depending on the relative size
of the bin contents, or the bin content and the function value.
## Access to internal parts
You can access the internal objects that are used to construct the plot via a series of
methods. `TRatioPlot::GetUpperPad` and `TRatioPlot::GetLowerPad` can be used to draw additional
elements on top of the existing ones.
`TRatioPlot::GetLowerRefGraph` returns a reference to the lower pad's graph that
is responsible for the range, which enables you to modify the range.
\image html gpad_ratioplot.png
*/
////////////////////////////////////////////////////////////////////////////////
/// TRatioPlot default constructor
TRatioPlot::TRatioPlot() : fLeftMargin(gStyle->GetPadLeftMargin()), fRightMargin(gStyle->GetPadRightMargin()) {}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
TRatioPlot::~TRatioPlot()
{
delete fSharedXAxis;
delete fUpYaxis;
delete fLowYaxis;
if ((fMode != CalculationMode::kFitResidual) || !fShowConfidenceIntervals) {
delete fConfidenceInterval1;
delete fConfidenceInterval2;
}
// special case when fH1 created from the stack but not drawn - need to delete it
if ((fMode != CalculationMode::kFitResidual) && fHistDrawProxyStack)
delete fH1;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal method that shares constructor logic
void TRatioPlot::Init(TH1* h1, TH1* h2, Option_t *option)
{
fH1 = h1;
fH2 = h2;
SetupPads();
TString optionString = option;
if (optionString.Contains("divsym")) {
optionString.ReplaceAll("divsym", "");
fMode = CalculationMode::kDivideHist;
} else if (optionString.Contains("diffsig")) {
optionString.ReplaceAll("diffsig", "");
fMode = CalculationMode::kDifferenceSign;
// determine which error style
if (optionString.Contains("errasym")) {
fErrorMode = ErrorMode::kErrorAsymmetric;
optionString.ReplaceAll("errasym", "");
}
if (optionString.Contains("errfunc")) {
fErrorMode = ErrorMode::kErrorFunc;
optionString.ReplaceAll("errfunc", "");
}
} else if (optionString.Contains("diff")) {
optionString.ReplaceAll("diff", "");
fMode = CalculationMode::kDifference;
} else {
fMode = CalculationMode::kDivideGraph; // <- default
}
fOption = optionString;
fH1DrawOpt = "hist";
fH2DrawOpt = "E";
fGraphDrawOpt = "AP";
// build ratio, everything is ready
if (!BuildLowerPlot()) return;
// taking x axis information from h1 by cloning it x axis
fSharedXAxis = static_cast<TAxis *>(fH1->GetXaxis()->Clone());
fUpYaxis = static_cast<TAxis *>(fH1->GetYaxis()->Clone());
fLowYaxis = static_cast<TAxis *>(fRatioGraph->GetYaxis()->Clone());
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor for two histograms
///
/// \param h1 First histogram
/// \param h2 Second histogram
/// \param option Steers the error calculation, as well as ratio / difference
TRatioPlot::TRatioPlot(TH1 *h1, TH1 *h2, Option_t *option) : TRatioPlot()
{
if (!h1 || !h2) {
Warning("TRatioPlot", "Need two histograms.");
return;
}
Bool_t h1IsTH1 = h1->InheritsFrom(TH1::Class());
Bool_t h2IsTH1 = h2->InheritsFrom(TH1::Class());
if (!h1IsTH1 && !h2IsTH1) {
Warning("TRatioPlot", "Need two histograms deriving from TH2 or TH3.");
return;
}
fHistDrawProxy = h1;
Init(h1, h2, option);
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor which accepts a `THStack` and a histogram. Converts the
/// stack to a regular sum of its containing histograms for processing.
///
/// \param st The THStack object
/// \param h2 The other histogram
/// \param option Steers the calculation of the lower plot
TRatioPlot::TRatioPlot(THStack *st, TH1 *h2, Option_t *option) : TRatioPlot()
{
if (!st || !h2) {
Warning("TRatioPlot", "Need a histogram and a stack");
return;
}
TList *stackHists = st->GetHists();
if (stackHists->GetSize() == 0) {
Warning("TRatioPlot", "Stack does not have histograms");
return;
}
auto tmpHist = static_cast<TH1 *>(stackHists->At(0)->Clone());
tmpHist->Reset();
for (int i = 0; i < stackHists->GetSize(); ++i) {
tmpHist->Add(static_cast<TH1 *>(stackHists->At(i)));
}
fHistDrawProxy = st;
fHistDrawProxyStack = kTRUE;
Init(tmpHist, h2, option);
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor which accepts a `THStack` and a histogram. Converts the
/// stack to a regular sum of its containing histograms for processing.
///
/// \param h1 The other histogram
/// \param st The THStack object
/// \param option Steers the calculation of the lower plot
TRatioPlot::TRatioPlot(TH1 *h1, THStack *st, Option_t *option) : TRatioPlot()
{
if (!st || !h1) {
Warning("TRatioPlot", "Need a histogram and a stack");
return;
}
TList *stackHists = st->GetHists();
if (stackHists->GetSize() == 0) {
Warning("TRatioPlot", "Stack does not have histograms");
return;
}
auto tmpHist = static_cast<TH1 *>(stackHists->At(0)->Clone());
tmpHist->Reset();
for (int i = 0; i < stackHists->GetSize(); ++i) {
tmpHist->Add(static_cast<TH1 *>(stackHists->At(i)));
}
fHistDrawProxy = h1;
Init(h1, tmpHist, option);
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor for one histogram and a fit.
///
/// \param h1 The histogram
/// \param option Steers the error calculation
/// \param fitres Explicit fit result to be used for calculation. Uses last fit if left empty
TRatioPlot::TRatioPlot(TH1 *h1, Option_t *option, TFitResult *fitres) : TRatioPlot()
{
fH1 = h1;
if (!fH1) {
Warning("TRatioPlot", "Need a histogram.");
return;
}
Bool_t h1IsTH1 = fH1->InheritsFrom(TH1::Class());
if (!h1IsTH1) {
Warning("TRatioPlot", "Need a histogram deriving from TH2 or TH3.");
return;
}
TList *h1Functions = fH1->GetListOfFunctions();
if (h1Functions->GetSize() < 1) {
Warning("TRatioPlot", "Histogram given needs to have a (fit) function associated with it");
return;
}
fHistDrawProxy = h1;
fFitResult = fitres;
fMode = CalculationMode::kFitResidual;
TString optionString = option;
// determine which error style
if (optionString.Contains("errasym")) {
fErrorMode = ErrorMode::kErrorAsymmetric;
optionString.ReplaceAll("errasym", "");
}
if (optionString.Contains("errfunc")) {
fErrorMode = ErrorMode::kErrorFunc;
optionString.ReplaceAll("errfunc", "");
}
fOption = optionString;
if (!BuildLowerPlot()) return;
// emulate option behaviour of TH1
if (fH1->GetSumw2N() > 0) {
fH1DrawOpt = "E";
} else {
fH1DrawOpt = "hist";
}
fGraphDrawOpt = "LX"; // <- default
fSharedXAxis = static_cast<TAxis *>(fH1->GetXaxis()->Clone());
fUpYaxis = static_cast<TAxis *>(fH1->GetYaxis()->Clone());
fLowYaxis = static_cast<TAxis *>(fRatioGraph->GetYaxis()->Clone());
//SyncAxesRanges();
SetupPads();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the drawing option for h1
void TRatioPlot::SetH1DrawOpt(Option_t *opt)
{
fH1DrawOpt = opt;
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the drawing option for h2
void TRatioPlot::SetH2DrawOpt(Option_t *opt)
{
TString optString = opt;
optString.ReplaceAll("same", "");
optString.ReplaceAll("SAME", "");
fH2DrawOpt = optString;
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the drawing option for the lower graph
void TRatioPlot::SetGraphDrawOpt(Option_t *opt)
{
fGraphDrawOpt = opt;
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the drawing option for the fit in the fit residual case
void TRatioPlot::SetFitDrawOpt(Option_t *opt)
{
fFitDrawOpt = opt;
}
////////////////////////////////////////////////////////////////////////////////
/// Setup the pads.
void TRatioPlot::SetupPads()
{
// this method will delete all the pads before recreating them
if (fUpperPad) {
delete fUpperPad;
fUpperPad = nullptr;
}
if (fLowerPad) {
delete fLowerPad;
fLowerPad = nullptr;
}
if (!gPad) {
Error("SetupPads", "need to create a canvas first");
return;
}
double pm = fInsetWidth;
double width = gPad->GetWNDC();
double height = gPad->GetHNDC();
double f = height/width;
fUpperPad = new TPad("upper_pad", "", pm*f, fSplitFraction, 1.-pm*f, 1.-pm);
fLowerPad = new TPad("lower_pad", "", pm*f, pm, 1.-pm*f, fSplitFraction);
SetPadMargins();
// connect to the pads signal
if (fTopPad) {
delete fTopPad;
fTopPad = nullptr;
}
fTopPad = new TPad("top_pad", "", pm*f, pm, 1-pm*f, 1-pm);
fTopPad->SetBit(kCannotPick);
}
////////////////////////////////////////////////////////////////////////////////
/// Connect some signals from the pads to handle them
/// Allows correctly work also after reading ratioplot from the file
void TRatioPlot::ConnectPadsSignals()
{
static const char *rangeSignal = "RangeAxisChanged()";
if (fUpperPad->HasConnection(rangeSignal) && fLowerPad->HasConnection(rangeSignal))
return;
fUpperPad->Connect(rangeSignal, ClassName(), this, "RangeAxisChanged()");
fLowerPad->Connect(rangeSignal, ClassName(), this, "RangeAxisChanged()");
fUpperPad->Connect("UnZoomed()", ClassName(), this, "UnZoomed()");
fLowerPad->Connect("UnZoomed()", ClassName(), this, "UnZoomed()");
fUpperPad->Connect("Resized()", ClassName(), this, "SubPadResized()");
fLowerPad->Connect("Resized()", ClassName(), this, "SubPadResized()");
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the top margin of the upper pad.
///
/// \param margin The new margin
void TRatioPlot::SetUpTopMargin(Float_t margin)
{
fUpTopMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the bottom margin of the upper pad.
///
/// \param margin The new margin
void TRatioPlot::SetUpBottomMargin(Float_t margin)
{
fUpBottomMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the top margin of the lower pad.
///
/// \param margin The new margin
void TRatioPlot::SetLowTopMargin(Float_t margin)
{
fLowTopMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the bottom margin of the lower pad.
///
/// \param margin The new margin
void TRatioPlot::SetLowBottomMargin(Float_t margin)
{
fLowBottomMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the left margin of both pads.
/// \param margin The new margin
void TRatioPlot::SetLeftMargin(Float_t margin)
{
fLeftMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the right margin of both pads.
///
/// \param margin The new margin
void TRatioPlot::SetRightMargin(Float_t margin)
{
fRightMargin = margin;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the margin that separates the two pads. The margin is split according
/// to the relative sizes of the pads
///
/// \param margin The new margin
///
/// Begin_Macro(source)
/// ../../../tutorials/hist/hist034_TRatioPlot_fit_margin.C
/// End_Macro
void TRatioPlot::SetSeparationMargin(Float_t margin)
{
Float_t sf = fSplitFraction;
fUpBottomMargin = margin/2./(1-sf);
fLowTopMargin = margin/2./sf;
SetPadMargins();
}
////////////////////////////////////////////////////////////////////////////////
/// Return the separation margin value.
Float_t TRatioPlot::GetSeparationMargin() const
{
Float_t sf = fSplitFraction;
Float_t up = fUpBottomMargin * (1-sf);
Float_t down = fLowTopMargin * sf;
return up+down;
}
////////////////////////////////////////////////////////////////////////////////
/// Draws the ratio plot to the currently active pad. Therefore it requires that
/// a TCanvas has been created first.
///
/// It takes the following options
///
/// | Option | Description |
/// | ---------- | ------------------------------------------------------------ |
/// | grid / nogrid | enable (default) or disable drawing of dashed lines on lower plot |
/// | hideup | hides the first label of the upper axis if there is not enough space |
/// | fhideup | always hides the first label of the upper axis |
/// | hidelow (default) | hides the last label of the lower axis if there is not enough space |
/// | fhidelow | always hides the last label of the lower axis |
/// | nohide | does not hide a label if there is not enough space |
/// | noconfint | does not draw the confidence interval bands in the fit residual case |
/// | confint | draws the confidence interval bands in the fit residual case (default) |
void TRatioPlot::Draw(Option_t *option)
{
TString drawOpt = option;
if (drawOpt.Contains("nogrid")) {
drawOpt.ReplaceAll("nogrid", "");
fShowGridlines = kFALSE;
} else if (drawOpt.Contains("grid")) {
drawOpt.ReplaceAll("grid", "");
fShowGridlines = kTRUE;
}
if (drawOpt.Contains("noconfint")) {
drawOpt.ReplaceAll("noconfint", "");
fShowConfidenceIntervals = kFALSE;
} else if (drawOpt.Contains("confint")) {
drawOpt.ReplaceAll("confint", "");
fShowConfidenceIntervals = kTRUE; // <- default
}
if (drawOpt.Contains("fhideup")) {
fHideLabelMode = HideLabelMode::kForceHideUp;
} else if (drawOpt.Contains("fhidelow")) {
fHideLabelMode = HideLabelMode::kForceHideLow;
} else if (drawOpt.Contains("hideup")) {
fHideLabelMode = HideLabelMode::kHideUp;
} else if (drawOpt.Contains("hidelow")) {
fHideLabelMode = HideLabelMode::kHideLow;
} else if (drawOpt.Contains("nohide")) {
fHideLabelMode = HideLabelMode::kNoHide;
} else {
fHideLabelMode = HideLabelMode::kHideLow; // <- default
}
if (!gPad) {
Error("Draw", "need to create a canvas first");
return;
}
fParentPad = gPad;
// draw ratio plot as very first object
// when painting one can update all attributes before other objects are painted
AppendPad();
fUpperPad->SetLogy(fParentPad->GetLogy());
fUpperPad->SetLogx(fParentPad->GetLogx());
fLowerPad->SetLogx(fParentPad->GetLogx());
fUpperPad->SetGridx(fParentPad->GetGridx());
fUpperPad->SetGridy(fParentPad->GetGridy());
fLowerPad->SetGridx(fParentPad->GetGridx());
fLowerPad->SetGridy(fParentPad->GetGridy());
// we are a TPad
fUpperPad->Draw();
fLowerPad->Draw();
fTopPad->SetFillStyle(0);
fTopPad->Draw();
fUpperPad->cd();
fConfidenceInterval1->SetFillColor(fCi1Color);
fConfidenceInterval2->SetFillColor(fCi2Color);
if (fMode == CalculationMode::kFitResidual) {
// use last function in the list
TF1 *func = nullptr;
for (int i = fH1->GetListOfFunctions()->GetSize()-1; i >= 0; i--) {
auto obj = fH1->GetListOfFunctions()->At(i);
if (obj->InheritsFrom(TF1::Class()) ) {
func = dynamic_cast<TF1*>(obj);
break;
}
}
if (!func) {
// this is checked in constructor and should thus not occur
Error("Draw", "h1 does not have a fit function");
return;
}
fH1->Draw("A"+fH1DrawOpt);
func->Draw(fFitDrawOpt+"same");
fLowerPad->cd();
if (fShowConfidenceIntervals) {
fConfidenceInterval2->Draw("IA3");
fConfidenceInterval1->Draw("3");
fRatioGraph->Draw(fGraphDrawOpt+"SAME");
} else {
fRatioGraph->Draw("IA"+fGraphDrawOpt+"SAME");
}
} else {
if (fHistDrawProxy) {
if (fHistDrawProxyStack || fHistDrawProxy->InheritsFrom(TH1::Class())) {
fHistDrawProxy->Draw("A"+fH1DrawOpt);
} else {
Warning("Draw", "Draw proxy not of type TH1 or THStack, not drawing it");
}
}
fH2->Draw("A"+fH2DrawOpt+"same");
fLowerPad->cd();
TString opt = fGraphDrawOpt;
fRatioGraph->Draw("IA"+fGraphDrawOpt);
}
// assign same axis ranges to lower pad as in upper pad
// the visual axes will be created on paint
SyncAxesRanges();
CreateVisualAxes();
CreateGridlines();
// restore active pad at the end
fParentPad->cd();
// only after object drawn connect signals
ConnectPadsSignals();
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the reference graph for the lower pad, which means the graph that
/// is responsible for setting the coordinate system. It is the first graph
/// added to the primitive list of the lower pad.
/// This reference can be used to set the minimum and maximum of the lower pad.
/// Note that `TRatioPlot::Draw` needs to have been called first, since the
/// graphs are only created then.
///
/// Begin_Macro(source)
/// ../../../tutorials/hist/hist031_TRatioPlot_residual_fit.C
/// End_Macro
TGraph *TRatioPlot::GetLowerRefGraph() const
{
if (!fLowerPad) {
Error("GetLowerRefGraph", "Lower pad has not been defined");
return nullptr;
}
TList *primlist = fLowerPad->GetListOfPrimitives();
if (primlist->GetSize() == 0) {
Error("GetLowerRefGraph", "Lower pad does not have primitives");
return nullptr;
}
TObjLink *lnk = primlist->FirstLink();
while (lnk) {
TObject *obj = lnk->GetObject();
if (obj->InheritsFrom(TGraph::Class()))
return static_cast<TGraph *>(obj);
lnk = lnk->Next();
}
Error("GetLowerRefGraph", "Did not find graph in list");
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the reference object. Its the first TH1 or THStack type object
/// in the upper pads list of primitives.
/// Note that it returns a `TObject`, so you need to test and cast it to use it.
TObject *TRatioPlot::GetUpperRefObject() const
{
TList *primlist = fUpperPad->GetListOfPrimitives();
for (Int_t i = 0; i < primlist->GetSize(); ++i) {
auto refobj = primlist->At(i);
if (refobj->InheritsFrom(TH1::Class()) || refobj->InheritsFrom(THStack::Class())) {
return refobj;
}
}
Error("GetUpperRefObject", "No upper ref object of TH1 or THStack type found");
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Gets the x axis of the object returned by `TRatioPlot::GetUpperRefObject`.
TAxis *TRatioPlot::GetUpperRefXaxis() const
{
TObject *refobj = GetUpperRefObject();
if (!refobj)
return nullptr;
if (refobj->InheritsFrom(TH1::Class())) {
return static_cast<TH1 *>(refobj)->GetXaxis();
} else if (refobj->InheritsFrom(THStack::Class())) {
return static_cast<THStack *>(refobj)->GetXaxis();
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Gets the y axis of the object returned by `TRatioPlot::GetUpperRefObject`.
TAxis *TRatioPlot::GetUpperRefYaxis() const
{
TObject *refobj = GetUpperRefObject();
if (!refobj)
return nullptr;
if (refobj->InheritsFrom(TH1::Class())) {
return static_cast<TH1 *>(refobj)->GetYaxis();
} else if (refobj->InheritsFrom(THStack::Class())) {
return static_cast<THStack *>(refobj)->GetYaxis();
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Gets the x axis of the lower ref graph.
/// Shortcut for:
///
/// ~~~{.cpp}
/// rp->GetLowerRefGraph()->GetXaxis();
/// ~~~
TAxis *TRatioPlot::GetLowerRefXaxis() const
{
auto gr = GetLowerRefGraph();
return gr ? gr->GetXaxis() : nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Gets the y axis of the lower ref graph.
/// Shortcut for:
///
/// ~~~{.cpp}
/// rp->GetLowerRefGraph()->GetYaxis();
/// ~~~
TAxis *TRatioPlot::GetLowerRefYaxis() const
{
auto gr = GetLowerRefGraph();
return gr ? gr->GetYaxis() : nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a grid lines
void TRatioPlot::CreateGridlines()
{
if (!fShowGridlines)
return; // don't draw them
while (fGridlines.size() < fGridlinePositions.size()) {
TLine *newline = new TLine(0, 0, 0, 0);
newline->SetLineStyle(2);
fLowerPad->Add(newline);
fGridlines.emplace_back(newline);
}
UpdateGridlines();
}
////////////////////////////////////////////////////////////////////////////////
/// Update positions of grid lines
void TRatioPlot::UpdateGridlines()
{
Double_t first = fSharedXAxis->GetBinLowEdge(fSharedXAxis->GetFirst());
Double_t last = fSharedXAxis->GetBinUpEdge(fSharedXAxis->GetLast());
Double_t lowYFirst = fLowerPad->GetUymin();
Double_t lowYLast = fLowerPad->GetUymax();
for (size_t i = 0; i < fGridlines.size(); ++i) {
auto line = fGridlines.at(i);
Bool_t visible = kFALSE;
Double_t y = 0.;
if (i < fGridlinePositions.size()) {
y = fGridlinePositions[i];
visible = (y >= lowYFirst && y <= lowYLast);
}
if (visible) {
line->SetX1(first);
line->SetX2(last);
line->SetY1(y);
line->SetY2(y);
} else {
line->SetX1(first);
line->SetX2(first);
line->SetY1(lowYFirst);
line->SetY2(lowYFirst);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Update the visual axes and grid lines when painting
void TRatioPlot::Paint(Option_t * /*opt*/)
{
// painting invoked before object drawn to the end - just ignore here
if (!fUpperGXaxis)
return;
ConnectPadsSignals();
UpdateVisualAxes();
UpdateGridlines();
// in any case reset flag after painting
fIsUpdating = kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Syncs the axes ranges from the shared ones to the actual ones.
void TRatioPlot::SyncAxesRanges()
{
// get ranges from the shared axis clone
Double_t first = fSharedXAxis->GetBinLowEdge(fSharedXAxis->GetFirst());
Double_t last = fSharedXAxis->GetBinUpEdge(fSharedXAxis->GetLast());
// set range on computed graph, have to set it twice because
// TGraph's axis looks strange otherwise
TAxis *ref = GetLowerRefXaxis();
ref->SetLimits(first, last);
ref->SetRangeUser(first, last);
GetUpperRefXaxis()->SetRangeUser(first, last);
}
////////////////////////////////////////////////////////////////////////////////
/// Build the lower plot according to which constructor was called, and
/// which options were passed.
Int_t TRatioPlot::BuildLowerPlot()
{
static const char *thisMethod = "BuildLowerPlot";
// Clear and delete the graph if not exists
if (fRatioGraph) {
delete fRatioGraph;
fRatioGraph = nullptr;
}
if (!fConfidenceInterval1)
fConfidenceInterval1 = new TGraphErrors();
if (!fConfidenceInterval2)
fConfidenceInterval2 = new TGraphErrors();
static Double_t divideGridlines[] = {0.7, 1.0, 1.3};
static Double_t diffGridlines[] = {0.0};
static Double_t signGridlines[] = {1.0, 0.0, -1.0};
// Determine the divide mode and create the lower graph accordingly
// Pass divide options given in constructor
if (fMode == CalculationMode::kDivideGraph) {
// use TGraphAsymmErrors Divide method to create
SetGridlines(divideGridlines, 3);
TH1 *tmpH1 = static_cast<TH1 *>(fH1->Clone());
TH1 *tmpH2 = static_cast<TH1 *>(fH2->Clone());
tmpH1->Scale(fC1);
tmpH2->Scale(fC2);
TGraphAsymmErrors *ratioGraph = new TGraphAsymmErrors();
ratioGraph->Divide(tmpH1, tmpH2, fOption.Data());
fRatioGraph = ratioGraph;
delete tmpH1;
delete tmpH2;
} else if (fMode == CalculationMode::kDifference) {
SetGridlines(diffGridlines, 3);
TH1 *tmpHist = static_cast<TH1 *>(fH1->Clone());
tmpHist->Reset();
tmpHist->Add(fH1, fH2, fC1, -1*fC2);
fRatioGraph = new TGraphErrors(tmpHist);
delete tmpHist;
} else if (fMode == CalculationMode::kDifferenceSign) {
SetGridlines(signGridlines, 3);
fRatioGraph = new TGraphAsymmErrors();
Int_t ipoint = 0;
for (Int_t i = 0; i <= fH1->GetNbinsX(); ++i) {
Double_t val = fH1->GetBinContent(i);
Double_t val2 = fH2->GetBinContent(i);
Double_t error = 0.;
if (fErrorMode == ErrorMode::kErrorAsymmetric) {
Double_t errUp = fH1->GetBinErrorUp(i);
Double_t errLow = fH1->GetBinErrorLow(i);
if (val - val2 > 0) {
// h1 > h2
error = errLow;
} else {
// h1 < h2
error = errUp;
}
} else if (fErrorMode == ErrorMode::kErrorSymmetric) {
error = fH1->GetBinError(i);
} else {
Warning(thisMethod, "error mode is invalid");
}
if (error != 0.) {