# Why can't D[] be used in place here? [duplicate]

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.

-

## marked as duplicate by Anna Lear♦Oct 27 '12 at 3:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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]. –  PlatoManiac Apr 5 '12 at 13:22

## 3 Answers

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}]


-
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? –  0sh Apr 5 '12 at 13:38
@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. –  Heike Apr 5 '12 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}]


-