5
$\begingroup$

Consider the following:

Quit[]
Format[Exp[x_], TraditionalForm]   (* e^{x_} *)
Format[Log[x_], TraditionalForm]   (* log(x_) *)

Now Plot[{Log[x], Exp[x]}, {x,1,2}, PlotLegends->"Expressions"] yields enter image description here

So perhaps PlotLegends doesn't use the TraditionalForm output, since the formatting for Exp doesn't correspond. But now:

Unprotect[Log]
Format[Log[x_], TraditionalForm] := ln[x]
Protect[Log]

Format[Log[x_], TraditionalForm]    (* ln(x_) *)

and now issuing the same plot command yields enter image description here

I would like exp(x) to print as e^x, so:

Unprotect[Exp]
Format[Exp[x_], TraditionalForm] := e^x

and I get SetDelayed: Tag Power in MakeBoxes[e^{x_}, TraditionalForm] is Protected. (Note: I've tried this both with the Mathematica ESC e e ESC and just the character e, with the same results.

So I guess I have two questions:

  1. What format is used for PlotLegends?
  2. Why is there a difference in behavior between Log and Exp in the above code?
$\endgroup$
  • $\begingroup$ Would using PlotLegends -> {Format[Exp[x], TraditionalForm], Format[Log[x], TraditionalForm]} not solve your issue? $\endgroup$ – MarcoB Jan 17 '17 at 22:38
  • $\begingroup$ Or perhaps Plot[{Log[x],Exp[x]},{x,1,2},PlotLegends->"Expressions"]/.HoldForm:> TraditionalForm? $\endgroup$ – chuy Jan 17 '17 at 23:03
5
$\begingroup$

For question 1, PlotLegends uses TraditionalForm, but it wraps the functions in HoldForm. For question 2, look at the FullForm of Exp[x]:

FullForm[Exp[x]]

Power[E,x]

The Exp[x] in the Format statement evaluates, which is why you get a SetDelayed::write message:

Unprotect[Exp]
Format[Exp[x_], TraditionalForm] := E^x
Protect[Exp]

{Exp}

-SetDelayed::write: Tag Power in MakeBoxes[E^x_,TraditionalForm] is Protected.

$Failed

{Exp}

So, you need to prevent evaluation by using HoldPattern:

Unprotect[Exp]
Format[HoldPattern@Exp[x_], TraditionalForm] := E^x
Protect[Exp]

{Exp}

{Exp}

Now, let's see if it worked:

Hold[Exp[x]]//TraditionalForm

Hold[E^x]

Note that the above is one of the reasons (evaluation leaks) I prefer using MakeBoxes rules instead, something along the lines of:

Unprotect[Exp]
Exp /: MakeBoxes[Exp[x_], TraditionalForm] := MakeBoxes[Power[E,x], TraditionalForm]
Protect[Exp]

{Exp}

{Exp}

|improve this answer|||||
$\endgroup$
  • $\begingroup$ One question, though: why does my original construct work for Log and not for Exp? Is it because Log appears to be built-in (FullForm[Log[x]] is Log[x]) while Exp is just shorthand for an invocation of the Power function? $\endgroup$ – rogerl Jan 18 '17 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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