Hi,
the results of RDataFrame go out of scope (“die”) at the end of your function.
This is why you need hist0->DrawCopy() instead of just Draw(): you need to make a copy of that histogram that is registered with ROOT and draw that, because the copy does not die at the end of the function.
Now to your problem: your legend l1 will still need a valid histogram to check what color its line is, even after the function has exited. So you should not pass hist0 (which will die) but its copy:
auto newHistRegisteredWithROOT = hist0->DrawCopy();
...
l1->AddEntry(newHistRegisteredWithROOT, "on", "lp");