How to set ranges on axis?

The viewing range for an histogram axis can be set from bin ifirst to ilast using the method TAxis::SetRange(ifirst, ilast). Example (hpxpy is a 2D histogram):

``````{
TFile f("hsimple.root");
hpxpy->Draw("colz");
hpxpy->GetYaxis()->SetRange(22,23);
hpxpy->GetXaxis()->SetRange(18,19);
}
``````

Sometimes it is more convenient to set this range using “User’s Coordinates” (axis values) rather than bin numbers. To do that one should use TAxis::SetRangeUser(ufirst, ulast). This method computes the closest bin to ufirst and ulast and call TAxis::SetRange(ifirst, ilast) with this values.

The method SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis) allows to set the axis ranges directly on an histogram object without having to do the intermediate Get[XYZ]axis(). For instance:

``````   hpxpy->GetYaxis()->SetRangeUser(0., 3.);
``````

is equivalent to:

``````   hpxpy->SetAxisRange(0., 3.,"Y");
``````

SetAxisRange also performs automatically the call to SetMinimum() and SetMaximum() when the axis the the one holding the histogram content (Y axis, for 1D histograms, Z axis for 2D histograms)

For unbinned data set like graphs and multigraphs, the way to changed the axis range is to use SetLimits(vmin, vmax). This method changes the minimum and maximum values of the axis. Example:

``````{
Int_t n=20;
Double_t x[n],y[n];
for (Int_t i=0; i < n; i++) {
x[i]=i*0.1;
y[i]=10*sin(x[i]+0.2);
}
auto gr1  = new TGraph (n,x,y);
auto axis = gr1->GetXaxis();

axis->SetLimits(0.,5.);                 // along X
gr1->GetHistogram()->SetMaximum(20.);   // along
gr1->GetHistogram()->SetMinimum(-20.);  //   Y

gr1->Draw("AC*");
}
``````

An other method is to change the axis ranges after the graph drawing:

``````{
auto c = new TCanvas("c","A Zoomed Graph",200,10,700,500);

int n = 10;
double x[10] = {-.22,.05,.25,.35,.5,.61,.7,.85,.89,.95};
double y[10] = {1,2.9,5.6,7.4,9,9.6,8.7,6.3,4.5,1};

auto gr = new TGraph(n,x,y);
gr->SetMarkerColor(4);
gr->SetMarkerStyle(20);
gr->Draw("ALP");
gr->GetXaxis()->SetRangeUser(0, 0.5);
gr->GetYaxis()->SetRangeUser(1, 8);
}
``````

It is also possible to first draw a frame with the wanted limits and then draw the graph in it. This method allows to specify wider axis ranges than the original one.

``````{
auto c = new TCanvas("c","A Zoomed Graph",200,10,700,500);
c->DrawFrame(0,1,0.5,8);

int n = 10;
double x[10] = {-.22,.05,.25,.35,.5,.61,.7,.85,.89,.95};
double y[10] = {1,2.9,5.6,7.4,9,9.6,8.7,6.3,4.5,1};

auto gr = new TGraph(n,x,y);
gr->SetMarkerColor(4);
gr->SetMarkerStyle(20);
gr->Draw("LP");
}
``````
5 Likes