6

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

g1 = Plot[x^2 + 3, {x, 0, 3}, 
   PlotLegends -> 
    Placed[LineLegend[{TraditionalForm[k == 1]}, 
      LegendLayout -> "Row", 
      LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], Below], 
   AxesOrigin -> {0, 0}, PlotStyle -> Red];
g2 = Plot[x^3 + x, {x, 1, 4}, 
   PlotLegends -> 
    Placed[LineLegend[{TraditionalForm[k == 2]}, 
      LegendLayout -> "Row", 
      LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], Below], 
   AxesOrigin -> {0, 0}, PlotStyle -> Blue];
g3 = Plot[20/x, {x, 1/2, 4}, 
   PlotLegends -> 
    Placed[LineLegend[{TraditionalForm[k == 3]}, 
      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: enter image description here

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?

Ya He
  • 160
  • 7

2 Answers2

6
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]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
4
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

xzczd
  • 65,995
  • 9
  • 163
  • 468