Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
hist003_TH1_draw_uhi.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_hist
3## \notebook
4## Draw a 1D histogram to a canvas.
5##
6## \note When using graphics inside a ROOT macro the objects must be created with `new`.
7##
8## \macro_image
9## \macro_code
10##
11## \date July 2025
12## \author Rene Brun, Giacomo Parolini, Nursena Bitirgen
13
14import matplotlib.pyplot as plt
15import mplhep as hep
16import numpy as np
17import ROOT
18
19# Create and fill the histogram.
20# See hist002_TH1_fillrandom_userfunc.C for more information about this section.
21form1 = ROOT.TFormula("form1", "abs(sin(x)/x)")
22rangeMin = 0.0
23rangeMax = 10.0
24sqroot = ROOT.TF1("sqroot", "x*gaus(0) + [3]*form1", rangeMin, rangeMax)
25sqroot.SetParameters(10.0, 4.0, 1.0, 20.0)
26
27nBins = 200
28h1d = ROOT.TH1D("h1d", "Test random numbers", nBins, rangeMin, rangeMax)
29
30random_numbers = np.array([sqroot.GetRandom() for _ in range(10000)])
31h1d[...] = np.histogram(np.array([sqroot.GetRandom() for _ in range(10000)]), bins=nBins, range=(rangeMin, rangeMax))[0]
32
33# Create a canvas and draw the histogram
34plt.figure(figsize=(7, 9))
35
36# Split the canvas into two sections to plot both the function and the histogram
37plt.axes([0.05, 0.55, 0.90, 0.40])
38x = np.linspace(rangeMin, rangeMax, 500)
39plt.plot(x, [sqroot.Eval(xi) for xi in x], "b-", lw=5)
41plt.title("x*gaus(0) + [3]*form1")
42plt.text(5, 40, "The sqroot function", fontsize=18, weight="bold", bbox=dict(facecolor="white", edgecolor="black"))
43plt.xlim(rangeMin, rangeMax)
44plt.ylim(bottom=0)
45
46plt.axes([0.05, 0.05, 0.90, 0.40])
47hep.histplot(h1d, yerr=False, histtype="fill", color="brown", alpha=0.7, edgecolor="blue", linewidth=1)
48
49plt.title("Test random numbers")
50plt.xlabel("x")
51plt.ylabel("Entries")
52plt.xlim(rangeMin, rangeMax)
53plt.ylim(bottom=0)
54
55stats_text = (
56 f"Entries = {len(random_numbers)}\nMean = {(np.mean(random_numbers)):.3f}\nStd Dev = {(np.std(random_numbers)):.2f}"
57)
58plt.text(0.90, 0.90, stats_text, transform=plt.gca().transAxes, ha="right", va="top", bbox=dict(facecolor="white"))
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.