ROOT官方教程中h2proj示例演示了如何显示直方图及其两个投影。 当对2D直方图执行缩放时,TExec允许自动重绘投影。
下面讲述具体步骤:
- 创建二维直方图对象以及两个投影一维直方图对象和绘制的Pad:
TH2F *h2;
TH1D * projh2X;
TH1D * projh2Y;
TPad *right_pad, *top_pad;
- 创建一个画布并设置其参数:
auto c1 = new TCanvas("c1", "c1",900,900); //创建900px*900px的画布
gStyle->SetOptStat(0); //不显示统计参数
TPad *center_pad = new TPad("center_pad", "center_pad",0.0,0.0,0.6,0.6);//创建主pad,用于绘制二维直方图
center_pad->Draw();
right_pad = new TPad("right_pad", "right_pad",0.55,0.0,1.0,0.6); //设置right_pad在画布中的位置
right_pad->Draw();
top_pad = new TPad("top_pad", "top_pad",0.0,0.55,0.6,1.0); //设置top_pad在画布中的位置
top_pad->Draw();
- 向二维直方图中填充随机数:
h2 = new TH2F("h2","",40,-4,4,40,-20,20); //x轴设置40个bin,范围为(-4,4);y轴设置40个bin,范围为(-20,20)
Float_t px, py;
for (Int_t i = 0; i < 25000; i++) {
gRandom->Rannor(px,py); //返回均值为0和sigma = 1的高斯分布后的2个数字
h2->Fill(px,5*py);
}
- 将X、Y轴投影到一维直方图:
projh2X = h2->ProjectionX(); //将X直方图投影到沿X的一维直方图中
projh2Y = h2->ProjectionY(); //将Y直方图投影到沿Y的一维直方图中
- 将直方图绘制:
center_pad->cd();
gStyle->SetPalette(1);
h2->Draw("COL");
top_pad->cd();
projh2X->SetFillColor(kBlue+1);
projh2X->Draw("bar");
right_pad->cd();
projh2Y->SetFillColor(kBlue-2);
projh2Y->Draw("hbar"); //侧画
- 添加两行注释:
c1->cd();
TLatex *t = new TLatex();
t->SetTextFont(42);
t->SetTextSize(0.02);
t->DrawLatex(0.6,0.88,"This example demonstrates how to display");
t->DrawLatex(0.6,0.85,"a histogram and its two projections.");
- 设置TExec,使其允许自动重绘投影:
auto ex = new TExec("zoom","ZoomExec()");
h2->GetListOfFunctions()->Add(ex);
其中ZommExec()
函数为:
void ZoomExec()
{
int xfirst = h2->GetXaxis()->GetFirst();
int xlast = h2->GetXaxis()->GetLast();
double xmin = h2->GetXaxis()->GetBinLowEdge(xfirst);
double xmax = h2->GetXaxis()->GetBinUpEdge(xlast);
projh2X->GetXaxis()->SetRangeUser(xmin, xmax);
top_pad->Modified();
int yfirst = h2->GetYaxis()->GetFirst();
int ylast = h2->GetYaxis()->GetLast();
double ymin = h2->GetYaxis()->GetBinLowEdge(yfirst);
double ymax = h2->GetYaxis()->GetBinUpEdge(ylast);
projh2Y->GetXaxis()->SetRangeUser(ymin, ymax);
right_pad->Modified();
}
至此,当缩放二维直方图坐标时,截取的X、Y轴一维直方图也跟随变化:
代码地址:https://github.com/root-project/root/blob/master/tutorials/hist/h2proj.C