绘制一维直方图在实验数据处理时,经常会使用,对于不同的绘制类型,能够达到不同的效果。h1draw()样例中展现了三种不同的类型,效果如下:
下面介绍具体步骤:
- 引用头文件:
#include "TInterpreter.h" //此类定义了与通用命令行解释器的抽象接口
#include "TCanvas.h" //画布类,画布是直接在显示管理器的控制下映射到窗口的区域。画布可以细分为独立的图形区域:Pad
#include "TSystem.h" //定义与底层操作系统的通用接口的抽象基类
#include "TFile.h" //文件类,ROOT文件是一套格式明确的连续数据记录(TKey实例)
#include "TH2.h" //二维直方图Service类
#include "TNtuple.h" //一个简单的TTree仅限于浮点变量列表,每个变量都进入一个单独的分支
#include "TPaveLabel.h" //文本框标签类,文字在文本框内居中
#include "TPaveText.h" //文本框文字类,使用相对于Pave(%)的坐标将线(和框)放置在Pave中
#include "TFrame.h" //TFrame是用于绘制直方图框架的TWbox
- 打开
hsimple.root
文件:
TString dir = gROOT->GetTutorialDir();
dir.Append("/hsimple.C");
dir.ReplaceAll("/./","/");
if (gBenchmark->GetBench("hsimple") < 0) gInterpreter->LoadMacro(dir.Data());
TFile *example = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
if (!example) return;
example->ls();
其中,hsimple.root
文件结构为:
TFile** hsimple.root Demo ROOT file with histograms
TFile* hsimple.root Demo ROOT file with histograms
KEY: TH1F hpx;1 This is the px distribution
KEY: TH2F hpxpy;1 py vs px
KEY: TProfile hprof;1 Profile of pz versus px
KEY: TNtuple ntuple;1 Demo ntuple
- 建立一维直方图,存储
hsimple.root
文件中的hpx
直方图:
TH1 *hpx = (TH1*)example->Get("hpx");
- 创建画布以及将其分为三个Pad并绘制至画布上:
TCanvas *c1 = new TCanvas("c1","Histogram Drawing Options",200,10,700,900);
TPad *pad1 = new TPad("pad1",
"The pad with the function",0.03,0.62,0.50,0.92);
TPad *pad2 = new TPad("pad2",
"The pad with the histogram",0.51,0.62,0.98,0.92);
TPad *pad3 = new TPad("pad3",
"The pad with the histogram",0.03,0.02,0.97,0.57);
pad1->Draw();
pad2->Draw();
pad3->Draw();
- 制作标题:
TPaveLabel *title = new TPaveLabel(0.1,0.94,0.9,0.98,
"Drawing options for one dimensional histograms");
title->SetTextFont(52);
title->Draw();
- 在第一块pad中使用默认方式绘制一维直方图:
pad1->cd();
pad1->GetFrame()->SetFillColor(18);
hpx->SetFillColor(45);
hpx->DrawCopy();
TPaveLabel *label1 = new TPaveLabel(-3.5,700,-1,800,"Default option");
label1->Draw();
- 在第二块pad中使用
lego1
方式绘制一维直方图:
pad2->cd();
hpx->DrawCopy("lego1");
TPaveLabel *label2 = new TPaveLabel(-0.72,0.74,-0.22,0.88,"option Lego1");
label2->Draw();
TPaveLabel *label2a = new TPaveLabel(-0.93,-1.08,0.25,-0.92,
"Click on lego to rotate");
label2a->Draw();
- 在第三块pad中绘制带有误差一维直方图:
pad3->cd();
pad3->SetGridx();
pad3->SetGridy();
hpx->SetMarkerStyle(21);
hpx->Draw("e1p");
TPaveLabel *label3 = new TPaveLabel(2,600,3.5,650,"option e1p");
label3->Draw();
- 使用PaveText添加注释:
TPaveText *pave = new TPaveText(-3.78,500,-1.2,750);
TText *t1=pave->AddText("You can move");
t1->SetTextColor(4);
t1->SetTextSize(0.05);
pave->AddText("Title and Stats pads");
pave->AddText("X and Y axis");
pave->AddText("You can modify bin contents");
pave->Draw();
c1->Update();
以上就是三种常见的一维直方图画法,其中第一种和第三种在实际应用中使用的比较广泛,在绘制一维直方图时可以作为参考!
代码地址:https://github.com/root-project/root/blob/master/tutorials/hist/h1draw.C