# Prevent manipulations in PlotLegends

Mathematica code to reproduce:

LogPlot[{x^(4/3), x*E^Sqrt[8Log2[5/2]*Log2[x]],x^2,x^(3/2), x*Log2[x]^2}, {x,10,1000000},
PlotLegends->LineLegend["Expressions",LegendMarkers->Automatic]]


How can I prevent the equations from having their form modified?

It would also be nice if I could get Log2[x] to appear as $\log_2x$.

Note: I want to avoid having a second copy of the expressions in the input.

• Dec 5, 2012 at 23:45

## 2 Answers

I feel the following satisfies your three requirements of 1) having the labels unevaluated, 2) logs in TraditionalForm, and 3) functions specified only once:

funs =
Function[{expr}, Extract[expr, {1, #}, HoldForm] & /@ Range[Length[expr[[1]] ] ] ]@
Hold[
{x^(4/3), x*E^Sqrt[8 Log2[5/2]*Log2[x]], x^2, x^(3/2), x*Log2[x]^2}
];

LogPlot[funs // ReleaseHold // Evaluate, {x, 10, 1000000},
PlotLegends -> LineLegend[TraditionalForm /@ funs, LegendMarkers -> Automatic]
]


• Good idea to use Hold (+1). My answer is more boring and I don't actually have a way to test it...
– Jens
Dec 6, 2012 at 0:37
• @Jens Thanks! The basic idea came pretty soon, but it took quite a bit of fiddling before it all worked. Afterwards it looks so simple. Dec 6, 2012 at 0:43

It looks like your main goal is to have the base-two logarithm displayed in a more readable form in the legend while at the same time being recognized as Log2 in the first argument of the Plot command. Since labels and legends in plots are by default displayed in TraditionalForm, one can try to use this as a trigger to force the different display without having to enter two differently formatted versions for Log2.

However, since I don't think it's worth fiddling with protected names to modify the system behavior, I would instead recommend defining a custom function that looks like the base-two logarithm for the purpose of plot evaluations and displays the way you want in the legend. I don't want to mess with the built-in formatting of the Log2 function directly.

I'll call that new binary log ld and define it to be equal to the Log2 function, but only for numerical arguments (which is what you need when plotting). Then I make a separate definition for how ld is supposed to be formatted when TraditionalForm display is called for:

Clear[ld, x]

ld[x_?NumericQ] := Log2[x]

ld /: MakeBoxes[ld[x_], TraditionalForm] :=
RowBox[{SubscriptBox["log", 2], "(", ToBoxes[x], ")"}]


The last line contains the formatting. Here is a test for numerical and symbolic arguments of ld:

ld[3]

(* ==> Log[3]/Log[2] *)

ld[x]

(* ==> ld[x] *)

ld[x] // TraditionalForm


$\log_2(x)$

Edit

Sjoerd's simultaneous answer reminded me that I didn't say anything about how to put this into the plot. Well, I don't actually have version 9 installed here, but I would expect that it should work if you just replace Log2 by ld everywhere in your plot command.