示例#1
0
def drawPtResponse(ax, hist, filename=""):
    ax.set_xlabel(r"$p_{T,obs}\left[GeV\right]$")  # Add x-axis labels for bottom row
    ax.set_ylabel(r"$p_{T,true}\left[GeV\right]$")  # Add x-axis labels for bottom row
    # rplt.hist2d(hist, label = "Hist",norm=LogNorm(),colorbar=True)
    rplt.hist2d(hist, label="Hist", norm=LogNorm())
    ax.set_xlim([5, 150])
    ax.set_ylim([5, 150])
示例#2
0
def drawResponse(ax, hist):
    ax.set_xlabel(r"$j_{T,obs}\left[GeV\right]$")  # Add x-axis labels for bottom row
    ax.set_ylabel(r"$j_{T,true}\left[GeV\right]$")  # Add x-axis labels for bottom row
    # rplt.hist2d(hist, label = "Hist",norm=LogNorm(),colorbar=True)
    rplt.hist2d(hist, label="Hist")
    ax.set_xlim([0.01, 10])
    ax.set_ylim([0.01, 10])
示例#3
0
def test_hist2d():
    from rootpy.plotting import root2matplotlib as rplt
    from matplotlib import pyplot
    import numpy as np
    if not hasattr(pyplot, 'hist2d'):
        raise SkipTest("matplotlib is too old")
    a = Hist2D(100, -3, 3, 100, 0, 6)
    a.fill_array(
        np.random.multivariate_normal(mean=(0, 3),
                                      cov=[[1, .5], [.5, 1]],
                                      size=(1000, )))
    rplt.hist2d(a)
示例#4
0
def test_hist2d():
    from rootpy.plotting import root2matplotlib as rplt
    from matplotlib import pyplot
    import numpy as np
    if not hasattr(pyplot, 'hist2d'):
        raise SkipTest("matplotlib is too old")
    a = Hist2D(100, -3, 3, 100, 0, 6)
    a.fill_array(np.random.multivariate_normal(
        mean=(0, 3),
        cov=[[1, .5], [.5, 1]],
        size=(1000,)))
    rplt.hist2d(a)
def draw(hist, ncols=1, nrows=1, cell=1, fig=None, figsize=(10, 5)):
    if fig is None:
        fig = plt.figure(figsize=figsize, dpi=100, facecolor='white')
    else:
        plt.figure(fig.number)
    subplot = fig.add_subplot(nrows, ncols, cell)
    subplot.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    if isinstance(hist, r.TH2):
        rplt.hist2d(hist, axes=subplot)
    else:
        rplt.errorbar([hist], xerr=False, emptybins=False)
    # plt.show()
    return fig
示例#6
0
def draw(hist, ncols=1, nrows=1, cell=1, fig=None, figsize=goldenaspect(3), **kwargs):
    if fig is None:
        fig = plt.figure(figsize=figsize, dpi=1200, facecolor="white")
    else:
        plt.figure(fig.number)
    subplot = fig.add_subplot(nrows, ncols, cell)
    # subplot.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    # subplot.ticklabel_format(scilimits=(0, 0))
    if isinstance(hist, R.TH2):
        rplt.hist2d(hist, axes=subplot, **kwargs)
    else:
        rplt.errorbar([hist], xerr=False, emptybins=False, **kwargs)
    # plt.show()
    return fig
示例#7
0
def draw2D(hist, title):
    fig, axs = plt.subplots(1, 1, figsize=(10, 10), sharex=True, sharey=True)
    # axs = axs.reshape(4)
    ax = axs
    ax.set_xlabel(r"$j_T$")
    ax.set_ylabel(r"$p_{T,jet}$")
    ax.set_xscale("log")
    # ax.set_yscale('log')
    # rplt.hist2d(hist,label="Hist",norm=PowerNorm(0.8),colorbar=True)
    rplt.hist2d(hist, label="Hist", norm=LogNorm(), colorbar=True)
    ax.set_xlim([0.01, 10])
    ax.set_ylim([5, 100])
    ax.text(
        1,
        7,
        title,
        fontsize=10,
        bbox=dict(boxstyle="round", ec=(1.0, 0.5, 0.5), fc=(1.0, 0.8, 0.8), alpha=0.8),
    )
    plt.show()
示例#8
0
def draw2DComparison(hists, titles):
    fig, axs = plt.subplots(1, 2, figsize=(10, 10))
    axs = axs.reshape(2)
    for ax, h, title in zip(axs, hists, titles):
        ax.set_xlabel(r"$j_T$")
        ax.set_ylabel(r"$p_{T,jet}$")
        ax.set_xscale("log")
        # ax.set_yscale('log')
        # rplt.hist2d(hist,label="Hist",norm=PowerNorm(0.8),colorbar=True)
        rplt.hist2d(h, axes=ax, label=title, norm=LogNorm(), colorbar=True)
        ax.set_xlim([0.01, 10])
        ax.set_ylim([5, 100])
        ax.text(
            1,
            7,
            title,
            fontsize=10,
            bbox=dict(
                boxstyle="round", ec=(1.0, 0.5, 0.5), fc=(1.0, 0.8, 0.8), alpha=0.8
            ),
        )
    plt.show()
示例#9
0
def sdraw(hists, xlabel="", ylabel="", xlims=None, ylims=None, space=0):
    nr, nc = 2, 3
    fig = plt.figure(figsize=goldenaspect(6.5, nr, nc))
    gs = gridspec.GridSpec(nr, nc, wspace=space, hspace=space, left=0.1, right=0.95, bottom=0.175)
    for irow in range(0, nr):
        for icol in range(0, nc):
            hnum = 3 * irow + (icol + 1)
            h = hists[hnum - 1]
            ax = plt.subplot(gs[irow, icol])
            rplt.hist2d(h, axes=ax)  # , norm=LogNorm())
            if xlims is not None:
                plt.xlim(xlims)
            if ylims is not None:
                plt.ylim(ylims)
            if icol > 0:
                ax.set_yticklabels("")
            if irow + 1 < nr:
                ax.set_xticklabels("")
    fig.add_axes([0.06, 0.105, 0.94, 0.895], frameon=False)
    plt.xticks([])
    plt.yticks([])
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    return fig
示例#10
0
    0.005, r'pPb $\sqrt{s_{NN}} = 5.02 \mathrm{TeV}$'
    '\n  Full jets\n'
    r'Anti-$k_T$, R=0.4'
    '\nJet Cone',
    fontsize=7
)  #Add text to second subfigure, first parameters are coordinates in the drawn scale/units

for jets, label in zip((measJets, trueJets), ('Measured', 'True')):
    rplt.errorbar(jets, xerr=False, emptybins=False, axes=ax1, label=label)
ax1.legend(loc='best')

ax1.grid(True)  #Draw grid
ratio = measJets.Clone()
ratio.Divide(trueJets)
rplt.errorbar(ratio, xerr=False, emptybins=False, axes=ax2)
ax1.set_xlim([5, 500])  #Set x-axis limits
ax1.set_ylim([5e-12, 2e0])  #Set y-axis limits

rplt.hist2d(jetPtResponse, axes=ax3, label="Response", norm=LogNorm())
x1 = linspace(0, 500, 50)
y1 = linspace(0, 500, 50)
plt.plot(x1, y1, '-r')
ax3.set_xlim([5, 500])
ax3.set_ylim([5, 500])
ax3.set_yscale('log')

plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)  #Set space between subfigures to 0
#plt.savefig(name,format='pdf') #Save figure
plt.show()  #Draw figure on screen
def make_correlation_plot_from_file( channel, variable, fit_variables, CoM, title, x_title, y_title, x_limits, y_limits, rebin = 1, save_folder = 'plots/fitchecks/', save_as = ['pdf', 'png'] ):
# global b_tag_bin
    parameters = ["TTJet", "SingleTop", "V+Jets", "QCD"]
    parameters_latex = []
    for template in parameters:
        parameters_latex.append(samples_latex[template])
        
    input_file = open( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), "r" )
    # cycle through the lines in the file
    for line_number, line in enumerate( input_file ):
        # for now, only make plots for the fits for the central measurement
        if "central" in line:
            # matrix we want begins 11 lines below the line with the measurement ("central")
            line_number = line_number + 11
            break
    input_file.close()
    
    #Note: For some reason, the fit outputs the correlation matrix with the templates in the following order:
    #parameter1: QCD
    #parameter2: SingleTop
    #parameter3: TTJet
    #parameter4: V+Jets
        
    for variable_bin in variable_bins_ROOT[variable]:
        weights = {}
        if channel == 'electron':
            #formula to calculate the number of lines below "central" to access in each loop
            number_of_lines_down = (variable_bins_ROOT[variable].index( variable_bin ) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down )
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 1 )
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 2 )
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]            
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 3 )
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        if channel == 'muon':
            #formula to calculate the number of lines below "central" to access in each bin loop
            number_of_lines_down =  ( len( variable_bins_ROOT [variable] ) * 12 ) + ( variable_bins_ROOT[variable].index( variable_bin ) * 12 )
            
            #Get QCD correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down )
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 1 )
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 2 )
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]
            
            #Get V+Jets correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 3 )
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        #Create histogram
        histogram_properties = Histogram_properties()
        histogram_properties.title = title
        histogram_properties.name = 'Correlations_' + channel + '_' + variable + '_' + variable_bin
        histogram_properties.y_axis_title = y_title
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_limits = y_limits
        histogram_properties.x_limits = x_limits
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'

        #initialise 2D histogram
        a = Hist2D( 4, 0, 4, 4, 0, 4 )
        #fill histogram
        for i in range( len( parameters ) ):
            for j in range( len( parameters ) ):
                a.fill( float( i ), float( j ), float( weights["%s_%s" % ( parameters[i], parameters[j] )] ) )
        # create figure
        plt.figure( figsize = CMS.figsize, dpi = CMS.dpi, facecolor = CMS.facecolor )
        # make subplot(?) 
        fig, ax = plt.subplots( nrows = 1, ncols = 1 )
        rplt.hist2d( a )
        plt.subplots_adjust( right = 0.8 )

        #Set labels and formats for titles and axes
        plt.ylabel( histogram_properties.y_axis_title )
        plt.xlabel( histogram_properties.x_axis_title )
        plt.title( histogram_properties.title )
        x_limits = histogram_properties.x_limits
        y_limits = histogram_properties.y_limits
        ax.set_xticklabels( parameters_latex )
        ax.set_yticklabels( parameters_latex )
        ax.set_xticks( [0.5, 1.5, 2.5, 3.5] )
        ax.set_yticks( [0.5, 1.5, 2.5, 3.5] )
        plt.setp( ax.get_xticklabels(), visible = True )
        plt.setp( ax.get_yticklabels(), visible = True )

        #create and draw colour bar to the right of the main plot
        im = rplt.imshow( a, axes = ax, vmin = -1.0, vmax = 1.0 )
        #set location and dimensions (left, lower, width, height)
        cbar_ax = fig.add_axes( [0.85, 0.10, 0.05, 0.8] )
        fig.colorbar( im, cax = cbar_ax )

        for xpoint in range( len( parameters ) ):
            for ypoint in range( len( parameters ) ):
                correlation_value = weights["%s_%s" % ( parameters[xpoint], parameters[ypoint] )]
                ax.annotate( correlation_value, xy = ( xpoint + 0.5, ypoint + 0.5 ), ha = 'center', va = 'center', bbox = dict( fc = 'white', ec = 'none' ) )
        for save in save_as:
            plt.savefig( save_folder + histogram_properties.name + '.' + save )
        plt.close(fig)
    plt.close('all')
示例#12
0
print __doc__
import ROOT
from matplotlib import pyplot as plt
from rootpy.plotting import root2matplotlib as rplt
from rootpy.plotting import Hist2D
import numpy as np

a = Hist2D(100, -3, 3, 100, 0, 6)
a.fill_array(
    np.random.multivariate_normal(mean=(0, 3),
                                  cov=np.arange(4).reshape(2, 2),
                                  size=(1E6, )))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))

ax1.set_title('hist2d')
rplt.hist2d(a, axes=ax1)

ax2.set_title('imshow')
im = rplt.imshow(a, axes=ax2)

ax3.set_title('contour')
rplt.contour(a, axes=ax3)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

if not ROOT.gROOT.IsBatch():
    plt.show()
                
            data_combo = np.stack(
                (data_integral_1,      # The pulse integral on y axis
                 data_pulseheight_1),    # The pulseheight on x axis
                 axis=-1)               # To get the direction correct

            a = rootpy.plotting.Hist2D(100, 0, 100000, 100, 0, 4500)
            a.fill_array(data_combo)
            
            canvas = rootpy.plotting.Canvas(width = 800, height = 600)    
            a.Draw("colz")
            rootpy.interactive.wait()
            
            fig = plt.figure(station)
            
            root2matplotlib.hist2d(a)
                       
            fig.subplots_adjust(right=0.8)
            cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
            fig.colorbar(im, cax=cbar_ax)
            
            fig.savefig(
                'hist2d.pdf',    # Name of the file
                bbox_inches='tight')   

            plt.close(fig)
        
print "####### I'm Done Bitches! #######"


################################## FOOTER ################################## 
 
 # Combine the detector data
 data_combo = np.stack(
     (data_integral_detector,      # The pulse integral on y axis
      data_pulseheight_detector),    # The pulseheight on x axis
      axis=-1)               # To get the direction correct
 
 # Initiate a 2D histogram (ROOT style)
 histogram_combo_detector = rootpy.plotting.Hist2D(100, 0, 150000, 100, 0, 4500)
 
 # Fill the Histogram
 histogram_combo_detector.fill_array(data_combo)
             
 # Plot the histogram with logarithmic colors in correct place
 if detector == 0:
     root2matplotlib.hist2d(histogram_combo_detector, norm=LogNorm(), axes=ax1)
 elif detector == 1:
     root2matplotlib.hist2d(histogram_combo_detector, norm=LogNorm(), axes=ax2)
 elif detector == 2:
     root2matplotlib.hist2d(histogram_combo_detector, norm=LogNorm(), axes=ax3)                    
 elif detector == 3:
     root2matplotlib.hist2d(histogram_combo_detector, norm=LogNorm(), axes=ax4) 
     
     # Save the file                    
     figure_combo.savefig(
         'pmt_saturation_s%d.pdf' %station)    # Name of the file
                               
     # Close the figure
     plt.close(figure_combo)
 
 # Now we go to the next detector
#import ROOT
import matplotlib.pyplot as plt
from rootpy.plotting import root2matplotlib
import rootpy.plotting
import numpy as np

a = rootpy.plotting.Hist2D(100, -3, 3, 100, 0, 6)
a.fill_array(np.random.multivariate_normal(
    mean=(0, 3),
    cov=np.arange(4).reshape(2, 2),
    size=(1E6,)))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))

ax1.set_title('hist2d')
root2matplotlib.hist2d(a, axes=ax1)

ax2.set_title('imshow')
im = root2matplotlib.imshow(a, axes=ax2)

ax3.set_title('contour')
root2matplotlib.contour(a, axes=ax3)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

fig.savefig(
    'hist2d.pdf',    # Name of the file
    bbox_inches='tight') 
示例#16
0
def main():
    print('Number of arguments: ', len(sys.argv), 'arguments.')
    print('Argument list:', str(sys.argv))
    filename = sys.argv[1]
    print("Input file: ")
    print(filename)
    MC_FullJets_R04 = dataset("FullR04",
                              NFIN=0,
                              range=(0, 9),
                              filename=filename,
                              directory='AliJJetJtTask/AliJJetJtHistManager',
                              color=2,
                              style=24,
                              rebin=1)

    response, jetPt = MC_FullJets_R04.get2DHist(
        'TrackJtCorrBin',
        dir='AliJJetJtTask/AliJJetJtMCHistManager',
        jetpt=True)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetOptTitle(0)
    linear = ROOT.TF1("linear", "x", 0, 10)
    linear.SetLineColor(1)
    linear.SetLineWidth(2)
    linear.SetLineStyle(2)
    x = linspace(0, 10, 50)
    y = linspace(0, 10, 50)

    #response[1].Draw('colz')
    #linear.Draw('Same')
    ij = 3
    rplt.hist2d(response[ij],
                label=MC_FullJets_R04.name(),
                norm=LogNorm(),
                colorbar=True)
    ax = plt.gca()
    ax.set_xlim([0, 4])
    ax.set_ylim([0, 4])
    ax.set_xlabel(
        r'$j_{T,true}\left[GeV\right]$')  #Add x-axis labels for bottom row
    ax.set_ylabel(
        r'$j_{T,obs}\left[GeV\right]$')  #Add x-axis labels for bottom row

    plt.plot(x, y, '-r')

    ax.text(0.5,
            2.8,
            d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
            '\n Jet Cone \n' + r'$p_{{T,\mathrm{{jet}}}}$:'
            '\n'
            r' {:02d}-{:02d} GeV'.format(jetPt[ij][0], jetPt[ij][1]),
            fontsize=10,
            bbox=dict(boxstyle="round",
                      ec=(1., 0.5, 0.5),
                      fc=(1., 0.8, 0.8),
                      alpha=0.8))

    plt.savefig("PythonFigures/ResponseMatrixNFin00JetPt03.pdf",
                format='pdf')  #Save figure

    d['system'] = r'pPb MC$\sqrt{s_{NN}} = 5.02 \mathrm{TeV}$'

    fig, axs = defs.makegrid(4,
                             2,
                             xlog=False,
                             ylog=False,
                             d=d,
                             shareY=True,
                             xtitle=r'$j_{T,true}\left[GeV\right]$',
                             ytitle=r'$j_{T,obs}\left[GeV\right]$')
    axs = axs.reshape(8)
    axs[1].text(0.5,
                5,
                d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                '\n Jet Cone',
                fontsize=7,
                bbox=dict(boxstyle="round",
                          ec=(1., 0.5, 0.5),
                          fc=(1., 0.8, 0.8),
                          alpha=0.7))
    for r, pT, ax, i in zip(response[1:], jetPt[1:], axs, range(0, 9)):
        rplt.hist2d(r, axes=ax, label=MC_FullJets_R04.name(), norm=LogNorm())
        x1 = linspace(0, 10, 50)
        y1 = linspace(0, 10, 50)
        plt.plot(x1, y1, '-r')

        ax.text(3.5,
                0.5,
                r'$p_{{T,\mathrm{{jet}}}}$:'
                '\n'
                r' {:02d}-{:02d} GeV'.format(pT[0], pT[1]),
                bbox=dict(boxstyle="round",
                          ec=(1., 0.5, 0.5),
                          fc=(1., 0.8, 0.8),
                          alpha=0.7))

        ax.set_xlim([0, 6.5])  #Set x-axis limits
        ax.set_ylim([0, 6.5])  #Set y-axis limits

    axs[0].legend(loc='lower left')

    #plt.savefig("PythonFigures/MixedFullJetsR04JetConeJtSignal.pdf",format='pdf') #Save figure
    plt.savefig("PythonFigures/ResponseMatrixNFin00.pdf",
                format='pdf')  #Save figure

    plt.show()  #Draw figure on screen
def saskia_plot_pmt(data_file_name, station_number):

    # If the plot exist we skip the plotting
    if os.path.isfile('./img/pmt_saturation_s%d.pdf' %station_number):
        # Say if the plot is present
        print "PMT saturation histogram already present for station %d" % station_number
    
    # If there is no plot we make it
    else:
        # Get event data
        event_data = data_file_name.get_node(
            '/s%d' %station,       # From the group (/s..station..)
            'events')           # Get the node with events
    
        # Get the pulseheight from all events
        data_phs = event_data.col('pulseheights')   # col takes all data from events (this improves the speed)
    
        # Get the integral from all events
        data_ints = event_data.col('integrals') # col takes all data from events
    
        # Make a figure so it can be closed
        figure_combo, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex = 'col', sharey = 'row')
    
        # Setting the plot titles
        ax1.set_title('Detector 1')
        ax2.set_title('Detector 2')
        ax3.set_title('Detector 3')
        ax4.set_title('Detector 4')
    
        # Setting the plot labels
        ax1.set_ylabel('Pulseheight [ADC]')
        ax3.set_ylabel('Pulseheight [ADC]')
        ax3.set_xlabel('Pulse integral [ADC.ns]')
        ax4.set_xlabel('Pulse integral [ADC.ns]')
    
        # Now we plot the data of every detector
        for detector in range(0,4):
    
            # Select the detector data
            data_ph_detector = data_phs[:,detector]
            data_int_detector = data_ints[:,detector]
    
            # Combine the detector data
            data_combo = np.stack(
                (data_int_detector,      # The pulse integral on y axis
                 data_ph_detector),    # The pulseheight on x axis
                 axis=-1)               # To get the direction correct
    
            # Initiate a 2D histogram (ROOT style)
            histo_combo_detector = rootpy.plotting.Hist2D(100, 0, 150000, 100, 0, 4500)
    
            # Fill the Histogram
            histo_combo_detector.fill_array(data_combo)
    
            # Plot the histogram with logarithmic colors in correct place
            if detector == 0:
                root2matplotlib.hist2d(histo_combo_detector, norm=LogNorm(), axes=ax1)
            elif detector == 1:
                root2matplotlib.hist2d(histo_combo_detector, norm=LogNorm(), axes=ax2)
            elif detector == 2:
                root2matplotlib.hist2d(histo_combo_detector, norm=LogNorm(), axes=ax3)
            elif detector == 3:
                root2matplotlib.hist2d(histo_combo_detector, norm=LogNorm(), axes=ax4)
    
                # Save the file
                figure_combo.savefig(
                    './img/pmt_saturation_s%d.pdf' %station_number)    # Name of the file
    
                # Close the figure
                plt.close(figure_combo)
    
            # Now we go to the next detector
            detector +1            
print(__doc__)
import ROOT
from matplotlib import pyplot as plt
from rootpy.plotting import root2matplotlib as rplt
from rootpy.plotting import Hist2D
import numpy as np

a = Hist2D(100, -3, 3, 100, 0, 6)
a.fill_array(np.random.multivariate_normal(
    mean=(0, 3),
    cov=[[1, .5], [.5, 1]],
    size=(1E6,)))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))

ax1.set_title('hist2d')
rplt.hist2d(a, axes=ax1)

ax2.set_title('imshow')
im = rplt.imshow(a, axes=ax2)

ax3.set_title('contour')
rplt.contour(a, axes=ax3)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

if not ROOT.gROOT.IsBatch():
    plt.show()
                
            data_combo = np.stack(
                (data_integral_1,      # The pulse integral on y axis
                 data_pulseheight_1),    # The pulseheight on x axis
                 axis=-1)               # To get the direction correct

            a = rootpy.plotting.Hist2D(100, 0, 150000, 100, 0, 5000)
            a.fill_array(data_combo)
            
            canvas = rootpy.plotting.Canvas(width = 800, height = 600)    
            a.Draw("colz")
            wait()
            
            fig = plt.figure(station)
            
            im = root2matplotlib.hist2d(a, norm=LogNorm())
            #cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
            #fig.colorbar(im)
                        
            fig.savefig(
                'hist2d.pdf',    # Name of the file
                bbox_inches='tight')   

            plt.close(fig)
        
print "####### I'm Done Bitches! #######"


################################## FOOTER ################################## 

"""
示例#20
0
def make_correlation_plot_from_file(channel,
                                    variable,
                                    fit_variables,
                                    CoM,
                                    title,
                                    x_title,
                                    y_title,
                                    x_limits,
                                    y_limits,
                                    rebin=1,
                                    save_folder='plots/fitchecks/',
                                    save_as=['pdf', 'png']):
    # global b_tag_bin
    parameters = ["TTJet", "SingleTop", "V+Jets", "QCD"]
    parameters_latex = []
    for template in parameters:
        parameters_latex.append(samples_latex[template])

    input_file = open(
        "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables), "r")
    # cycle through the lines in the file
    for line_number, line in enumerate(input_file):
        # for now, only make plots for the fits for the central measurement
        if "central" in line:
            # matrix we want begins 11 lines below the line with the measurement ("central")
            line_number = line_number + 11
            break
    input_file.close()

    #Note: For some reason, the fit outputs the correlation matrix with the templates in the following order:
    #parameter1: QCD
    #parameter2: SingleTop
    #parameter3: TTJet
    #parameter4: V+Jets

    for variable_bin in variable_bins_ROOT[variable]:
        weights = {}
        if channel == 'electron':
            #formula to calculate the number of lines below "central" to access in each loop
            number_of_lines_down = (
                variable_bins_ROOT[variable].index(variable_bin) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down)
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 1)
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 2)
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 3)
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        if channel == 'muon':
            #formula to calculate the number of lines below "central" to access in each bin loop
            number_of_lines_down = (len(variable_bins_ROOT[variable]) * 12) + (
                variable_bins_ROOT[variable].index(variable_bin) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down)
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 1)
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 2)
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 3)
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        #Create histogram
        histogram_properties = Histogram_properties()
        histogram_properties.title = title
        histogram_properties.name = 'Correlations_' + channel + '_' + variable + '_' + variable_bin
        histogram_properties.y_axis_title = y_title
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_limits = y_limits
        histogram_properties.x_limits = x_limits
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'

        #initialise 2D histogram
        a = Hist2D(4, 0, 4, 4, 0, 4)
        #fill histogram
        for i in range(len(parameters)):
            for j in range(len(parameters)):
                a.fill(
                    float(i), float(j),
                    float(weights["%s_%s" % (parameters[i], parameters[j])]))
        # create figure
        plt.figure(figsize=CMS.figsize, dpi=CMS.dpi, facecolor=CMS.facecolor)
        # make subplot(?)
        fig, ax = plt.subplots(nrows=1, ncols=1)
        rplt.hist2d(a)
        plt.subplots_adjust(right=0.8)

        #Set labels and formats for titles and axes
        plt.ylabel(histogram_properties.y_axis_title)
        plt.xlabel(histogram_properties.x_axis_title)
        plt.title(histogram_properties.title)
        x_limits = histogram_properties.x_limits
        y_limits = histogram_properties.y_limits
        ax.set_xticklabels(parameters_latex)
        ax.set_yticklabels(parameters_latex)
        ax.set_xticks([0.5, 1.5, 2.5, 3.5])
        ax.set_yticks([0.5, 1.5, 2.5, 3.5])
        plt.setp(ax.get_xticklabels(), visible=True)
        plt.setp(ax.get_yticklabels(), visible=True)

        #create and draw colour bar to the right of the main plot
        im = rplt.imshow(a, axes=ax, vmin=-1.0, vmax=1.0)
        #set location and dimensions (left, lower, width, height)
        cbar_ax = fig.add_axes([0.85, 0.10, 0.05, 0.8])
        fig.colorbar(im, cax=cbar_ax)

        for xpoint in range(len(parameters)):
            for ypoint in range(len(parameters)):
                correlation_value = weights["%s_%s" % (parameters[xpoint],
                                                       parameters[ypoint])]
                ax.annotate(correlation_value,
                            xy=(xpoint + 0.5, ypoint + 0.5),
                            ha='center',
                            va='center',
                            bbox=dict(fc='white', ec='none'))
        for save in save_as:
            plt.savefig(save_folder + histogram_properties.name + '.' + save)
        plt.close(fig)
    plt.close('all')
示例#21
0
        #h.SetMaximum(0.5*h.GetMaximum())

# <codecell>

fgaus = r.TF1('fgaus', 'gaus', 0, 0.3)
nr, nc = 2, 3
fig = figure(figsize=goldenaspect(6.5,nr,nc))
gs = gridspec.GridSpec(nr, nc, wspace=0, hspace=0, left=0.1, right=0.95, bottom=0.175)
for irow in range(0,nr):
    for icol in range(0,nc):
        hnum = 3*irow+(icol+1)
        h2 = hs_ec_oVi[hnum-1]
        hx = h2.ProjectionX()
        hx.Fit(fgaus, 'N0', '', 0.01, 0.035)
        ax = subplot(gs[irow, icol])
        rplt.hist2d(h2, axes=ax, norm=LogNorm())
        X = linspace(0, 0.1, 100)
        fscale = fgaus.GetParameter(0)/(0.9*0.3)
        plot(X, [fgaus.Eval(x)/fscale for x in X],
             'k-', linewidth=0.5)
        cutoff = fgaus.GetParameter(1)+5*fgaus.GetParameter(2)
        #plot([0.13,cutoff], [0,cutoff], 'r-')
        #plot([cutoff,cutoff], [cutoff,0.3], 'r-')
        plot([cutoff,cutoff], [0,0.3], 'r-')
#         text(0.9, 0.85, 'sector %d'%hnum, fontsize=12, color='black', transform=ax.transAxes,
#              verticalalignment='top', horizontalalignment='right', bbox=dict(facecolor='gray', pad=5))
        print('%d,%.3f' % (hnum, cutoff))
#         annotate('(%.3f, %.3f) GeV'%(cutoff,cutoff), xy=(cutoff, cutoff),
#                  xytext=(+0.075, +0.2), fontsize=8,
#                  arrowprops=dict(arrowstyle="->",
#                                  connectionstyle="arc3,rad=.2"),