Last active
January 22, 2018 18:08
-
-
Save acidbourbon/5262138dfc61c29567ff0a241ce7a7f9 to your computer and use it in GitHub Desktop.
Invert TGraphErrors/TGraph ROOT Graph, swap axes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function takes a ROOT TGraphErrors Object and swaps the x and y coordinates | |
// of the data points. This is especially useful if you want to use the TGraph/TGraphErrors built-in interpolation | |
// functionality. Say you have measured a calibration function to get from x values to y values. But now | |
// you measure new y values and want to determine the corresponding x values ... | |
TGraphErrors* invert_tge(TGraphErrors* orig){ | |
TGraphErrors* tge = (TGraphErrors*) orig->Clone(); | |
Double_t x,y,xe,ye; | |
TString xtitle, ytitle; | |
xtitle = tge->GetXaxis()->GetTitle(); | |
ytitle = tge->GetYaxis()->GetTitle(); | |
tge->GetXaxis()->SetTitle(ytitle); | |
tge->GetYaxis()->SetTitle(xtitle); | |
for (Int_t i = 0; i< tge->GetN(); ++i){ | |
tge->GetPoint(i,x,y); | |
xe = tge->GetErrorX(i); | |
ye = tge->GetErrorY(i); | |
tge->SetPoint(i,y,x); | |
tge->SetPointError(i,ye,xe); | |
} | |
return tge; | |
} | |
// the same functionality but for a TGraph Object | |
TGraph* invert_tg(TGraph* orig){ | |
TGraph* tg = (TGraph*) orig->Clone(); | |
Double_t x,y; | |
TString xtitle, ytitle; | |
xtitle = tg->GetXaxis()->GetTitle(); | |
ytitle = tg->GetYaxis()->GetTitle(); | |
tg->GetXaxis()->SetTitle(ytitle); | |
tg->GetYaxis()->SetTitle(xtitle); | |
for (Int_t i = 0; i< tg->GetN(); ++i){ | |
tg->GetPoint(i,x,y); | |
tg->SetPoint(i,y,x); | |
} | |
return tg; | |
} | |
void invert_TGraphErrors_example(void){ | |
const Int_t n = 10; | |
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.7)-6; | |
} | |
TGraph* gr = new TGraph(n,x,y); | |
gr->GetXaxis()->SetTitle("Voltage (V)"); | |
gr->GetYaxis()->SetTitle("Current (A)"); | |
gr->SetTitle("A graph"); | |
TGraph* gr_inv = invert_tg(gr); | |
gr_inv->SetTitle("An inverted graph"); | |
TCanvas* c = new TCanvas(); | |
c->Divide(2,1); | |
c->cd(1); | |
gr->Draw(); | |
(new TLine(0,3.0,1,3.0))->Draw("same"); | |
c->cd(2); | |
gr_inv->Draw(); | |
(new TLine(3.0,0,3.0,1))->Draw("same"); | |
cout << "I measured three amps, what voltage did I apply?" << endl; | |
cout << "Answer: " << gr_inv->Eval(3.0) << "volts" << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment