# Formatting fractions in front in PlotLegends

I have this Plot:

Plot[{Sin[x], 3 Sin[x], Sin[x]/2}, {x, -2 Pi, 2 Pi},
ImageSize -> Large, AxesLabel -> {HoldForm[x], HoldForm[y]},
PlotLegends -> "Expressions", PlotStyle -> {Blue, Red, Green}]


In the graphic result, there is sin(x)/2

Is there a way to change it in 1/2 sin(x)?

• The simplest way is to set the legend manually, and type in the form that you prefer. – Szabolcs May 11 '17 at 8:32
• @Szabolcs If I am not in the Plot function, but I am somewhere else, is there a way to do that? And by the way, how can I set the legend manually? – Ale1794 May 11 '17 at 8:37
• You can use PlotLegends -> {Sin[x], 3 Sin[x], HoldForm[1/2] Sin[x]}. I do not understand your other question: "If I am not in the Plot function, but I am somewhere else" – Szabolcs May 11 '17 at 8:41
• @Szabolcs I think you answer that, nominating HoldForm – Ale1794 May 11 '17 at 8:48
• @Szabolcs I meant if i would like to write somewhere 1/2*sin[x] and not sin[x]/2 – Ale1794 May 11 '17 at 8:52

Here are a couple of ways.

1. We post-process the output. One has to take care, since we change the expression, that the result makes sense. The $excludedForms indicate expressions not to be altered. For a general purpose function, this might be quite long. For the OP's problem it need only be _Graphics. $excludedForms = _Graphics | _Graphics3D  (* |_Rule|_InterpolatingFunction etc. *);
fractionForm = # /.
{x : \$excludedForms :> x, HoldPattern[Times][c__?NumericQ, r__] :> Row[{c, r}, " "]} &;


2. This is more general, but overrides the built-in formatting process for Times.

ClearAll[fractionForm];
fractionForm /: MakeBoxes[fractionForm[expr_], form_] :=
InternalInheritedBlock[{Times},
Unprotect[Times];
Times /: MakeBoxes[HoldPattern[Times][c__?NumericQ, r__], f_] :=
MakeBoxes[Row[{c, r}, " "], f];
Protect[Times];
MakeBoxes[expr, form]
];


In both cases, we get this:

Plot[{Sin[x], 3 Sin[x], Sin[x]/2}, {x, -2 Pi, 2 Pi},
AxesLabel -> {HoldForm[x], HoldForm[y]},
PlotLegends -> "Expressions", PlotStyle -> {Blue, Red, Green}
] // fractionForm


This does it automatically for this example.

exp = {Sin[x], 3 Sin[x], Sin[x]/2};
Plot[exp, {x, -2 Pi, 2 Pi},
ImageSize -> Large, AxesLabel -> {HoldForm[x], HoldForm[y]},
PlotLegends -> (exp /. Rational[a_, b_] :> HoldForm[a/b]),
PlotStyle -> {Blue, Red, Green}]


No idea how generally this will work.

In:

Plot[{Sin[x], 3 Sin[x], Sin[x]/2}, {x, -2 Pi, 2 Pi},
ImageSize -> Large, AxesLabel -> {HoldForm[x], HoldForm[y]},
PlotLegends -> {"sin(x)", "3 sin(x)", "1/2 sin(x)"},
PlotStyle -> {Blue, Red, Green}]
`

Out: