# Question about using Replace All where x gets replaced with x-h

I'm having a little trouble with replace all. I'm illustrating horizontal and vertical shifting of basic graphs. The vertical shifting work fine, but the horizontal shifting does not work and has something to do with my lack of understanding on how replace all works. Any ideas?

Manipulate[
Plot[(f /. x -> (x - h)) + k, {x, -10, 10},
PlotRange -> {{-10, 10}, {-10, 10}},
Epilog -> Text[(f /. x -> (x - h)) + k, {7, 9}],
GridLines -> {Range[-10, 10], Range[-10, 10]},
GridLinesStyle -> Opacity[.04]], {{f, x^2, "base function:"}, {x^2,
Cos[x] -> "cos(x)"}}, {{k, 0, "k"}, -10, 10, 1}, {{h, 0, "h"}, -10,
10, 1}]


You can fix this by wrapping the plotting function inside an Evaluate:

Manipulate[
Plot[
Evaluate[(f /. x -> (x - h)) + k]
, {x, -10, 10}
, PlotRange -> {{-10, 10}, {-10, 10}}
, Epilog -> Text[(f /. x -> (x - h)) + k, {7, 9}]
, GridLines -> {Range[-10, 10], Range[-10, 10]}
, GridLinesStyle -> Opacity[.04]
]
, {{f, x^2, "base function:"}, {x^2, Cos[x] -> "cos(x)"}}
, {{k, 0, "k"}, -10, 10, 1}
, {{h, 0, "h"}, -10, 10, 1}
]


This seems to be related to the HoldAll attribute of Plot, which can cause some counter-intuitive evaluations. The Evaluate trick is pretty useful when plotting commands fail to recognize some aspect of the plotting function. For example, the naive attempt

Plot[
Table[x^n, {n, 0, 5}]
, {x, 0, 1}
]


will produce a bunch of blue lines - Plot will fail to realize that it's been fed six different lines to plot, and that it needs to render them in different colours, unless it's given an explicit List header. Wrapping the Table inside an Evaluate will then produce the desired behaviour.

Plot[
Evaluate[Table[x^n, {n, 0, 5}]]
, {x, 0, 1}
]


It seems your code falls prey to something similar, since the ReplaceAll works fine if you change the Plot to a dummy nonPlottingPlot, but the details are not that clear to me.

Alternatively, switching to pure functions for f (rather than expressions) will also fix it:

Manipulate[
Plot[
f[x - h] + k
, {x, -10, 10}
, PlotRange -> {{-10, 10}, {-10, 10}}
, Epilog -> Text[f[x - h] + k, {7, 9}]
, GridLines -> {Range[-10, 10], Range[-10, 10]}
, GridLinesStyle -> Opacity[.04]
]
, {{f, #^2 &, "base function:"},
{#^2 & -> "\!$$\*SuperscriptBox[\(x$$, $$2$$]\)", Cos -> "cos(x)"}}
, {{k, 0, "k"}, -10, 10, 1}
, {{h, 0, "h"}, -10, 10, 1}
]