Thank you very much for the solution! It works smoothly!
In my final application, the TGraphErrors are created and added to the TMultiGraph in a different scope, hence the snippet needs a tweak. I leave here the working macro:
// --- SELECT THE PALETTE
gStyle -> SetPalette (100);
// --- PREPARE SOME DATA
std::vector <double> x = {0., 1., 2., 3., 4., 5.};
std::vector <double> y1 = {0., 1., 2., 3., 4., 5.};
std::vector <double> y2 = {0., 2., 4., 6., 8., 10.};
std::vector <double> err_x = {0., 0., 0., 0., 0., 0.};
std::vector <double> err_y = {0.1, 0.1, 0.1, 0.1, 0.1, 0.1};
// --- CREATE TCanvas AND TMultigraph
TCanvas c ("c", "c", 1000, 800);
TMultiGraph mg;
// --- DIFFERENT SCOPE --- //
{
// --- CREATE THE TGraphs
TGraphErrors *g1 = new TGraphErrors (x.size(), &x[0], &y1[0], &err_x[0], &err_y[0]);
TGraphErrors *g2 = new TGraphErrors (x.size(), &x[0], &y2[0], &err_x[0], &err_y[0]);
g1->SetMarkerStyle(20);
g2->SetMarkerStyle(20);
g1->SetTitle("Graph #1");
g2->SetTitle("Graph #2");
g1->SetName("g_1");
g2->SetName("g_2");
// --- FIT
g1->Fit("pol1");
g2->Fit("pol1");
// --- ADD
mg.Add(g1);
mg.Add(g2);
}
// --- --------------- --- //
mg.Draw("AP PMC PLC PFC");
// --- MODIFIED SOLUTION --- //
gPad -> Update();
auto g1 = (TGraphErrors*) mg.GetListOfGraphs()->FindObject("g_1");
auto c1 = g1->GetLineColor();
auto f1 = (TF1*) g1 -> GetListOfFunctions()->FindObject("pol1");
f1 -> SetLineColor(c1);
auto g2 = (TGraphErrors*) mg.GetListOfGraphs()->FindObject("g_2");
auto c2 = g2->GetLineColor();
auto f2 = (TF1*) g2 -> GetListOfFunctions()->FindObject("pol1");
f2 -> SetLineColor(c2);
// --- DRAW THE CANVAS ---
c.SetGrid();
c.BuildLegend(0.15, 0.6, 0.4, 0.8);
c.DrawClone();
As a final note, I would suggest evaluating the possibility of implementing in a future ROOT release some option similar to PLC
for the functions of a TGraphs. Personally, I never really use the L
option when drawing TMultiGraphs, whereas I more often happen to plot TGraphs and fit functions of some quantity for different parameters (the line slope, in this example).
Thank you very much, once more!
Loris