# Plot functions over different domains with legend [closed]

I have two functions which I'd like to plot over different domains, and combine them into a single plot, with a legend included. If it weren't for the legend, I'd simply use Show. However, I have issues with Mathematica's new ShowLegend even in the most trivial case, so I'm not sure quite how to go about this. There are a few posts about using ShowLegend within Show but I had trouble making sense of them, and I'm wondering if my simple case, there's an easier way. An example that will suffice is

F[x_] := Sqrt[4 - x^2];
G[x_] := 9 - x^2;
Plot[F[x], {x, 0, 2}]
Plot[G[x], {x, 0, 3}]


with the resulting plot being over the full range {x, 0 ,3}.

• Plot[{f[x], g[x]}, {x, 0, 3}, PlotLegends -> "Expressions"] – Young Aug 16 '16 at 20:21
• Young's solution is perfect here, but even if you didn't use that there's no reason to use ShowLegend: mathematica.stackexchange.com/a/100997/9490 – Jason B. Aug 16 '16 at 20:29

f[x_] := Sqrt[4 - x^2]
g[x_] := 9 - x^2


You can do it Young's way, which works well for your example functions, as JasonB noted in a comment.

Plot[{f[x], g[x]}, {x, 0, 3}, PlotLegends -> {f[x], g[x]}] Or you can fake it with Inset, which will give you more control.

With[
{colors = ColorData,
rowF =
Row[
{Graphics[{Thick, #1, Line[{{0, 0}, {1, 0}}]},
AspectRatio -> 1/6, ImageSize -> 30],
"  ",
#2}] &},
With[
{inset =
Panel[Column[{rowF @@ {colors, f[x]}, rowF @@ {colors, g[x]}}]]},
Show[
Plot[f[x], {x, 0, 2}, PlotStyle -> colors],
Plot[g[x], {x, 0, 3}, PlotStyle -> colors],
Graphics[Inset[inset, Scaled[{1, 1}], {Right, Top}]],
PlotRange -> All]]] Clearly, doing it with Inset is more work, but it gives you complete control over how your legend looks and where it is placed.

• You don't have to use Inset: Legended[ Show[Plot[f[x], {x, 0, 2}, PlotStyle -> colors], Plot[g[x], {x, 0, 3}, PlotStyle -> colors], PlotRange -> All], Placed[LineLegend[97, {f[x], g[x]}, LegendFunction -> Panel], {Right, Top}]] – Brett Champion Aug 17 '16 at 1:46
• @BrettChampion. Looks like good answer. You should post it. I haven't learned all these new-fangled things like Legended. My answer shows the the way I've been doing this sort of thing since long before Legended appeared. – m_goldberg Aug 17 '16 at 1:54

Adding legends to two distinct Plot[]s doesn't prevent Show from combining them appropriately:

F[x_] := Sqrt[4 - x^2]
G[x_] := 9 - x^2

pos = {Right, Top};
Show[Plot[F[x], {x, 0, 2}, PlotLegends -> Placed[{F}, pos], PlotStyle -> Red],
Plot[G[x], {x, 0, 3}, PlotLegends -> Placed[{G}, pos]],
PlotRange -> All]

• Thanks! Can one easily place the legend in the bulk of the figure this way? I notice now that LegendPosition doesn't work, even if the two locations are the same. Maybe this is a command from an old Mathematica – Benighted Aug 16 '16 at 21:10
• @spietro Non-numeric position arguments in Placed keeps the legend within the bulk. See the edit. – Coolwater Aug 17 '16 at 10:11