0

If I plot a derivative it fails: Plot[ D[x^2 + 1, x], {x, -6., 6.}] General::ivar: -5.99975 is not a valid variable.

But if I simply put the derivative, 2x, in, the plot works: Plot[2x,{x,-.6,.6}]

Most other standard functions don't do this. Why doesn't plotting a derivative work, and what is the "..valid variable" warning about?

cybervigilante
  • 599
  • 2
  • 7

1 Answers1

2

Using With:

With[{f = D[x^2 + 1, x]}, Plot[f, {x, -6, 6}]]

Or using HoldForm as points out @userrandrand:

ReleaseHold@HoldForm[Plot][D[x^2 + 1, x], {x, -6, 6}]
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
  • 1
    Hi. I did not mention using HoldForm like that but that's a possibility. Although the idea of controlling the evaluation order is similar, I think it's quicker to use Plot[D[x^2+1,x]//Evaluate,{x,-6,6}]. Another possibility is D[x^2 + 1, x] // Plot[#, {x, -6, 6}] &. That last option is particularly convenient if there a lot of functions that will be plotted in the same interval in which case one can set plt=Plot[#, {x, -6, 6}] & and use D[x^2 + 1, x] //plt then D[x^4 + 1, x] //plt – userrandrand Oct 10 '22 at 01:37
  • Hi. True, you didn't mention using HoldForm in that way, but I thought you were thinking of that. In fact, D[x^2 + 1, x] // Plot[#, {x, -6, 6}] & is a better way. :-) – E. Chan-López Oct 10 '22 at 01:40
  • 1
    Another way is plt2 = OperatorApplied[Plot] then D[x^2 + 1, x] // plt2[{x, -6, 6}] which could be convenient for changing the interval. – userrandrand Oct 10 '22 at 01:53
  • 3
    @userrandrand - or more concisely, Plot @@ {D[x^2 + 1, x], {x, -6, 6}} – Bob Hanlon Oct 10 '22 at 02:36
  • @BobHanlon that one is quite beautiful. Feels like something I should save in a corner of my log on screen . Quite pretty. – userrandrand Oct 10 '22 at 02:42