2
$\begingroup$

No, it's not InputForm. Consider this example:

p = Show[ListPlot[{1}, PlotLegends -> "1"], ListPlot[{2}, PlotLegends -> "2"]];

This is the output of p // InputForm:

enter image description here

while this is what you'll see if you execute p and select the output and press Ctrl+Shift+I:

enter image description here

Can I get the output of Ctrl+Shift+I with a function rather than keyboard shortcut?

What? Why I'm interested in such a boring question? Well, I encountered this when trying to do some direct modification on the legends. Try the following example:

data1 = Sin@Range[1, 10, 0.1];
data2 = Cos@Range[1, 10, 0.1];

pline = ListLinePlot[{data1, data2}, PlotLegends -> {"line1", "line2"}];

ppoint = ListPlot[{data1, data2}, PlotMarkers -> "0", PlotLegends -> {"point", "point2"}];

pjoin = Show[pline, ppoint];
pjoin /. Legended[Legended[a_, {Placed[b_, c__]}], {Placed[d_, e__]}] :> 
  Legended[a, Placed[Grid[{{b}, {d}}, Frame -> True], c]]

enter image description here

The last line added one frame for the different sorts of legends. Dirty, right? And it'll be dirtier if we have more sorts of legends. However, if the output of p is baptized by Ctrl+Shift+I (actually you just need to copy and paste it) then a much simpler pattern can be used!:

(* copy and paste the graphics here *) /. Grid[a__] :> Grid[a, Frame -> True]

The resulted graphics is the same so I'd like to omit it here.

$\endgroup$
1
  • 1
    $\begingroup$ xzczd, I have marked this question as a duplicate because I believe it is one. Please review it and let me know if it is not. $\endgroup$
    – Mr.Wizard
    Commented May 15, 2015 at 7:07

1 Answer 1

5
$\begingroup$

This points out that Legended is typeset instead of being evaluated in the kernel evaluation time. The evidence is in that InputForm[p] still contains two Legendeds and the graphics only one.

This is what you need:

Show[ListPlot[Range[10], PlotLegends -> {"a"}, PlotStyle -> Red], 
 ListPlot[Range[10] + 2, PlotLegends -> {"b"}, 
  PlotStyle -> Blue]] // ToBoxes // MakeExpression // InputForm // ReleaseHold

ToBoxes forces Legended to do its business to resolve multiple Legendeds during the evaluation time and MakeExpression reconstructs expressions from boxes so you can further parse.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.