def MakeOneHist(histogramName):

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources:  # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],
                                              source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get("OSUAnalysis/" +
                                        source['num_channel'] + "/" +
                                        histogramName)
        if 'condor_dir_den' in source:  # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],
                                                     source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get("OSUAnalysis/" +
                                               source['den_channel'] + "/" +
                                               histogramName)
        else:  # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get("OSUAnalysis/" +
                                            source['den_channel'] + "/" +
                                            histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'num_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'den_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetTitle(
            ).find("GenMatch") is -1 and not Histogram.Class().InheritsFrom(
                    "TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)
            ) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj)
        if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            Histogram = TGraphAsymmErrors(Histogram, DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1. / histogram.Integral())

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram, LegendEntries[legendIndex], "LEP")
        legendIndex = legendIndex + 1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    if arguments.noTGraph:
        for histogram in Histograms:
            currentMax = histogram.GetMaximum() + histogram.GetBinError(
                histogram.GetMaximumBin())
            if (currentMax > finalMax):
                finalMax = currentMax
    finalMax = 1.5 * finalMax
    if finalMax is 0:
        finalMax = 1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1, 2)
        Canvas.cd(1)
        gPad.SetPad(0, 0.25, 1, 1)
        gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0, 0, 1, 0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[
                DatasetName.rfind('__') +
                2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom,
                                      topLeft_x_right, topLeft_y_top,
                                      DatasetName, "NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()
            if arguments.makeFancy:
                HeaderLabel.Draw()

        else:
            if histogram.InheritsFrom("TGraph") and histCounter == 0:
                plotting_options = "AP"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)
            histogram.GetXaxis().SetTitle(xAxisLabel)
            histogram.GetYaxis().SetTitle(yAxisLabel)
            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    if arguments.makeFancy:
        HeaderLabel.Draw()

    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            Comparison = ratioHistogram(Histograms[0], Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1], -1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
            else:  #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMax, 1.2 * YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 1.2 * YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
示例#2
0
    h1.GetXaxis().SetNdivisions(5)  
    h1.GetYaxis().SetNdivisions(5)  
    h1.GetXaxis().SetTitleSize(0.05)
    h1.GetYaxis().SetTitleSize(0.05)
    h1.GetZaxis().SetTitleSize(0.05)
    h1.GetXaxis().SetLabelSize(0.05)
    h1.GetYaxis().SetLabelSize(0.05)
    h1.GetZaxis().SetLabelSize(0.05)
    h1.GetXaxis().SetTitleOffset(1.0) 
    h1.GetYaxis().SetTitleOffset(1.6) 

    HeaderLabel = TPaveLabel(0.2, 0.92, 0.8, 0.98,title,"NDC")
    # HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.8) 
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    if h1.Class().InheritsFrom("TH2"):
        is2D = True
    else:
        is2D = False  

    if is2D:
        c.SetRightMargin(0.15)  
        c.SetLogz(True)  
        HeaderLabel.SetTextSize(0.7) 

        h1.Draw("colz")
        HeaderLabel.SetLabel(title + ": " + plot["label1"])  
示例#3
0
def main():

    import argparse
    parser = argparse.ArgumentParser(
        usage="makePValuePlot.py [options] -o OUTPUTFILE --card CARD1",
        description="plots pvalue scans for Z' analysis'",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--card",
                        dest="cards",
                        default=[],
                        action="append",
                        help='add datacard to list of curves to plot')
    parser.add_argument("--smooth",
                        dest="smooth",
                        action="store_true",
                        default=False,
                        help="Smooth observed values")
    parser.add_argument("-c",
                        "--config",
                        dest="config",
                        default='',
                        help="config name")
    parser.add_argument("-t",
                        "--tag",
                        dest="tag",
                        default='',
                        help="limit tag")
    parser.add_argument("--ratioLabel",
                        dest="ratioLabel",
                        default='',
                        help="label for ratio")
    args = parser.parse_args()

    canv = ROOT.TCanvas("c1", "c1", 600, 450)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1)
    ROOT.gStyle.SetPadLeftMargin(0.12)
    ROOT.gStyle.SetPadBottomMargin(0.12)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetTitleXSize(0.055)
    ROOT.gStyle.SetLabelSize(0.055, "X")
    ROOT.gStyle.SetLabelSize(0.055, "Y")
    ROOT.gStyle.SetTitleXOffset(1.05)
    #ROOT.gStyle.SetLabelYSize(0.04)
    ROOT.gStyle.SetTitleYSize(0.055)
    ROOT.gStyle.SetTitleYOffset(1.1)

    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    plotPad.DrawFrame(200, 1e-4, 4000, 10, ";M [GeV]; local p-Value")
    plotPad.SetLogy()
    #ROOT.gStyle.SetLabelXSize(0.04)
    leg = ROOT.TLegend(0.32, 0.72, 0.9, 0.875, "", "brNDC")
    leg.SetFillColor(10)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetTextSize(0.06)
    graphs = []

    name = "pValues_%s_%s" % (args.config, args.tag)
    fileForHEPData = TFile("plots/" + name + "_forHEPData.root", "RECREATE")
    for index, card in enumerate(args.cards):
        if 'width' in card:
            width = "signif" + card.split('width')[-1].split('_')[0]
        else:
            width = 'signif'

        masses, pValues = getPValues(card)
        minPVal, minPValMass = getMinPValue(card)
        print card, minPVal, minPValMass
        graphs.append(
            ROOT.TGraph(len(masses), numpy.array(masses),
                        numpy.array(pValues)))
        label = card.split("_")[-1].split(".")[0]
        if args.smooth:
            smoother = ROOT.TGraphSmooth("normal")
            graphs[index] = deepcopy(
                smoother.SmoothSuper(graphs[index], "linear", 0, 0.005))

        graphs[index].SetLineColor(lineColors[width])
        graphs[index].SetLineStyle(lineStyles[width])
        leg.AddEntry(graphs[index], labels[width], "l")
        graphs[index].Draw("Lsame")
        graphs[index].SetLineWidth(2)
        graphs[index].SetName("graphPVal%s" % width)
        graphs[index].Write("graphPVal%s" % width)

    leg.Draw()
    leg.SetTextSize(0.045)
    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.03)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(62)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    configName = "scanConfiguration_%s" % args.config

    config = __import__(configName)
    chan = config.leptons

    if (chan == "mumu"):
        plLumi = TPaveLabel(.65, .885, .9, .99,
                            "139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC")
    elif (chan == "elel"):
        plLumi = TPaveLabel(.65, .885, .9, .99, "136.8 fb^{-1} (13 TeV, ee)",
                            "NBNDC")
    elif (chan == "elmu"):
        plLumi = TPaveLabel(
            .27, .885, .9, .99,
            "136.8 fb^{-1} (13 TeV, ee) + 139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
            "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.14, 0.81, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.78
    else:
        yLabelPos = 0.78

    latexCMSExtra.DrawLatex(0.14, yLabelPos, "%s" % (cmsExtra))

    ZeroSigmaLine = ROOT.TLine(200, 0.5, 4000, 0.5)
    ZeroSigmaLine.SetLineStyle(ROOT.kDashed)
    ZeroSigmaLine.Draw("same")

    OneSigmaLine = ROOT.TLine(200, 0.317 / 2, 4000, 0.317 / 2)
    OneSigmaLine.SetLineStyle(ROOT.kDashed)
    OneSigmaLine.Draw("same")

    TwoSigmaLine = ROOT.TLine(200, 0.0455 / 2, 4000, 0.0455 / 2)
    TwoSigmaLine.SetLineStyle(ROOT.kDashed)
    TwoSigmaLine.Draw("same")

    ThreeSigmaLine = ROOT.TLine(200, 0.0027 / 2, 4000, 0.0027 / 2)
    ThreeSigmaLine.SetLineStyle(ROOT.kDashed)
    ThreeSigmaLine.Draw("same")

    FourSigmaLine = ROOT.TLine(200, 0.00006 / 2, 4000, 0.00006 / 2)
    FourSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FourSigmaLine.Draw("same")

    FiveSigmaLine = ROOT.TLine(200, 3e-07, 4000, 3e-07)
    FiveSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FiveSigmaLine.Draw("same")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    #~ latex.SetNDC(Tru78
    latex.DrawLatex(4150, 0.5, "0#sigma")
    latex.DrawLatex(4150, 0.317 / 2, "1#sigma")
    latex.DrawLatex(4150, 0.0455 / 2, "2#sigma")
    latex.DrawLatex(4150, 0.0027 / 2, "3#sigma")
    #~ latex.DrawLatex(4200, 0.00006/2, "4#sigma")
    #~ latex.DrawLatex(4200, 3e-7, "5#sigma")

    #~ ROOT.gPad.WaitPrimitive()
    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()
    if args.smooth:
        name += "_smoothed"
    #name = name+".pdf"
    canv.Print("plots/" + name + ".pdf")
    canv.Print("plots/" + name + ".root")

    plotPad.RedrawAxis()

    fileForHEPData.Write()
    fileForHEPData.Close()
示例#4
0
def MakeOneDHist(histogramDirectory, histogramName,integrateDir):

    if arguments.verbose:
        print "Creating histogram", histogramName, "in directory", histogramDirectory

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    canvasName = histogramName
    if integrateDir is "left":
        canvasName += "_CumulativeLeft"
    elif integrateDir is "right":
        canvasName += "_CumulativeRight"
    Canvas = TCanvas(canvasName)
    Histograms = []
    RefIndex = -99
    LegendEntries = []

    colorIndex = 0
    markerStyleIndex = 0
    fillIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)


        if arguments.generic:
            if histogramDirectory == "":
                histPath = histogramName
            else:
                histPath = histogramDirectory + "/" + histogramName
            HistogramObj = inputFile.Get(histPath)
        else:
            HistogramObj = inputFile.Get(source['channel'] + "Plotter/" + histogramDirectory + "/" + histogramName)
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        Histogram.Sumw2()
        if arguments.verbose:
            print "  Got histogram", Histogram.GetName(), "from file", dataset_file
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        # correct bin contents of object multiplcity plots
        if Histogram.GetName().startswith("num") and "PV" not in Histogram.GetName():
            # include overflow bin
            for bin in range(2,Histogram.GetNbinsX()+2):
                content = Histogram.GetBinContent(bin)
                Histogram.SetBinContent(bin, content/float(bin-1))


        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")
        xAxisLabelVar = xAxisLabel

        if "_pfx" in Histogram.GetName() or "_pfy" in Histogram.GetName() or "_sigma" in Histogram.GetName():
            yAxisLabel = Histogram.GetYaxis().GetTitle()
        else:

            if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
                yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex]
                xAxisLabelVar = xAxisLabel[0:unitBeginIndex]
            else:
                yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
            if arguments.normalizeToUnitArea:
                yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

            if arguments.normalizeToUnitArea and arguments.makeSignificancePlots:
                unit = "Efficiency"
            else:
                unit = "Yield"
            if integrateDir is "left":
                yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
            if integrateDir is "right":
                yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"


        nbins = Histogram.GetNbinsX()
        if not noOverFlow:
            Histogram.SetBinContent(nbins, Histogram.GetBinContent(nbins) + Histogram.GetBinContent(nbins+1)) # Add overflow
            Histogram.SetBinError(nbins, math.sqrt(math.pow(Histogram.GetBinError(nbins),2) + math.pow(Histogram.GetBinError(nbins+1),2))) # Set the errors to be the sum in quadrature
        if not noUnderFlow:
            Histogram.SetBinContent(1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) # Add underflow
            Histogram.SetBinError(1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) # Set the errors to be the sum in quadrature

        if not arguments.makeFancy and not arguments.generic:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
                markerStyleIndex = markerStyleIndex + 1
                if markerStyleIndex is len(markerStyleList):
                    markerStyleIndex = 0
                    fillIndex = fillIndex + 1


        if 'scale' in source:
            Histogram.Scale(source['scale'])

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        else:
            markerStyle = markers[markerStyleList[markerStyleIndex]]

        fillStyle = 0
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        else:
            markerStyle = markerStyle + fills[fillList[fillIndex]]

        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(0.5)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        if arguments.normalizeToUnitArea and Histogram.Integral() > 0:
            Histogram.Scale(1./Histogram.Integral())

        Histogram = MakeIntegralHist(Histogram, integrateDir)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        if 'reference' in source:
            if source['reference']:
                RefIndex = len(Histograms)-1

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.generic:
        plotting_options = "p,e"
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        histogram.SetTitle(histoTitle)
        if arguments.verbose:
            print "  Drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor())
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        histogram.SetMaximum(finalMax)

        if "_pfx" not in Histogram.GetName() and "_pfy" not in Histogram.GetName() and "_sigma" not in Histogram.GetName():
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            plotting_options = plotting_options + " SAME"
        histCounter = histCounter + 1

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()


    # Deciding which text labels to draw and drawing them
    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()




    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Comparisons = []
        Canvas.cd(2)
        if RefIndex == -99:
            Reference = Histograms[0]
        else:
            Reference = Histograms[RefIndex]

        for Histogram in Histograms:
            if Histogram is Reference:
                continue

            if makeRatioPlots:
                makeRatio = functools.partial (ratioHistogram,Histogram, Reference)
                if arguments.ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                    makeRatio =  functools.partial (makeRatio, relErrMax = float(arguments.ratioRelErrMax))
                if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                    makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
                Comparison = makeRatio()
            elif makeDiffPlots:
                Comparison = Reference.Clone("diff")
                Comparison.Add(Histograms[1],-1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("X-ref")

            Comparison.SetLineColor(Histogram.GetLineColor())
            Comparison.SetFillColor(Histogram.GetFillColor())
            Comparison.SetFillStyle(Histogram.GetFillStyle())
            Comparison.SetMarkerColor(Histogram.GetMarkerColor())
            Comparison.SetMarkerStyle(Histogram.GetMarkerStyle())

            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)

            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)

            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
                else: #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparisons.append(Comparison)

        option = "E0"
        for index,Comparison in enumerate(Comparisons):
            if index == 0:
                option += " SAME"
            Comparison.Draw(option)

    outputFile.cd(histogramDirectory)
    Canvas.Write()
    if arguments.verbose:
        print "  Finished writing canvas: ", Canvas.GetName()

    if arguments.savePDFs:
        Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")
def MakeOneHist(dirName, histogramName):

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    #legend coordinates, empirically determined :-)
    x_left = 0.4
    x_right = 0.7
    y_min = 0.15
    y_max = 0.3

    Legend = TLegend(x_left,y_min,x_right,y_max)
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    HistogramClones = []
    NBins = []
    MaxXValues = []
    MinXValues = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get(source['num_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if 'condor_dir_den' in source:   # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        else:   # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source['num_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source['den_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        nbinsN = Histogram.GetNbinsX()
        nbinsD = DenHistogram.GetNbinsX()
        if not noOverFlow:
            # Add overflow
            Histogram.SetBinContent(   nbinsN,    Histogram.GetBinContent(nbinsN) +    Histogram.GetBinContent(nbinsN+1))
            DenHistogram.SetBinContent(nbinsD, DenHistogram.GetBinContent(nbinsD) + DenHistogram.GetBinContent(nbinsD+1))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(  nbinsN,     math.sqrt(math.pow(Histogram.GetBinError(nbinsN),2) +    math.pow(Histogram.GetBinError(nbinsN+1),2)))
            DenHistogram.SetBinError(nbinsD, math.sqrt(math.pow(DenHistogram.GetBinError(nbinsD),2) + math.pow(DenHistogram.GetBinError(nbinsD+1),2)))

        if not noUnderFlow:
            # Add underflow
            Histogram.SetBinContent(   1,    Histogram.GetBinContent(1) +    Histogram.GetBinContent(0))
            DenHistogram.SetBinContent(1, DenHistogram.GetBinContent(1) + DenHistogram.GetBinContent(0))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(   1,    math.sqrt(math.pow(Histogram.GetBinError(1), 2) +    math.pow(Histogram.GetBinError(0), 2)))
            DenHistogram.SetBinError(1, math.sqrt(math.pow(DenHistogram.GetBinError(1), 2) + math.pow(DenHistogram.GetBinError(0), 2)))

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1 and not Histogram.Class().InheritsFrom("TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #check if bin content is consistent
        TEfficiency.CheckConsistency(Histogram,DenHistogram)
        for i in range(1,Histogram.GetNbinsX()+1):
            if Histogram.GetBinContent(i) > DenHistogram.GetBinContent(i):
                DenHistogram.SetBinContent(i,Histogram.GetBinContent(i))

        #HistogramClone and HistogramClones only used for ratio plot
        HistogramClone = Histogram.Clone()
        HistogramClone.SetDirectory(0)
        HistogramClone.Divide(DenHistogram)
        Nbins = HistogramClone.GetNbinsX()
        MaxXValue = HistogramClone.GetXaxis().GetBinLowEdge(Nbins+1)
        MinXValue = HistogramClone.GetXaxis().GetBinLowEdge(1)

        #this Histogram becomes the main TEfficiency
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            #using default methods (which give correct uncertainties)
            #see https://root.cern.ch/doc/master/classTEfficiency.html (c.f. section IV)
            Histogram = TEfficiency(Histogram,DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        HistogramClones.append(HistogramClone)
        NBins.append(Nbins)
        MaxXValues.append(MaxXValue)
        MinXValues.append(MinXValue)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1./histogram.Integral())


    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 1.1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    dontRebinRatio = -1
    if arguments.dontRebinRatio:
        dontRebinRatio = arguments.dontRebinRatio

    ratioRelErrMax = -1
    if arguments.ratioRelErrMax:
        ratioRelErrMax = arguments.ratioRelErrMax

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    h = TH2F("h1","",NBins[0],MinXValues[0],MaxXValues[0],110,0.,finalMax)
    h.SetTitle(";"+xAxisLabel+";"+yAxisLabel)
    h.Draw()

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[DatasetName.rfind('__')+2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,DatasetName,"NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()

        else:
            if histogram.InheritsFrom("TEfficiency") and histCounter==0:
                plotting_options = "P SAME"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)

            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)

        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TEfficiency"):
                plotting_options = "P" + " SAME"

        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    Legend.Draw()


    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()



    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            makeRatio = functools.partial (ratioHistogram,HistogramClones[0],HistogramClones[1])
            if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
            if ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, relErrMax = float (ratioRelErrMax))
            if dontRebinRatio is True:
                makeRatio = functools.partial (makeRatio, dontRebinRatio)
            Comparison = makeRatio ()
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
            else:
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd(dirName)
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
示例#6
0
def makeLimitPlot(output,obs,exp,chan,printStats=False):

	fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")

	obsLimits = {}
	
	for obsFile in obs:
		if 'width' in obsFile:
			width = obsFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'
		obsLimits[width] = createObsGraph(obsFile)	

        if  SMOOTH:
		for width,obsGraph in obsLimits.iteritems():
                	smooth_obs=TGraphSmooth("normal")
                	GraphObs_nonSmooth=obsGraph
                	obsLimits[width]=copy.deepcopy(smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005))
                	obsLimits[width].SetLineWidth(3)


	expLimits = {}
	
	for expFile in exp:
		if 'width' in expFile:
			width = expFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'	
		expLimits[width] = createExpGraph(expFile)	

    	cCL=TCanvas("cCL", "cCL",0,0,600,450)
    	gStyle.SetOptStat(0)
	gStyle.SetPadRightMargin(0.063)
	gStyle.SetPadLeftMargin(0.14)
	gStyle.SetPadBottomMargin(0.12)
	
    	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    	plotPad.Draw()	
    	plotPad.cd()


     	smoother=TGraphSmooth("normal")
    	smoother2=TGraphSmooth("normal")
	   

    
    	zprimeX=[]
    	zprimeY=[]
    	fileZPrime=open('tools/xsec_ssm.txt','r')
    	for entries in fileZPrime:
        	entry=entries.split()
        	zprimeX.append(float(entry[0]))
        	zprimeY.append(float(entry[1])/1928)
    	zpX=numpy.array(zprimeX)
    	zpY=numpy.array(zprimeY)
    	GraphZPrime=TGraph(len(zprimeX),zpX,zpY)
    	GraphZPrimeSmooth=smoother2.SmoothSuper(GraphZPrime,"linear")
    	GraphZPrimeSmooth.SetLineWidth(3)
    	GraphZPrimeSmooth.SetLineColor(ROOT.kGreen+3)
    	GraphZPrimeSmooth.SetLineStyle(2)

    	zprimePsiX=[]
    	zprimePsiY=[]
    	fileZPrimePsi=open('tools/xsec_psi.txt','r')
    	for entries in fileZPrimePsi:
        	entry=entries.split()
        	zprimePsiX.append(float(entry[0]))
        	zprimePsiY.append(float(entry[1])/1928)

   	zpPsiX=numpy.array(zprimePsiX)
	zpPsiY=numpy.array(zprimePsiY)
    	GraphZPrimePsi=TGraph(len(zprimePsiX),zpPsiX,zpPsiY)
    	GraphZPrimePsiSmooth=smoother.SmoothSuper(GraphZPrimePsi,"linear")
   	GraphZPrimePsiSmooth.SetLineWidth(3)
    	GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

#Draw the graphs:
    	plotPad.SetLogy()
    	DummyGraph=TH1F("DummyGraph","",100,200,5500)
    	DummyGraph.GetXaxis().SetTitle("M [GeV]")
	if SPIN2:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] G_{KK} / #sigma#upoint#font[12]{B}] Z")
	else:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")



    	gStyle.SetOptStat(0)
    	DummyGraph.GetXaxis().SetRangeUser(200,5500)

    	DummyGraph.SetMinimum(1e-8)
    	DummyGraph.SetMaximum(3e-4)
    	DummyGraph.GetXaxis().SetLabelSize(0.055)
    	DummyGraph.GetXaxis().SetTitleSize(0.055)
   	DummyGraph.GetXaxis().SetTitleOffset(1.05)
    	DummyGraph.GetYaxis().SetLabelSize(0.055)
    	DummyGraph.GetYaxis().SetTitleSize(0.055)
    	DummyGraph.GetYaxis().SetTitleOffset(1.3)

    	DummyGraph.Draw()

    	plCMS=TPaveLabel(.16,.76,.27,.83,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.16,.76,.27,.82,"Preliminary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetBorderSize(0)
#    	plPrelim.Draw()

    	leg=TLegend(0.420517,0.7,0.85,0.878644,"","brNDC")   
    	legWidth=TLegend(0.625,0.5,0.9,0.7,"width","brNDC")   
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.0425)
    	legWidth.SetTextSize(0.0425)
	colors = {'01':ROOT.kBlue,'03':ROOT.kRed,'05':ROOT.kGreen+3,'10':ROOT.kOrange}
#	for width in sorted(obsLimits):
#		obsGraph = obsLimits[width]
#		if colors.has_key(width):
#			obsGraph.SetLineColor(colors[width])
#		obsGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(obsGraph,"Observed 95% CL limit width 0.6%","l")
#		else:	
#			leg.AddEntry(obsGraph,"Observed 95%% CL limit width %d%%"%int(width),"l")
#
#	for width  in sorted(expLimits):
#		expGraph = expLimits[width]
#		if colors.has_key(width):
#			expGraph.SetLineColor(colors[width])
#		expGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(expGraph,"Expected 95% CL limit width 0.6%, median","l")
#		else:	
#			leg.AddEntry(expGraph,"Expected 95%% CL limit width %d%%, median"%(int(width)),"l")

	
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		obsGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(obsGraph,"Obs. 95% CL limit","l")

	for width  in sorted(expLimits):
		expGraph = expLimits[width]
		if colors.has_key(width):
			expGraph.SetLineColor(colors[width])
		expGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(expGraph,"Exp. 95% CL limit, median","l")
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		if width == '0.006':
			legWidth.AddEntry(obsGraph,"0.6%","l")
		else:	
			legWidth.AddEntry(obsGraph,"%d%%"%int(width),"l")


    	if not SPIN2:
        	GraphZPrimeSmooth.Draw("lsame")
        	GraphZPrimePsiSmooth.Draw("lsame")

	leg1=TLegend(0.625,0.35,0.825,0.5,"","brNDC")
	leg1.SetTextSize(0.0375)
	leg1.AddEntry(GraphZPrimeSmooth,"Z'_{SSM} (width 2.97%)","l")	
	leg1.AddEntry(GraphZPrimePsiSmooth,"Z'_{#Psi} (width 0.53%)","l")	
	
    	leg1.SetLineWidth(0)
    	leg1.SetLineStyle(0)
    	leg1.SetLineColor(0)
    	leg1.SetFillStyle(0)
    	leg1.SetBorderSize(0)

	leg1.Draw()

    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#plCMS.Draw()
  	plotPad.SetTicks(1,1)
	plotPad.RedrawAxis()	

	

    	leg.SetLineWidth(0)
    	leg.SetLineStyle(0)
    	leg.SetLineColor(0)
    	leg.Draw("hist")
    	legWidth.SetLineWidth(0)
    	legWidth.SetLineStyle(0)
    	legWidth.SetLineColor(0)
    	legWidth.SetFillStyle(0)
	legWidth.SetNColumns(2)
    	legWidth.Draw("hist")


	if "Moriond" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.885,.9,.99,"36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.27,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
	else:
 	      	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"2.7 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")

    	plLumi.SetTextSize(0.5)
    	plLumi.SetTextFont(42)
    	plLumi.SetFillColor(0)
    	plLumi.SetBorderSize(0)
    	plLumi.Draw()
    

	plotPad.RedrawAxis()
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		obsGraph.SetName("graphObs%s"%width)
		obsGraph.Write("graphObs%s"%width)
	for width in sorted(expLimits):
		expGraph = expLimits[width]
		expGraph.SetName("graphExp%s"%width)
		expGraph.Write("graphExp%s"%width)


   	fileForHEPData.Write()
	fileForHEPData.Close() 


    
    	cCL.Update()
    	printPlots(cCL,output)
def MakeOneHist(varXaxis, varConst, xvalues, constval):

    if len(xvalues)<=1:
        return # Do not make plot if there is only 1 xvalue
    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)
    Canvas = TCanvas("sigEff_"+varConst+str(constval)+"_vs_"+varXaxis)
    Histograms = []
    LegendEntries = []
    colorIndex = 0
    for source in input_sources: # loop over different input sources in config file
#        print "Debug:  running over input_source from: ", source['condor_dir'], " for varXaxis=", varXaxis, ", varConst=", varConst

        # Create histogram of efficiencies with appropriate binning
        xAxisBins = array('d')
        xBinWidth = xvalues[1] - xvalues[0]
        for xval in xvalues:
            xAxisBins.append(xval - xBinWidth/2.0)
        xAxisBins.append(xvalues[-1] + xBinWidth/2.0)   # add an extra bin boundary for the last bin.

        Histogram = TH1F("Histogram", ";x title;signal efficiency", len(xvalues), xAxisBins)
        Histogram.SetDirectory(0)

        # Now fill the histogram of efficiencies:
        for xval in xvalues:
            if   varXaxis=="mass" and varConst=="lifetime":
                mass = xval
                lifetime = constval
            elif varXaxis=="lifetime" and varConst=="mass":
                lifetime = xval
                mass = constval
            else:
                print "Unrecognized value of varXaxis=", varXaxis
                return
            dataset_file = "condor/%s/%s.root" % (source['condor_dir'],dataset)
            dataset_file = dataset_file.replace("MASS",     str(mass))
            dataset_file = dataset_file.replace("LIFETIME", str(lifetime))
            inputFile = TFile(dataset_file)
            HistCutflow = inputFile.Get("OSUAnalysis/" + source['channel'] + "CutFlow")
            if not HistCutflow:
                print "WARNING: Could not find histogram OSUAnalysis/" + source['channel'] + "CutFlow in file " + dataset_file + ". Will skip it and continue."
                return

            # calculate efficiency
            nbinsCutflow = HistCutflow.GetNbinsX()
            if arguments.xsecFile:
                xsec = float(signal_cross_sections[str(mass)]['value'])
                denom = xsec * intLumi
            else:
                denom = HistCutflow.GetBinContent(1)  # denominator is the first entry in the cutflow histogram
            eff    = HistCutflow.GetBinContent(nbinsCutflow) / denom
            effErr = HistCutflow.GetBinError  (nbinsCutflow) / denom
            ibin = Histogram.FindBin(xval)
            Histogram.SetBinContent(ibin, eff)
            Histogram.SetBinError  (ibin, effErr)
            print "Setting bin content for varConst = ", varConst, " = ", constval, " in ibin=", ibin, ", xval=", xval, ", eff=", eff, " +- ", effErr, ", fractional error =", effErr/eff, " numerator = ", HistCutflow.GetBinContent(nbinsCutflow), " denom = ", denom, " from file: ", dataset_file
            inputFile.Close()

        if varXaxis=="mass":
            xAxisLabel = "chargino mass [GeV]"
        elif varXaxis=="lifetime":
            xAxisLabel = "chargino c#tau [cm]"
        else:
            print "Unrecognized value of varXaxis=", varXaxis
            return

        yAxisLabel = "efficiency"

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(1)
#        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)
        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    # Finish loop over input_sources

    # formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
#        print "Adding entry to legend:  ", LegendEntries[legendIndex]
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    # finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
#        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        currentMax = histogram.GetMaximum()
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if finalMax is 0:
        finalMax = 1
##         if arguments.setYMax:
##             finalMax = float(arguments.setYMax)

    # Drawing histograms to canvas
    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    yAxisMin = 0.0
##         if arguments.setYMin:
##             yAxisMin = float(arguments.setYMin)
    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
##             if arguments.setLogY:
##                 gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()
        Canvas.cd(1)

    histCounter = 0
    plotting_options = "pe, x0"   # x0 suppresses the error bar along x
##         if arguments.plot_hist:
##             plotting_options = "HIST"

    for histogram in Histograms:
        #            histogram.SetTitle(histoTitle)
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        if histogram.InheritsFrom("TH1"):
            histogram.SetMaximum(finalMax)
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    x_left = 0.15
    x_right = 0.55
    y_min = 0.6
    y_max = 0.8
    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    customText = "chargino " + varConst + " " + str(constval)
    if varConst == "mass":
        customText += " GeV"
    elif varConst == "lifetime":
        customText += " cm"
    customText = customText.replace("lifetime", "c#tau")

    CustomLabel = TPaveLabel(x_left, 0.8, x_right, 0.9, customText, "NDC")
    CustomLabel.SetBorderSize(0)
    CustomLabel.SetFillColor(0)
    CustomLabel.SetFillStyle(0)
    CustomLabel.Draw()

    #drawing the ratio or difference plot if requested
    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
#            Comparison = ratioHistogram(Histograms[0],Histograms[1], 1000)
            Comparison = Histograms[0].Clone()
            Comparison.Divide(Histograms[1])
            Comparison.GetYaxis().SetTitle("ratio")
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
#            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(0.7, 1.3)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
        Comparison.GetYaxis().SetNdivisions(205)
#        Comparison.Draw("E0")
        Comparison.Draw("PE, X0")  # X0 suppresses error bar in x direction

    outputFile.cd()
    Canvas.Write()
    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
示例#8
0
def MakeOneDHist(histogramName,integrateDir): 

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)
    
    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)
    
    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)
    
    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"
        
    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    canvasName = histogramName
    if integrateDir is "left":
        canvasName += "_CumulativeLeft"
    elif integrateDir is "right":
        canvasName += "_CumulativeRight"
    Canvas = TCanvas(canvasName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0
    
    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)
        if arguments.generic:
            HistogramObj = inputFile.Get(source['channel'] + "/" +histogramName)  
        else: 
            HistogramObj = inputFile.Get("OSUAnalysis/" + source['channel'] + "/" +histogramName)
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."  
            return 
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")
        xAxisLabelVar = xAxisLabel
        
        if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
            yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex]
            xAxisLabelVar = xAxisLabel[0:unitBeginIndex]
        else:
            yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        if arguments.normalizeToUnitArea and arguments.makeSignificancePlots:
            unit = "Efficiency"
        else:
            unit = "Yield"
        if integrateDir is "left":
            yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
        if integrateDir is "right":
            yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
                                                        
        
        if not arguments.makeFancy and not arguments.generic:  
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
        
        markerStyle = 20 
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)
        
        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        if arguments.normalizeToUnitArea and Histogram.Integral() > 0:
            Histogram.Scale(1./Histogram.Integral())

        Histogram = MakeIntegralHist(Histogram, integrateDir)
            
        LegendEntries.append(source['legend_entry']) 
        Histograms.append(Histogram)

            
    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if arguments.setYMax:  
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    #makeSignifPlots = arguments.makeSignificancePlots
    
    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.generic:
        plotting_options = "p,e" 
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        histogram.SetTitle(histoTitle)
        if arguments.verbose:
            print "Debug:  drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor())    
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        histogram.SetMaximum(finalMax)
        histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            plotting_options = plotting_options + " SAME"
        histCounter = histCounter + 1

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()


    # Deciding which text labels to draw and drawing them
    drawHeaderLabel = False

    if arguments.makeFancy:
        drawHeaderLabel = True

    #now that flags are set, draw the appropriate labels

    if drawHeaderLabel:
        HeaderLabel.Draw()




    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            if arguments.ratioRelErrMax:
                Comparison = ratioHistogram(Histograms[0],Histograms[1],float(arguments.ratioRelErrMax))
            else:
                Comparison = ratioHistogram(Histograms[0],Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
                         
        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()
    
    if arguments.savePDFs:
        Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")