def create_canvas(self, ratio=True): if ratio: self.canvas = Canvas(width=700, height=700) self.canvas.Draw() self.canvas.cd() self.main_pad = Pad(0., 0.25, 1., 1.) self.main_pad.Draw() self.canvas.cd() self.ratio_pad = Pad(0., 0., 1., 0.25) self.ratio_pad.Draw() self.main_pad.SetTicks(True) self.main_pad.SetBottomMargin(0.) self.main_pad.SetLeftMargin(0.15) self.main_pad.SetRightMargin(0.15) self.ratio_pad.SetLeftMargin(0.15) self.ratio_pad.SetRightMargin(0.15) self.ratio_pad.SetTopMargin(0.) self.ratio_pad.SetGridy() self.ratio_pad.SetBottomMargin(0.3) else: self.canvas = Canvas(width=700, height=700) self.canvas.Draw() self.canvas.cd() self.main_pad = Pad(0., 0., 1., 1.) self.main_pad.Draw() self.canvas.cd() self.ratio_pad = Pad(-1., -1., -.9, -.9) self.ratio_pad.Draw() # put it outside the canvas self.main_pad.SetTicks(True) self.main_pad.SetTopMargin(0.15) self.main_pad.SetBottomMargin(0.15) self.main_pad.SetLeftMargin(0.15) self.main_pad.SetRightMargin(0.15)
def main(args): fileName = '/data/nawoods/lepsForSIP/lepsForSIP_M2500.root' checker = MuonCandMatchChecker('Check PF cand matching', [fileName]) checker.processSample() h = checker.hists['pfCandPt'] h.Sumw2() h.drawstyle = 'HIST' h.legendstyle = 'L' h.linewidth = 2 h.color = 'red' c = Canvas(1000, 1000) (xax, yax), lims = draw( h, c, ytitle='PF Cands', xtitle='PF Cand p_T', ) xax.SetTitleSize(0.4 * xax.GetTitleSize()) xax.SetTitleOffset(1.6) xax.SetLabelSize(0.7 * xax.GetLabelSize()) c.Print('/afs/cern.ch/user/n/nawoods/www/ptStudy/matchedCandPt.png') h2 = checker.hists['pfCandPtVsGenPt'] c2 = Canvas(1000, 1000) h2.xaxis.SetTitleOffset(1.8) h2.yaxis.SetTitleOffset(1.7) h2.xaxis.SetTitleSize(0.5 * h2.xaxis.GetTitleSize()) h2.yaxis.SetTitleSize(0.5 * h2.yaxis.GetTitleSize()) h2.xaxis.SetLabelSize(0.6 * h2.xaxis.GetLabelSize()) h2.yaxis.SetLabelSize(0.6 * h2.yaxis.GetLabelSize()) h2.xaxis.SetTitle("Gen #mu p_{T}") h2.yaxis.SetTitle("PF cand p_{T}") h2.Draw("COLZ") c2.Print( '/afs/cern.ch/user/n/nawoods/www/ptStudy/matchedCandPtVsGenPt.png') print "Out of {} good muons, {} failed PF ID ({}%).".format( checker.nTot, checker.nFailPF, 100. * float(checker.nFailPF) / checker.nTot) print( "Out of those failing PF, {} shared a track with a PF charged hadron " "({}%, {}% of the total)").format( checker.nPFMatched, 100. * checker.nPFMatched / checker.nFailPF, 100. * checker.nPFMatched / checker.nTot)
def extract_MET(f_tt, f_qcd, f_wjet): # get trees from files t_tt = f_tt.Get("Delphes") t_qcd = f_qcd.Get("Delphes") t_wjet = f_wjet.Get("Delphes") # get number of entries tt_n_entries = t_tt.GetEntries() qcd_n_entries = t_qcd.GetEntries() wjet_n_entries = t_wjet.GetEntries() # define leaves var_tt = "MissingET.MET" var_qcd = "MissingET.MET" var_wjet = "MissingET.MET" leaf_tt = t_tt.GetLeaf(var_tt) leaf_qcd = t_qcd.GetLeaf(var_qcd) leaf_wjet = t_wjet.GetLeaf(var_wjet) # create the histograms MET_tt = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_tt', legendstyle='L') MET_qcd = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_qcd', legendstyle='L') MET_wjet = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_wjet', legendstyle='L') # FILLING THE TREE fill_MET_tree(tt_n_entries, t_tt, leaf_tt, MET_tt) fill_MET_tree(qcd_n_entries, t_qcd, leaf_qcd, MET_qcd) fill_MET_tree(wjet_n_entries, t_wjet, leaf_wjet, MET_wjet) #set line colors MET_tt.SetLineColor('blue') MET_qcd.SetLineColor('green') MET_wjet.SetLineColor('red') #begin drawing stuff c1 = Canvas() MET_qcd.SetStats(0) MET_qcd.Draw('HIST') MET_tt.Draw('HIST SAME') MET_wjet.Draw('HIST SAME') #make legend l1 = Legend([MET_tt, MET_qcd, MET_wjet], textfont=42, textsize=.03) l1.Draw() #save as pdf c1.SaveAs("../plots/MET_plots/MET.pdf") #make the plots wait on screen wait(True)
def draw_efficiency(eff_s, rej_b, field, category, textsize=22): xtitle = get_xtitle(field) c = Canvas() c.SetGridx() c.SetGridy() eff_s.painted_graph.yaxis.SetRangeUser(0, 1.10) eff_s.painted_graph.yaxis.title = 'Efficiency' eff_s.painted_graph.xaxis.title = xtitle eff_s.painted_graph.Draw('AP') rej_b.color = 'red' rej_b.markerstyle = 'square' rej_b.painted_graph.Draw('sameP') right_axis = ROOT.TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(), 0, 1.10, 510, "+L") right_axis.SetLineColor(ROOT.kRed) right_axis.SetLabelColor(ROOT.kRed) right_axis.SetTextColor(ROOT.kRed) right_axis.SetTitle('Rejection = 1 - #epsilon_{B}') right_axis.Draw('same') ROOT.gStyle.SetPadTickY(0) ROOT.gPad.Update() ROOT.gStyle.SetPadTickY(1) label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label) label.SetNDC() label.SetTextFont(43) label.SetTextSize(textsize) label.Draw() leg = Legend([eff_s, rej_b], pad=c) # textsize=20, leftmargin=0.6, topmargin=0.6) leg.Draw('same') return c
def draw_hists(hists, field, category, textsize=22, logy=False, unit_area=False): xtitle = get_xtitle(field) c = Canvas() c.SetGridx() c.SetGridy() c.SetLogy(logy) if not isinstance(hists, (list, tuple)): hists = [hists] if unit_area: for h in hists: if h.integral() != 0: h /= h.integral() hists[0].xaxis.title = xtitle hists[0].yaxis.title = 'Arbitrary Unit' y_max = get_ymax(hists) hists[0].yaxis.SetRangeUser(0., 1.05 * y_max) hists[0].Draw('HIST') colors = [ 'black', 'red', 'orange', 'blue', 'green', 'purple', 'yellow', 'pink', ] if len(hists) > len(colors): colors = len(hists) * colors for hist, col in zip(hists, colors): hist.color = col hist.color = col hist.fillstyle = 'hollow' hist.markersize = 0 hist.linewidth = 2 hist.linestyle = 'solid' hist.drawstyle = 'hist E0' hist.legendstyle = 'l' hist.Draw('SAMEHIST') label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label) label.SetNDC() label.SetTextFont(43) label.SetTextSize(textsize) label.Draw() leg = Legend(hists, pad=c, textsize=20) # textsize=20, leftmargin=0.6, topmargin=0.6) leg.Draw('same') return c
def plotSummary(name, closure, xmin=0, xmax=1, xTitle='m_{vis} [GeV]'): histoSmoothRatios = [] for hname, graph in closure.data['True/Est'].items(): if 'Histo' in hname and 'Smooth' in hname and not 'Error' in hname: histoSmoothRatios.append(graph) ################ Plot ratios histoDummyRatio = Hist(1, xmin, xmax, type='F') values = [] for ratio in histoSmoothRatios: for p in xrange(ratio.GetN()): values.append(ratio.GetY()[p]) maxi = max(values) mini = min(values) maxi = maxi * 1.1 if maxi > 0 else maxi * 0.9 mini = mini * 1.1 if mini < 0 else mini * 0.9 histoDummyRatio.SetAxisRange(mini, maxi, 'Y') ## for ratio in histoSmoothRatios: ratio.SetLineColor(ROOT.kGray + 3) ratio.SetLineWidth(1) ## canvasRatio = Canvas(800, 800) canvasRatio.SetName('Ratio_Summary_Canvas') histoDummyRatio.SetXTitle(xTitle) histoDummyRatio.SetYTitle('Ratio') histoDummyRatio.Draw() for ratio in histoSmoothRatios: ratio.Draw('l same') canvasRatio.Print( 'results/{NAME}_NonClosure_Ratio_Summary.png'.format(NAME=name))
def draw_DR(DR_tt, DR_qcd, DR_wjet): #set line colors DR_tt.SetLineColor(4) DR_qcd.SetLineColor(8) DR_wjet.SetLineColor(2) DR_tt.legendstyle = 'L' DR_qcd.legendstyle = 'L' DR_wjet.legendstyle = 'L' #begin drawing stuff c1 = Canvas() DR_qcd.SetStats(0) DR_qcd.Draw('HIST') DR_tt.Draw('HIST SAME') DR_wjet.Draw('HIST SAME') #make legend l1 = Legend([DR_tt, DR_qcd, DR_wjet], textfont=42, textsize=.03) l1.Draw() #save as pdf c1.SaveAs("DeltaR.pdf") #make the plots wait on screen wait(True)
def plotResults(variable, data, templates, results): resCan = Canvas() leg = Legend(nTemplates + 2) data.Draw('PE') leg.AddEntry(data, style='LEP') nBins = len(inputTemplates[variable]['data'][whichBinFromFile]) h_tSumAfter = Hist(nBins, 0, nBins, title='after_' + variable) if useT1: plotTemplateAfter(templates[tNames['t1']], results[tNames['t1']][0], resCan, leg, h_tSumAfter) pass if useT2: plotTemplateAfter(templates[tNames['t2']], results[tNames['t2']][0], resCan, leg, h_tSumAfter) pass if useT3: plotTemplateAfter(templates[tNames['t3']], results[tNames['t3']][0], resCan, leg, h_tSumAfter) pass if useT4: plotTemplateAfter(templates[tNames['t4']], results[tNames['t4']][0], resCan, leg, h_tSumAfter) pass leg.Draw() h_tSumAfter.SetLineColor(2) h_tSumAfter.SetLineStyle(7) h_tSumAfter.SetMarkerSize(0) h_tSumAfter.Draw('SAME HIST') resCan.Update() return resCan, h_tSumAfter
def checkOnMC(unfolding, method): global bins, nbins RooUnfold.SVD_n_toy = 1000 pulls = [] for sub in range(1,9): inputFile2 = File('../data/unfolding_merged_sub%d.root' % sub, 'read') h_data = asrootpy(inputFile2.unfoldingAnalyserElectronChannel.measured.Rebin(nbins, 'measured', bins)) nEvents = inputFile2.EventFilter.EventCounter.GetBinContent(1) lumiweight = 164.5 * 5050 / nEvents # print sub, nEvents h_data.Scale(lumiweight) doUnfoldingSequence(unfolding, h_data, method, '_sub%d' %sub) pull = unfolding.pull_inputErrorOnly() # unfolding.printTable() pulls.append(pull) unfolding.Reset() allpulls = [] for pull in pulls: allpulls.extend(pull) h_allpulls = Hist(100,-30,30) filling = h_allpulls.Fill for entry in allpulls: filling(entry) fit = h_allpulls.Fit('gaus', 'WWS') h_fit = asrootpy(h_allpulls.GetFunction("gaus").GetHistogram()) canvas = Canvas(width=1600, height=1000) canvas.SetLeftMargin(0.15) canvas.SetBottomMargin(0.15) canvas.SetTopMargin(0.10) canvas.SetRightMargin(0.05) h_allpulls.Draw() fit.Draw('same') canvas.SaveAs('plots/Pull_allBins_withFit.png') plt.figure(figsize=(16, 10), dpi=100) rplt.errorbar(h_allpulls, label=r'Pull distribution for all bins', emptybins=False) rplt.hist(h_fit, label=r'fit') plt.xlabel('(unfolded-true)/error', CMS.x_axis_title) plt.ylabel('entries', CMS.y_axis_title) plt.title('Pull distribution for all bins', CMS.title) plt.tick_params(**CMS.axis_label_major) plt.tick_params(**CMS.axis_label_minor) plt.legend(numpoints=1) plt.savefig('plots/Pull_allBins.png') #individual bins for bin_i in range(nbins): h_pull = Hist(100,-30,30) for pull in pulls: h_pull.Fill(pull[bin_i]) plt.figure(figsize=(16, 10), dpi=100) rplt.errorbar(h_pull, label=r'Pull distribution for bin %d' % (bin_i + 1), emptybins=False) plt.xlabel('(unfolded-true)/error', CMS.x_axis_title) plt.ylabel('entries', CMS.y_axis_title) plt.title('Pull distribution for bin %d' % (bin_i + 1), CMS.title) plt.savefig('Pull_bin_%d.png' % (bin_i + 1))
def do_stuff(file_name, plot=True): tiq_data = TIQData(file_name) NFRAMES = 100 LFRAMES = 1024 tiq_data.read(nframes=NFRAMES, lframes=LFRAMES, sframes=1) center = tiq_data.center # do fft ff, pp, _ = tiq_data.get_fft() freq_lower = center + ff[0] / 1e6 freq_upper = center + ff[-1] / 1e6 # create hist h1 = Hist(NFRAMES * LFRAMES, freq_lower, freq_upper, name='h1', title='Frequency Spectrum', drawstyle='hist', legendstyle='F', fillstyle='/', linecolor='green') for i in range(len(pp)): h1.set_bin_content(i, pp[i]) # set visual attributes h1.GetXaxis().SetTitle('Freuqency [MHz]') h1.linecolor = 'green' # h1.fillcolor = 'green' # h1.fillstyle = '/' if plot: # plot c = Canvas(name='c1', width=700, height=500) c.set_left_margin(0.15) c.set_bottom_margin(0.15) c.set_top_margin(0.10) c.set_right_margin(0.05) c.toggle_editor() c.toggle_event_status() c.toggle_tool_bar() # c.set_crosshair() h1.Draw() # create the legend legend = Legend([h1], pad=c, header='Header', leftmargin=0.05, rightmargin=0.5) legend.Draw() # wait for key press wait()
def __prepare_canvas(canvas_args): style = gStyle style.SetOptStat(0) canvas = Canvas(**canvas_args) canvas.SetGridx(True) canvas.SetGridy(True) canvas.title = "" return canvas, style
def plot(params, rates): canvas = Canvas(width=500, height=500) draw_axes(params) draw_rates(params, rates) HGCAL_label(text='HGCAL Simulation', pad=canvas) canvas.SetLogy() canvas.RedrawAxis() canvas.Print('%s.png' % params.name) canvas.Print('%s.pdf' % params.name) canvas.Print('%s.C' % params.name)
def plot(params, efficiency): canvas = Canvas(width=500, height=500) draw_axes(params) draw_efficiency(params, efficiency) draw_lines(params) HGCAL_label(text='HGCAL Simulation', pad=canvas) draw_legends(params) canvas.RedrawAxis() canvas.Print('%s.png' % params.name) canvas.Print('%s.pdf' % params.name) canvas.Print('%s.C' % params.name) return canvas
def plot_comparisons(input_file, comparison_plots): with root_open(input_file) as file: for name,histo_config in comparison_plots.items(): canvas = Canvas(1200,700) canvas.SetLeftMargin(0.08) canvas.SetRightMargin(0.12) histogram = file.Get(histo_config.name) if len(histo_config.range)==2: histogram.SetAxisRange(histo_config.range[0], histo_config.range[1], 'X') histogram.color = histo_config.color histogram.markerstyle = histo_config.marker histogram.Draw() canvas.Print('./plots/{}.png'.format(name))
def makePage(histos, fileName, fileDescr, separateFiles, logscale): """ Prepares a canvas with one histogram per pad """ import rootpy from rootpy.plotting import Hist, Canvas from ROOT import kBlue, gPad log = logging.getLogger('pyroplot') cans = {} log.info("Drawing histograms ..") for idx, name in enumerate(sorted(histos.keys())): if separateFiles: log.debug("Creating new canvas with index %d." % (idx)) c = Canvas(600, 800) cans[name] = c markCanvas(c, fileName, 0.05, y=0.009, size=0.025, color=2) if not separateFiles and (idx) % 6 == 0: log.debug("Creating new canvas with index %d." % (idx / 6)) # start a new canvas c = Canvas(600, 800) cans[fileName + '/' + name] = c c.Divide(2, 3) markCanvas(c, fileName, 0.05, y=0.009, size=0.025, color=2) # draw the histogram hist = histos[name] log.debug("Drawing histogram #" + str(idx % 6 + 1) + ": " + hist.GetName() + " (" + hist.__class__.__name__ + ") in canvas #" + str(int(idx / 6))) hist.color = kBlue if not separateFiles: c.cd(idx % 6 + 1) if logscale: gPad.SetLogy() plotHistos(histos=[hist], text=name) if fileDescr: markPad(text=fileDescr, x=.14, y=.8, size=0.041, color=2) return cans
def draw_curve_7(_func, name, title, ylow, yhigh): """ Draw 7TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TauTriggerCorrections( os.path.join(base, 'triggerSF_%s.root' % trigger)) func = getattr(tool, _func) eff = map(lambda x: func(x, 0), pt) eff_low = map(lambda x: func(x, -1), pt) eff_high = map(lambda x: func(x, 1), pt) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.4, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AC') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3C SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
def test_cmstdr(): style = get_style('CMSTDR') with style: canvas = Canvas() hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution") ROOT.gRandom.SetSeed() for i in xrange(1000): hpx.Fill(ROOT.gRandom.Gaus()) hpx.GetXaxis().SetTitle("random variable [unit]") hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]") hpx.SetMaximum(100.) hpx.Draw() CMS_label("Testing 2050", sqrts=100) if INTERACTIVE: wait()
def test_lhcb(): style = get_style('LHCb') with style: canvas = Canvas() hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution") ROOT.gRandom.SetSeed() for i in xrange(1000): hpx.Fill(ROOT.gRandom.Gaus()) hpx.GetXaxis().SetTitle("random variable [unit]") hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]") hpx.SetMaximum(80.) hpx.Draw() LHCb_label("R", "preliminary") if INTERACTIVE: wait()
def plot_distribution(self, output_file): f = r.TFile.Open(os.path.join(self.input_directory, output_file), 'read') intuple = f.Get('pythia8-Geant4') h = Hist2D(100, 0, 350, 100, 0, 6) for muon in intuple: px = muon.px py = muon.py pz = muon.pz p = np.sqrt(px**2 + py**2 + pz**2) pt = np.sqrt(px**2 + py**2) h.Fill(p, pt) c = Canvas() r.gStyle.SetOptStat(11111111) h.Draw("colz") c.Draw() c.SaveAs(os.path.join(self.input_directory, "p_dist.png"))
def plot_event(name, canvas): primitives = canvas.GetListOfPrimitives() histo = None point = None for primitive in primitives: if primitive.InheritsFrom(TH2Poly.Class()): histo = primitive if primitive.InheritsFrom(TMarker.Class()): point = primitive histo.SetXTitle('x [cm]') histo.SetYTitle('y [cm]') canvas_new = Canvas(700, 700) histo.SetAxisRange(77,100,'X') histo.Draw('colz') point.Draw() canvas_new.SetLogz() canvas_new.Print('./plots/event_{}.png'.format(name))
def draw_efficiencies(effs, field, category, textsize=22): xtitle = get_xtitle(field) c = Canvas() c.SetGridx() c.SetGridy() if not isinstance(effs, (list, tuple)): effs = [effs] h = Hist(10, effs[0].painted_graph.xaxis.min, effs[0].painted_graph.xaxis.max) h.yaxis.SetRangeUser(0.0, 1.1) h.Draw('HIST') h.yaxis.title = 'Efficiency' h.xaxis.title = xtitle colors = [ 'black', 'red', 'orange', 'blue', 'green', 'purple', 'yellow', 'pink', ] if len(effs) > len(colors): colors = len(effs) * colors for eff, col in zip(effs, colors): eff.color = col eff.color = col eff.painted_graph.legendstyle = 'l' eff.painted_graph.Draw('SAMEP') label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label) label.SetNDC() label.SetTextFont(43) label.SetTextSize(textsize) label.Draw() leg = Legend(effs, pad=c, textsize=20) # textsize=20, leftmargin=0.6, topmargin=0.6) leg.Draw('same') return c
def draw_stuff(): ROOT.TH1.AddDirectory(ROOT.kFALSE) #TH1.SetDirectory(0) f = root_open( "/eos/cms/store/group/dpg_dt/comm_dt/dtRootple2015/DTTree_Run259685.root", "r") f2 = root_open("tmp.root", "RECREATE") for path, dirs, objects in f.walk(): print(objects) tree = f.DTTree #for branch in f.DTTree.branchnames: # print branch canvas = Canvas() hist = Hist(100, 0.0, 1E3, name='h' + '_' + '_IPchi2', type='D') #tree.Draw('Ndigis', '', '', hist) selection = "digi_wheel==-1 & digi_station==4 & digi_sector==4 & digi_sl==1 & digi_layer==1 & (digi_time < 300 | digi_time > 700)" # & digi_wire=='wire0'" h = tree.Draw('timestamp', selection=selection, create_hist=True) #h.SetDirectory(0) canvas.SaveAs("test.png")
def bkg_fitting(filename): if filename[-5:] == '.root': filename = filename[:-5] s_root_path = './data/%s.root' % filename f_integral = root_open(s_root_path, 'read') conversion_to_num_electrons = 1. / ( 250e6) / 50. / 10. / 1.6e-19 * 2. / 2**12 # find fit limits l_percentiles = [10, 90] lb_fit, ub_fit = -30, 30 # grab histogram h_bkg = f_integral.bkgd_data_integral_hist c_fit = Canvas() h_bkg.Draw() fit_func = root.TF1('fit_func', 'gaus', lb_fit, ub_fit) h_bkg.Fit('fit_func', 'MELSR') fit_func.Draw('same') c_fit.Update() d_fit = {} d_fit['bkg_mean'] = fit_func.GetParameter(1) * conversion_to_num_electrons d_fit['bkg_std'] = fit_func.GetParameter(2) * conversion_to_num_electrons d_fit['bkg_mean_unc'] = fit_func.GetParError( 1) * conversion_to_num_electrons d_fit['bkg_std_unc'] = fit_func.GetParError( 2) * conversion_to_num_electrons print d_fit raw_input('Press enter to continue...') pickle.dump(d_fit, open('./bkg_results/bkg_%s.p' % (file), 'w'))
def plot_distributions(input_file, distribution_plots): with root_open(input_file) as file: for name,histo_configs in distribution_plots.items(): canvas = Canvas(700,700) legend = Legend(len(histo_configs), leftmargin=0.4, margin=0.3) histograms = [] for histo_config in histo_configs: histogram = file.Get(histo_config.name) if len(histo_config.range)==2: histogram.SetAxisRange(histo_config.range[0], histo_config.range[1], 'X') histogram.color = histo_config.color histogram.markerstyle = histo_config.marker legend.AddEntry(histogram, label=histo_config.legend, style='ep') histograms.append(histogram) xmin, xmax, ymin, ymax = get_limits(histograms, logy=False) option = '' for histogram in histograms: histogram.SetAxisRange(ymin,ymax,'Y') histogram.Draw(option) option += ' same' legend.Draw() canvas.Print('plots/{}.png'.format(name))
def draw_channel(self, channelNumber): print '\n\n---------- Draw channel ' + str( channelNumber) + ' ----------\n\n' assert channelNumber >= 1 and channelNumber <= 17 and type( channelNumber) == type( 1), 'Improper channel number given - please check input' failStatus = -1 # grab required histograms bkgFile = self.lProcessedRootFiles[0] signalFile = self.lProcessedRootFiles[self.dLightLevels[channelNumber]] hSignal = signalFile.Get('spe_' + str(channelNumber)) hSignal.DrawStyle = 'hist' c1 = Canvas() hSignal.Draw('') c1.Update() raw_input('Please press enter when finished...')
def draw(event, vects, radii=None, colors=None, etamin=-5, etamax=5, phimin=-math.pi, phimax=math.pi): """ This function creates a 2D view of an event over eta and phi """ c = Canvas() display = Hist2D(100, etamin, etamax, 100, phimin, phimax) display.SetXTitle('#eta') display.SetYTitle('#phi') display.Draw() things = [] for i, vect in enumerate(vects): radius = .4 if radii: radius = radii[i] thing = Ellipse(vect.Eta(), vect.Phi(), radius, radius) thing.SetLineWidth(3) if colors: thing.SetLineColor(colors[i]) thing.SetFillStyle(0) thing.Draw() things.append(thing) c.SaveAs('eventviews/event_%i.png' % event.EventNumber)
def CreatCanvas(self): H_ref = 600 W_ref = 800 W = W_ref H = H_ref T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref # Set the tdr style canvas = Canvas(width=W, height=H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) canvas.SetTickx(0) canvas.SetTicky(0) return canvas
def draw_MT(MT_tt, MT_qcd, MT_wjet): #set line colors MT_tt.SetLineColor(4) MT_qcd.SetLineColor(8) MT_wjet.SetLineColor(2) MT_tt.legendstyle = 'L' MT_qcd.legendstyle = 'L' MT_wjet.legendstyle = 'L' #begin drawing stuff c1 = Canvas() MT_qcd.SetStats(0) MT_qcd.Draw('HIST') MT_tt.Draw('HIST SAME') MT_wjet.Draw('HIST SAME') #make legend l1 = Legend([MT_tt, MT_qcd, MT_wjet], textfont=42, textsize=.03) l1.Draw() #save as pdf c1.SaveAs("MT.pdf")
def draw_HT(HT_tt, HT_qcd, HT_wjet): #set line colors HT_tt.SetLineColor(4) HT_qcd.SetLineColor(8) HT_wjet.SetLineColor(2) HT_tt.legendstyle = 'L' HT_qcd.legendstyle = 'L' HT_wjet.legendstyle = 'L' #begin drawing stuff c1 = Canvas() HT_wjet.SetStats(0) HT_wjet.Draw('HIST') HT_tt.Draw('HIST SAME') HT_qcd.Draw('HIST SAME') #make legend l1 = Legend([HT_tt, HT_qcd, HT_wjet], textfont=42, textsize=.03) l1.Draw() #save as pdf c1.SaveAs("HT.pdf")
def draw_DPHImj(DPHI_tt, DPHI_qcd, DPHI_wjet): #set line colors DPHI_tt.SetLineColor(4) DPHI_qcd.SetLineColor(8) DPHI_wjet.SetLineColor(2) DPHI_tt.legendstyle = 'L' DPHI_qcd.legendstyle = 'L' DPHI_wjet.legendstyle = 'L' #begin drawing stuff c1 = Canvas() DPHI_qcd.SetStats(0) DPHI_qcd.Draw('HIST') DPHI_tt.Draw('HIST SAME') DPHI_wjet.Draw('HIST SAME') #make legend l1 = Legend([DPHI_tt, DPHI_qcd, DPHI_wjet], textfont=42, textsize=.03) l1.Draw() #save as pdf c1.SaveAs("DPHI_metjet.pdf")