# Plotting with Units

I'm trying to get Mathematica to plot with units, but I'm having some trouble.

Below is a minimal example of trying to plot y = x, where x is a quantity with units. Why does it only seem to work if the units are put directly into the plot function:

(*Define unitful constants*)
x1 = Quantity[1, "Volts"]; x2 = Quantity[2, "Volts"];
(*Try to plot, get an error*)
Plot[x, {x, x1, x2}]
(*But this works*)
Plot[x, {x, Quantity[1, "Volts"], x2}]
(*As does this*)
Plot[x, {x, x1 - Quantity[1, "Volts"], x2}]


There error message is

Plot:plln: Limiting value 1V in {x, x1, x2} is not a machine-sized real number

For reference, here's what I see when I run it

(View full)

-
Please copy your code into your question and indent with 4 spaces to format it. Its very hard for people to help you wiht a screen shot as they can't directly copy your code. – s0rce Mar 8 '13 at 1:36
Sorry, I would have, but it necessarily contains Dynamic Input. I've added the notebook itself. – Sam Bader Mar 8 '13 at 1:51
I see what you mean. I only used it because I don't like to have Quantity[...,...] all over for readability. Let me rewrite the question with all "normal" code--the problem is still there. – Sam Bader Mar 8 '13 at 2:04

2 important things about Plot, from help:

For some reason, Plot is doing Hold on not just the first argument x, but also on the whole argument list, when x1 and x2 are Quantity.

When you did

x1 = Quantity[1, "Volts"];
x2 = Quantity[2, "Volts"];
Plot[x, {x, x1, x2}]


Then Trace shows this:

Plot[x, Unevaluated[{x, x1, x2}]]


and you can see now x1 and x2 have no numerical values.

But when one does this

x1 = 1;
x2 = 2;
Plot[x, {x, x1, x2}]


Then it works ofcourse, and Trace shows the Hold is doing on only the first argument x as expected:

Plot[x, {x, x1, x2}], {SystemDumpHeldOptionQ[x],
OptionQ[Unevaluated[x]], OptionQ[x], False


Now for the case that worked: When you typed

x1 = Quantity[1, "Volts"]; x2 = Quantity[2, "Volts"];
Plot[x, {x, Quantity[1, "Volts"], x2}]


This worked, because now Plot did this:

Plot[x, Unevaluated[{x, Quantity[1, "Volts"], Quantity[2, "Volts"]}]]


So the values 1 and 2 has been evaluated already inside the arguments.

Either way, it is strange and I do not know exactly why this happened. I just wanted to show more what is going on as to why Plot did what it did in the first case above. Either way, it has to do with evaluation of Quantity to a number. But I do not feel I gave an exact reason why Plot did what I did.

But to do what you want, you can use QuantityMagnitude like this

x1 = Quantity[1, "Volts"];
x2 = Quantity[2, "Volts"];
Plot[x, {x, QuantityMagnitude@x1, QuantityMagnitude@x2}]

-