Possible Duplicate:
General::ivar is not a valid variable when plotting - what actually causes this and how to avoid it?

Beginner question:

Why can't I use D[] like that?

Plot[{Sin[x], D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]

If I assign the result of D[] to a variable and put that variable in the list it works.

  • 1
    $\begingroup$ What about Plot[{Sin[x], Sin'[x]}, {x, -2 Pi, 2 Pi}]? For any function of type f[x] you can use f'[x] in place of the D[f[x],x]. $\endgroup$ Commented Apr 5, 2012 at 13:22

3 Answers 3


Plot has attribute HoldAll which means in this case that D[Sin[x], x] isn't evaluated until after x is replaced with some number, so you end up with something like D[Sin[-6.28], -6.28] etc. which causes the errors since you can't take a derivative with respect to a number.

One way to get around this is to use Evaluate to evaluate the derivative before the numbers are plugged in, i.e. to do something like

Plot[Evaluate[{Sin[x], D[Sin[x], x]}], {x, -2 Pi, 2 Pi}]

Mathematica graphics

  • $\begingroup$ I find it weird however why Plot[{Sin[x], Evaluate[D[Sin[x], x]]}, {x, -2 Pi, 2 Pi}] won't work. You should be able to evaluate just the D[..] part, shouldn't you? $\endgroup$ Commented Apr 5, 2012 at 13:38
  • 4
    $\begingroup$ @Milosz This is because Evaluate only works on the first level of the held expression. So for example Hold[Evaluate[f[1+2]]] works, but Hold[f[Evaluate[1+2]]] doesn't. $\endgroup$
    – Heike
    Commented Apr 5, 2012 at 13:49

Quick answer: The help page for plot states that "Plot has attribute HoldAll, and evaluates f only after assigning specific numerical values to x." Therefore what D[] effectively sees is something like D[Sin[0.1],0.1] (where I chose 0.1 as an arbitrary numerical value) and issues an error message that 0.1 is no valid variable. To work around that you can use Evaluate[] like this

Plot[Evaluate@{Sin[x],D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]

You needn't use Evaluate, consider using of Derivative instead of D if you don't like to use Evaluate. Derivative operates on built-in or user-defined functions and returns pure functions, e.g.

Derivative[#][Sin] & /@ Range[4]
{Cos[#1] &, -Sin[#1] &, -Cos[#1] &, Sin[#1] &}

There are shortcuts for Derivative, e.g. f' or f'' are equivalent respectively to Derivative[1][f] and Derivative[2][f] and in your specific examples it works like this :

Plot[{Sin[x], Derivative[1][Sin][x]}, {x, -2 Pi, 2 Pi}]

enter image description here


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