The problem lies in g[x_] := D[f[x], x]
; remember that what SetDelayed
SetDelayed
(that is, :=
) does is to replace stuff on the right corresponding to patterns on the left before evaluating. Thus, when one does something like g[2]
(and something like this happens within Plot[]
), you are in fact evaluating D[f[2], 2]
, and since one cannot differentiate with respect to a constant ;), you get the General::ivar
error message.
If you use Set
Set
instead (that is, g[x_] = D[f[x], x]
), f[x]
is differentiated first before the result of D[]
is assigned to g[x_]
. Since what's on the right of g[x_]
is now an actual function, Plot[]
no longer has a reason to complain.