# How to combine several legends in one frame?

I'm using Show to combine three plots. The code I write is as follows:

g1 = Plot[x^2 + 3, {x, 0, 3},
PlotLegends ->
LegendLayout -> "Row",
LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], Below],
AxesOrigin -> {0, 0}, PlotStyle -> Red];
g2 = Plot[x^3 + x, {x, 1, 4},
PlotLegends ->
LegendLayout -> "Row",
LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], Below],
AxesOrigin -> {0, 0}, PlotStyle -> Blue];
g3 = Plot[20/x, {x, 1/2, 4},
PlotLegends ->
LegendLayout -> "Row",
LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], Below],
AxesOrigin -> {0, 0}, PlotStyle -> Black];
Show[{g1, g2, g3}, PlotRange -> {{0, 4}, {0, All}}]


The output is the following:

As we can see in the output, the three legends are seperate in three frames. How can I place the three legends in a row in one frame?

show = Show[{g1, g2, g3}, PlotRange -> {{0, 4}, {0, All}}];


Extract the main plot and legends from show and reorganize them in desired form:

plot = Cases[show, _Graphics, All][[1]];

legendargs = Transpose @
Cases[show, LineLegend[arg1_, arg2_, opts___] :> {arg1, arg2, opts}, All];

newlegend = Placed[LineLegend @@ legendargs,
## & @@ First @ Cases[show, Placed[_, a___] :> {a}, All]];

Legended[plot, newlegend]


• It indicates an error when I run the code newlegend = Placed[LineLegend @@ legendargs, ## & @@ First @ Cases[show, Placed[_, a___] :> {a}, All]]. Did you miss something in this code? Apr 30, 2023 at 12:51
• @YaHe, what is the error message?
– kglr
Apr 30, 2023 at 12:54
• It indicates that "First::nofirst, the length of {} is zero, there is no first element" Apr 30, 2023 at 13:02
• It could be version/os difference (I am using V13.1.0 on Linux). Try newlegend=Placed[LineLegend @@ legendargs, Below].
– kglr
Apr 30, 2023 at 13:12
• Many thanks. It works now (I'm also using V13.1). Besides, by reducing the FrameMargins in the plot g1, g2, g3, I can reduce the margin of the legends frame in the final output. Apr 30, 2023 at 13:43
With[{ll = LineLegend},
ToExpression@
ToBoxes@Show[{g1, g2, g3},
PlotRange -> {{0, 4}, {0, All}}] //. {ll[{a1__}, {b1__}, c__],
ll[{a2_}, {b2_}, c__], rest___} :> {ll[{a1, a2}, {b1, b2}, c], rest}]


To understand why ToBoxes and ToExpression are used, read the following:

Graphics in Notebook Different from Graphics Expression?

Function equal to Ctrl+Shift+I

• Thanks! Your proposal works well! Apr 30, 2023 at 13:46
• I have one question about your code. Sometimes the combined legend may be displayed in two rows (this happens when each legend is a bit long). Do you know how to make the combined legend always shown in one row? May 2, 2023 at 0:47
• @YaHe It's answered in this post: mathematica.stackexchange.com/q/26231/1871 May 2, 2023 at 2:09
• Thanks! I have solved the problem. May 2, 2023 at 2:20
• @YaHe Then you should tell kglr you've solved this. May 2, 2023 at 2:45