def test_imshow(): from rootpy.plotting import root2matplotlib as rplt 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=(1000,))) rplt.imshow(a)
def test_imshow(): from rootpy.plotting import root2matplotlib as rplt 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=(1000, ))) rplt.imshow(a)
def test_imshow(): from rootpy.plotting import root2matplotlib as rplt 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=(1000,))) rplt.imshow(a)
def test_imshow(): from rootpy.plotting import root2matplotlib as rplt 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=(1000, ))) rplt.imshow(a)
def make_jet_response_plot(input_file, response): global output_folder, output_formats, suffix jet_response_plot = asrootpy(input_file.Get(response)) x_limits = [0, 200] y_limits = [0.8, 1.2] if '_eta' in response: x_limits = [-3, 3] x_title = '$\eta$(reco jet)' else: x_title = '$p_{\mathrm{T}}$(reco jet) [GeV]' y_title = '$p_{\mathrm{T}}$(reco jet)/$p_{\mathrm{T}}$(HLT jet)' save_as_name = response plt.figure(figsize=(20, 16), dpi=200, facecolor='white') ax0 = plt.axes() ax0.minorticks_on() ax0.grid(True, 'major', linewidth=2) ax0.grid(True, 'minor') plt.tick_params(**CMS.axis_label_major) plt.tick_params(**CMS.axis_label_minor) ax0.xaxis.set_major_formatter(FormatStrFormatter('%d')) ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax0.xaxis.labelpad = 12 ax0.yaxis.labelpad = 12 if '_prof' in response: rplt.errorbar(jet_response_plot, xerr=True, emptybins=True, axes=ax0, marker='o', ms=15, mew=3, lw=2) else: im = rplt.imshow(jet_response_plot, axes=ax0, cmap=cm.Blues) #plt.colorbar(im) ax0.set_xlim(x_limits) ax0.set_ylim(y_limits) plt.tick_params(**CMS.axis_label_major) plt.tick_params(**CMS.axis_label_minor) plt.xlabel(x_title, CMS.x_axis_title) plt.ylabel(y_title, CMS.y_axis_title) plt.title(r'e+jets, CMS Preliminary, $\sqrt{s}$ = 8 TeV', CMS.title) if '_prof' in response: plt.legend(['data'], numpoints=1, loc='lower right', prop=CMS.legend_properties) plt.tight_layout() for output_format in output_formats: plt.savefig(output_folder + save_as_name + '_' + suffix + '.' + output_format)
def make_scatter_plot( input_file, histogram, bin_edges, channel, variable, title ): global output_folder, output_formats, options scatter_plot = get_histogram_from_file( histogram, input_file ) # Finding max value in scatterplot for colourmap normalisation max_bin = scatter_plot.GetMaximumBin() max_bin_content = scatter_plot.GetBinContent(max_bin) norm = mpl.colors.LogNorm(vmin = 1, vmax = int(max_bin_content+1)) # scatter_plot.Rebin2D( 5, 5 ) x_limits = [bin_edges[variable][0], bin_edges[variable][-1]] y_limits = x_limits x_title = 'Reconstructed $' + variables_latex[variable] + '$ [GeV]' y_title = 'Generated $' + variables_latex[variable] + '$ [GeV]' save_as_name = channel + '_' + variable + '_' + str(options.CoM) + 'TeV' plt.figure( figsize = ( 20, 16 ), dpi = 200, facecolor = 'white' ) ax0 = plt.axes() ax0.minorticks_on() # ax0.grid( True, 'major', linewidth = 2 ) # ax0.grid( True, 'minor' ) plt.tick_params( **CMS.axis_label_major ) plt.tick_params( **CMS.axis_label_minor ) ax0.xaxis.labelpad = 12 ax0.yaxis.labelpad = 12 im = rplt.imshow( scatter_plot, axes = ax0, cmap = my_cmap, norm=norm ) colorbar = plt.colorbar( im ) colorbar.ax.tick_params( **CMS.axis_label_major ) # draw lines at bin edges values for edge in bin_edges[variable]: # do not inclue first and last values if ( edge != bin_edges[variable][0] ) and ( edge != bin_edges[variable][-1] ): plt.axvline( x = edge, color = 'red', linewidth = 4, alpha = 0.5 ) plt.axhline( y = edge, color = 'red', linewidth = 4, alpha = 0.5 ) ax0.set_xlim( x_limits ) ax0.set_ylim( y_limits ) plt.tick_params( **CMS.axis_label_major ) plt.tick_params( **CMS.axis_label_minor ) plt.xlabel( x_title, CMS.x_axis_title ) plt.ylabel( y_title, CMS.y_axis_title ) plt.title( title, CMS.title ) plt.tight_layout() for output_format in output_formats: plt.savefig( output_folder + save_as_name + '.' + output_format )
def make_jet_response_plot(input_file, response): global output_folder, output_formats, suffix jet_response_plot = asrootpy(input_file.Get(response)) x_limits = [0, 200] y_limits = [0.8, 1.2] if '_eta' in response: x_limits = [-3, 3] x_title = '$\eta$(reco jet)' else: x_title = '$p_{\mathrm{T}}$(reco jet) [GeV]' y_title = '$p_{\mathrm{T}}$(reco jet)/$p_{\mathrm{T}}$(HLT jet)' save_as_name = response plt.figure(figsize=(20, 16), dpi=200, facecolor='white') ax0 = plt.axes() ax0.minorticks_on() ax0.grid(True, 'major', linewidth=2) ax0.grid(True, 'minor') plt.tick_params(**CMS.axis_label_major) plt.tick_params(**CMS.axis_label_minor) ax0.xaxis.set_major_formatter(FormatStrFormatter('%d')) ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax0.xaxis.labelpad = 12 ax0.yaxis.labelpad = 12 if '_prof' in response: rplt.errorbar(jet_response_plot, xerr=True, emptybins=True, axes=ax0) else: im = rplt.imshow(jet_response_plot, axes=ax0, cmap = cm.Blues) #plt.colorbar(im) ax0.set_xlim(x_limits) ax0.set_ylim(y_limits) plt.tick_params(**CMS.axis_label_major) plt.tick_params(**CMS.axis_label_minor) plt.xlabel(x_title, CMS.x_axis_title) plt.ylabel(y_title, CMS.y_axis_title) plt.title(r'e+jets, CMS Preliminary, $\sqrt{s}$ = 8 TeV', CMS.title) if '_prof' in response: plt.legend(['data'], numpoints=1, loc='lower right', prop=CMS.legend_properties) plt.tight_layout() for output_format in output_formats: plt.savefig(output_folder + save_as_name + '_' + suffix + '.' + output_format)
def draw_interp_subplot(ax, limit, x_spec, y_spec, z_spec, triang = None, xi = None, yi = None, zi = None, cont = None, title = "", show_grids = False, masked_region = None): if isinstance(limit,r.TH2): img = rplt.imshow(limit, ax, norm=mpl.colors.LogNorm(), vmin = z_spec.ax_min , vmax = z_spec.ax_max) elif isinstance(limit,np.ma.core.MaskedArray): dx = (xi[2][2]-xi[1][1]) xi_n = xi - dx/2. dy = (yi[2][2]-yi[1][1]) yi_n = yi - dy/2. img = ax.pcolor(xi_n,yi_n,limit, vmin = z_spec.ax_min, vmax = z_spec.ax_max, norm=mpl.colors.LogNorm()) else: log.error("Argument 'limit' has wrong type: %s"%type(limit)) sys.exit() ax.set_xlim(x_spec.limits) ax.set_xlabel(x_spec.label, fontsize = 45) ax.set_ylim(y_spec.limits) ax.set_ylabel(y_spec.label, fontsize = 45) ax.set_title(title) if not xi==None and not yi==None and not zi==None and cont == None: c = ax.contour(xi, yi, zi, colors='black') ax.clabel(c, inline=1, fontsize=15) if not xi==None and not yi==None and not zi==None: if masked_region == None: c = ax.contour(xi, yi, zi, levels = cont, colors='black', extrapolate = True, interp = True) else: zi[masked_region] = np.ma.masked c = ax.contour(xi, yi, zi, levels = cont, colors='black', extrapolate = True, interp = True) c.levels = [format_clabel(val) for val in c.levels ] fmt = r'%r' ax.clabel(c, fontsize=18, fmt = fmt) if show_grids: if triang: ax.triplot(triang, 'ko-') if (not xi == None): ax.plot(xi_n, yi_n, 'k-', alpha=0.5) if (not yi == None): ax.plot(xi_n.T, yi_n.T, 'k-', alpha=0.5) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(img, cax=cax) cbar.set_label(z_spec.label,fontsize=45)
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')
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')
def mega_plot(hist_2D, ax=None, range_2d=None, yrange_px=None, xrange_py=None, details=None, fit=False, exclude_peak=True, plot_fit=False, dphi_extra=None): # start with a rectangular Figure if ax: fig = plt.gcf() else: fig = plt.figure(1, figsize=(8, 10)) #ax = plt.axes() ax = plt.axes([0.18, 0.18, .64, .64], axisbg='w') #ax_debug = plt.axes([0,0,1,1], axisbg='r') ax.axis('off') frame = 0.0 fibo = 1.681 heat_x = heat_y = 1.0 / fibo cbar_dist = 0.01 extra_left_legend = 0.08 # may over extend to right but not left... xpro_x, xpro_y = heat_x, 1.0 - 1.0 / fibo cbar_x, cbar_y = 0.04, heat_y ypro_x, ypro_y = xpro_y - cbar_x - cbar_dist, heat_y rect_2d = [frame, frame, heat_x, heat_y] rect_histx = [frame, frame + heat_y, xpro_x, xpro_y] rect_histy = [frame + heat_x, frame, ypro_x, ypro_y] rect_cbar = [frame + heat_x + ypro_x + cbar_dist, frame, cbar_x, cbar_y] rect_legend = [frame + heat_x + extra_left_legend, frame + heat_y, ypro_x + cbar_dist + cbar_x, xpro_y] # collect plotted lines for legend lns = list() ax_2d = _add_subplot_axes(ax, rect_2d) ax_2d.set_xlabel(r'$\Delta\varphi$') ax_2d.set_ylabel(r'$\Delta\eta$') if isinstance(range_2d, (list, tuple)): im = rplt.imshow(hist_2D, vmin=range_2d[0], vmax=range_2d[1]) else: im = rplt.imshow(hist_2D) # x projection: axHistx = _add_subplot_axes(ax, rect_histx) if exclude_peak: lable = '$\Delta \phi$ projection\nexcl. peak' else: lable = '$\Delta \phi$ projection' _plot_x_projection(hist_2D, yrange_px=yrange_px, lns=lns, lable=lable, ax=axHistx, exclude_peak=exclude_peak, plot_fit=plot_fit, dphi_extra=dphi_extra) # y axis projection sub_py = project_onto_deta_with_sections(hist_2D) axHisty = _add_subplot_axes(ax, rect_histy) axHisty.set_ylim(bottom=ax_2d.get_ylim()[0], top=ax_2d.get_ylim()[1]) # cannot use rplt since x and y are swapped mini, maxi = 99, -99 for hist in sub_py: mini = hist.GetMinimum() if hist.GetMinimum() < mini else mini maxi = hist.GetMaximum() if hist.GetMaximum() > maxi else maxi lns.append(plt.errorbar(x=list(hist.y()), y=list(hist.x()), xerr=np.array([list(hist.yerrh()), list(hist.yerrl())]), label=hist.GetTitle())) if isinstance(xrange_py, (list, tuple)): axHisty.set_xlim(xrange_py) else: dist = (maxi - mini)*0.1 axHisty.set_xlim([mini-dist, maxi+dist]) axHisty.set_xlabel(r'$\frac{1}{N_{tr}}\frac{dN_{as}}{d\Delta \eta}$ [rad$^{-1}$]', labelpad=0) # fix labels and ticks nullfmt = NullFormatter() # no labels axHistx.xaxis.set_major_formatter(nullfmt) axHistx.yaxis.set_major_locator(MaxNLocator(prune='lower', nbins=4)) axHistx.xaxis.set_minor_locator(AutoMinorLocator()) axHistx.yaxis.set_minor_locator(AutoMinorLocator()) axHisty.yaxis.set_major_formatter(nullfmt) axHisty.xaxis.set_minor_locator(AutoMinorLocator()) axHisty.yaxis.set_minor_locator(AutoMinorLocator()) axHisty.xaxis.set_major_locator(MaxNLocator(prune='lower', nbins=4)) # get lables for the py projection and rotate them axHisty.set_xticklabels(axHisty.get_xticks(), rotation=35, ha='right') #plt.setp(axHisty.get_xmajorticklabels(), rotation=35) # colorbar axes cbar_ax = _add_subplot_axes(ax, rect_cbar) cb = fig.colorbar(im, cax=cbar_ax, ) cb.set_label(r'$\frac{1}{N_{tr}}\frac{dN^{2}_{as}}{d\Delta \eta d\Delta \varphi}$[rad$^{-1}$]',) # labelpad=0 rotation=270) # make the legend axes: ax_leg = _add_subplot_axes(ax, rect_legend) labels = [l.get_label() for l in lns] #ax_leg.xaxis.set_major_formatter(nullfmt) #ax_leg.yaxis.set_major_formatter(nullfmt) if details: ax_leg.text(0.05, 0.75, details) ax_leg.legend(lns, labels, numpoints=1, loc=10)#loc=(.03, -0.03)) ax_leg.axis('off') # write title at center of plot #ax.text(0.5, 1.1, hist_2D.title, fontsize=12, transform=axHistx.transAxes, # horizontalalignment='center', verticalalignment='center') ax.set_title(hist_2D.title) return fig
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') #if not ROOT.gROOT.IsBatch(): # plt.show()
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()
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()
plt.clf() plt.close('all') if (MCSample,norm, label, firstInCombinedSample) in samplestooverlay: alpha = 0.7 linestyle = 'solid' levels = [ round_to_1( MCScales[MCSample]*NEvent[MCSample]* tmpfactor ) for tmpfactor in [ 0.0001,0.001,0.01,0.1] ] if colornorm==0: colornorm = matplotlib.colors.Normalize(vmin = 0 , vmax = 100, clip = False) # plt.grid() # # ims[MCSample] = rplt.imshow(a,axes=OverlayAxes, norm = colornorm, cmap = sns.blend_palette(["ghostwhite", colorpal[iSample]], as_cmap=True) , alpha=0.25 ) ims[MCSample] = rplt.imshow (corrhist,axes=OverlayAxes, norm = colornorm, cmap = sns.blend_palette(["ghostwhite", colorpal[iSample]], as_cmap=True) , alpha=0.25 ) ctr[MCSample] = rplt.contour(corrhist,axes=OverlayAxes, linewidth=10, alpha=alpha, linestyles=linestyle , colors = matplotlib.colors.rgb2hex(colorpal[iSample]) ) #, locator=ticker.FixedLocator(levels) ) plt.clabel(ctr[MCSample], inline=0, inline_spacing=-1, fontsize=10,fmt='%1.0f') OverlayAxes.annotate(r"\textbf{\textit{ATLAS}} Internal", xy=(0.65, 0.05), xycoords='axes fraction', fontweight='bold', fontsize=10) pass OverlayAxes.set_xlim(var1limits[:2]) OverlayAxes.set_ylim(var2limits[:2]) tmpRectangle = {} for iSample, (MCSample,norm, label, tmp) in enumerate(samplestodraw) : tmpRectangle[MCSample] = Rectangle((0, 0), 1, 1, fc=matplotlib.colors.rgb2hex(colorpal[iSample]) ) OverlayAxes.legend([tmpRectangle[x] for (x,y,z,x1) in samplestooverlay ], [z for (x,y,z,x1) in samplestooverlay], loc="best" , borderaxespad=3) OverlayAxes.set_xlabel(var1label)