Skip to content

Instantly share code, notes, and snippets.

@riga
Last active May 20, 2021 10:30
Show Gist options
  • Save riga/f0ae4fd4a8f7bc8fbda19812e697cfc5 to your computer and use it in GitHub Desktop.
Save riga/f0ae4fd4a8f7bc8fbda19812e697cfc5 to your computer and use it in GitHub Desktop.
Edge aligned bin labels in ROOT
# coding: utf-8
# import root into a cage
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch()
# preps
canvas = ROOT.TCanvas()
canvas.Divide(1)
pad = [p for p in canvas.GetListOfPrimitives()if isinstance(p, ROOT.TPad)][0]
h = ROOT.TH1F("h", "", 10, 0., 1.)
axis = h.GetXaxis()
# disable default axis labels
axis.SetBinLabel(1, "")
# get margins and ranges
l = pad.GetLeftMargin()
r = pad.GetRightMargin()
b = pad.GetBottomMargin()
x_min = axis.GetXmin()
x_max = axis.GetXmax()
# some dummy edge values
edge_values = "abcdefghijklmnopqrstuvwxyz"[:axis.GetNbins() + 1]
# create edge labels
labels = []
for i, val in enumerate(edge_values):
x = l + (1 - r - l) * i / axis.GetNbins()
y = b - 0.01
label = ROOT.TLatex(x, y, val)
label.SetNDC(True)
label.SetTextFont(43)
label.SetTextSize(12)
label.SetTextAlign(32)
label.SetTextAngle(90)
labels.append(label)
# draw and save
pad.cd()
h.Draw("HIST")
for label in labels:
label.Draw()
canvas.SaveAs("bin_labels.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment