3
$\begingroup$

How can I flip/mirror the legend like this? The text should be right aligned and if the text is longer than the text move to the left.

Legended[Show[ListLinePlot[{1, 2, 3}, PlotStyle -> Red], 
  Plot[x^2, {x, 1, 3}, PlotStyle -> Blue]], 
 Placed[LineLegend[{Red, Blue}, {"graph1", "graph2"}], {0.8, 0.5}]]

enter image description here

$\endgroup$
0

2 Answers 2

5
$\begingroup$

You can use "MarkerLayout", an undocumented option to Legend functions I've learned about in this answer. In fact, I think this question is likely a duplicate of that one.

Here is an example:

Legended[
  Plot[{x^3 - 2, x^2 - 1}, {x, -1, 2}, PlotStyle -> {Red, Blue}],
  LineLegend[
    {Red, Blue}, {"cubic", "quadratic"},
    LegendLayout -> "Column", "MarkerLayout" -> After
  ]
]

sample plot in which the legend marker lines are after the legend text

I found that, oddly, you have to include a LegendLayout directive for "MarkerLayout" to work. These are undocumented features after all...

$\endgroup$
2
  • $\begingroup$ Thanks, I have one additional question. This is not originally asked but what would you do if I want the text left-aligned? $\endgroup$
    – hana
    Commented Jun 29, 2022 at 3:22
  • $\begingroup$ @hana I suspect that you'd have to write your own function to pass to LegendLayout. At that point, unless you have to make hundreds of similar plots, it may be easier to build your legends by hand using graphics objects and Epilog. $\endgroup$
    – MarcoB
    Commented Jun 29, 2022 at 3:37
2
$\begingroup$

Using the undocumented option MarkerLayout, as @MarcoB points out, it could be something like this:

  Legended[Show[ListLinePlot[{1, 2, 3}, PlotStyle -> Red], 
  Plot[x^2, {x, 1, 3}, PlotStyle -> Blue]], 
  Placed[If[
  Mean[Map[Length[Characters[#]] &, 
  LineLegend[{"graph1", "graph2"}, {Red, Blue}][[1]]]] > 6, 
  LineLegend[{Red, Blue}, {"graph1", "graph2"}, 
  LegendLayout -> "Column", "MarkerLayout" -> After], 
  LineLegend[{Red, Blue}, {"graph1", "graph2"}, 
  LegendLayout -> "Column", "MarkerLayout" -> Before]], {0.8, 0.5}]]

enter image description here

 Legended[Show[ListLinePlot[{1, 2, 3}, PlotStyle -> Red], 
 Plot[x^2, {x, 1, 3}, PlotStyle -> Blue]], 
 Placed[If[
 Mean[Map[Length[Characters[#]] &, 
 LineLegend[{"My graph1", "My graph2"}, {Red, Blue}][[1]]]] > 6, 
 LineLegend[{Red, Blue}, {"My graph1", "My graph2"}, 
 LegendLayout -> "Column", "MarkerLayout" -> After], 
 LineLegend[{Red, Blue}, {"My graph1", "My graph2"}, 
 LegendLayout -> "Column", "MarkerLayout" -> Before]], {0.8, 0.5}]]

enter image description here

$\endgroup$
1
  • $\begingroup$ This works well, I have one additional question which I'd like to know so I may use it sometime in the future. What should I do if i want to make the text now left-aligned? $\endgroup$
    – hana
    Commented Jun 29, 2022 at 3:35

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