visualize_data.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.ticker import AutoMinorLocator
  4. from matplotlib import ticker
  5. import matplotlib.lines as mlines
  6. from matplotlib.ticker import NullFormatter, LogLocator
  7. # User defined:
  8. #################################################################################
  9. labels = ["Background", "Signal", "Data"]
  10. path_to_original_histograms = 'DATA/original_histograms/'
  11. output_filename = "all_hmumu_ratio.pdf"
  12. logy = True # logscale
  13. ymax = 5 * 10**7 # graph ymax value
  14. yloc = 0.95 # legend y location
  15. color_background = 'green'
  16. color_signal = 'red'
  17. color_data_bkg = 'blue'
  18. color_data = 'black'
  19. #################################################################################
  20. # Load data to dictionary pldict:
  21. pldict = {}
  22. for label in labels:
  23. with np.load(path_to_original_histograms + 'mass_mm_all_' + label + '.npz', 'rb') as data:
  24. bin_edges = data['bin_edges']
  25. bin_centers = data['bin_centers']
  26. bin_values = data['bin_values']
  27. bin_errors = data['bin_errors']
  28. pldict[label] = [bin_centers, bin_edges, bin_values, bin_errors]
  29. # Magic:
  30. f, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(6, 6), gridspec_kw={'height_ratios': [3, 1]})
  31. xs = pldict["Data"][0]
  32. xedges = pldict["Data"][1]
  33. xwidths = (xedges[1:] - xedges[:-1])
  34. xerrs = 0.4 * xwidths
  35. ys = pldict["Data"][2]
  36. yerrs = pldict["Data"][3]
  37. bkgs = pldict["Background"][2]
  38. berrs = pldict["Background"][3]
  39. sigs = pldict["Signal"][2]
  40. serrs = pldict["Signal"][3]
  41. dataPlot = ax1.errorbar(xs, ys, xerr=xerrs, yerr=yerrs, fmt='.', color=color_data, markersize=2)
  42. bkgHist = ax1.hist(xs, xedges, weights=bkgs, histtype='step', color=color_background)
  43. sigHist = ax1.hist(xs, xedges, weights=sigs, histtype='step', color=color_signal)
  44. sigInterp = ax1.fill_between(xs, sigs - serrs, sigs + serrs, color=color_signal, alpha=0.2)
  45. # Fine control over labels - histograms as lines, data with marker only...
  46. siglab = mlines.Line2D([], [], color=color_signal, markersize=10, label='Signal')
  47. bkglab = mlines.Line2D([], [], color=color_background, markersize=10, label='Background')
  48. dlab = mlines.Line2D([], [], color=color_data, marker=".", lw=0, markersize=10, label='Data')
  49. ax1.legend(handles=[siglab, bkglab, dlab], loc='upper right', frameon=0, bbox_to_anchor=(0.95, yloc))
  50. ax1.set_ylabel("Events/bin")
  51. ax1.set_xlabel(r"$m_{\mu\mu}$ [GeV]")
  52. ax1.set_xlim([xedges[0], xedges[-1]])
  53. ax1.set_ylim([0.01, ymax])
  54. # Prettyfy #1
  55. formatter = ticker.ScalarFormatter(useMathText=True)
  56. formatter.set_scientific(True)
  57. formatter.set_powerlimits((-1, 1))
  58. ax1.yaxis.set_major_formatter(formatter)
  59. ax1.tick_params(labeltop=False, labelright=False)
  60. plt.xlabel(ax1.get_xlabel(), horizontalalignment='right', x=1.0)
  61. plt.ylabel(ax1.get_ylabel(), horizontalalignment='right', y=1.0)
  62. ax1.xaxis.set_minor_locator(AutoMinorLocator())
  63. ax1.yaxis.set_minor_locator(AutoMinorLocator())
  64. ax1.tick_params(axis='y', direction="in", left=1, right=1, which='both')
  65. ax1.tick_params(axis='x', direction="in", bottom=1, top=1, which='both')
  66. ax1.tick_params(axis='both', which='major', length=12)
  67. ax1.tick_params(axis='both', which='minor', length=6)
  68. if logy:
  69. ax1.set_yscale("log")
  70. locmin = LogLocator(base=10.0, subs=(0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 9, 10))
  71. locmin = LogLocator(base=10.0, subs=(2, 4, 6, 8, 10))
  72. ax1.yaxis.set_minor_locator(locmin)
  73. ax1.yaxis.set_minor_formatter(NullFormatter())
  74. finelab = ax1.yaxis.get_ticklabels()
  75. finelab[1].set_visible(False)
  76. zvals = ys / bkgs
  77. ry = yerrs / ys
  78. rb = berrs / bkgs
  79. zerrs = zvals * np.sqrt(ry * ry + rb * rb)
  80. ax2.errorbar(xs, zvals, xerr=xerrs, yerr=zerrs, fmt='none', color=color_data_bkg, markersize=10)
  81. ax2.set_ylabel('Data/Bkg')
  82. # Fine y-label control for overlap
  83. finelab = ax2.yaxis.get_ticklabels()
  84. finelab[0].set_visible(False)
  85. if not logy:
  86. finelab[-1].set_visible(False)
  87. ax2.set_xlabel(r"$m_{\mu\mu}$ [GeV]")
  88. ax2.set_xlim([xedges[0], xedges[-1]])
  89. ax2.set_ylim([0.8, 1.2])
  90. ax2.axhline(1, color='k', lw=1)
  91. # Prettyfy #2
  92. ax2.tick_params(labeltop=False, labelright=False)
  93. plt.xlabel(ax2.get_xlabel(), horizontalalignment='right', x=1.0)
  94. plt.ylabel(ax2.get_ylabel(), horizontalalignment='center', y=0.5)
  95. ax2.xaxis.set_minor_locator(AutoMinorLocator())
  96. ax2.yaxis.set_minor_locator(AutoMinorLocator())
  97. ax2.tick_params(axis='y', direction="in", left=1, right=1, which='both')
  98. ax2.tick_params(axis='x', direction="in", bottom=1, top=1, which='both')
  99. ax2.tick_params(axis='both', which='major', length=12)
  100. ax2.tick_params(axis='both', which='minor', length=6)
  101. f.subplots_adjust(hspace=0)
  102. plt.savefig(output_filename, format="pdf")
  103. plt.show()
  104. plt.close()