sliding a tangent line along a curve
LocatorPane[Dynamic[pt, (pt = {#[[1]], Sin[#[[1]]]}) &],
Dynamic@Plot[{Sin[x],
ConditionalExpression[Cos[pt[[1]]]*(x - pt[[1]]) + Sin[pt[[1]]],
pt[[1]] - 1 <= x <= pt[[1]] + 1]}, {x, 0, 10},
PlotRange -> {{-2, 11}, {-2, 2}},
Epilog -> {PointSize[Large], Point[pt]}],
Appearance -> None]
For arbitrary function func
, replace Cos
with Derivative[1][func]
in the first argument of ConditionalExpression
.
Instead of Epilog -> {PointSize[Large], Point[pt]}],
one can also use
Mesh -> {{pt[[1]]}}, MeshStyle -> PointSize[Large]]
Update: Using Locator
as a graphics primitive, one can get the same result without having to use LocatorPane
:
Dynamic@Plot[{Sin[x],
ConditionalExpression[Cos[pt[[1]]]*(x - pt[[1]]) + Sin[pt[[1]]],
pt[[1]] - 1 <= x <= pt[[1]] + 1]}, {x, 0, 10},
PlotRange -> {{-2, 11}, {-2, 2}},
Epilog -> Dynamic@{Locator[Dynamic[pt, (pt = {#[[1]], Sin[#[[1]]]}) &],
Graphics[{Black, PointSize[Large], Point[pt]}]]}]
Even if this is already answered... here a short, straightforward, "solution", which might be instructive to people, not so deeply concerned with all that "Dynamic" stuff ;-)
f[x_] := Sin[x]
tangent[f_, x0_, x_] := f'[x0] (x - x0) + f[x0]
Manipulate[Plot[{f[x], tangent[f, p, x]}, {x, 0, 2 π},PlotRange -> {{0, 2 π}, {-3, 3}},
Epilog -> {Red, PointSize[.015], Point@{p, Sin[p]}}], {p, 0, 2 π}]
(edit by J. M.)
This is a variation of mgamer's proposal; I did not feel it deserved its own answer, but it was too long for a comment. This one eliminates the slider, and uses a Locator
instead, so that one can slide the tangent line along the curve:
Manipulate[Plot[f[x], {x, 0, 2 π}, PlotRange -> {{0, 2 π}, {-3, 3}},
Epilog -> {{Directive[ColorData[97, 2], AbsoluteThickness[1]],
InfiniteLine[{p[[1]], f[p[[1]]]}, {1, f'[p[[1]]]}]},
{Directive[Red, AbsolutePointSize[6]],
Point[{p[[1]], f[p[[1]]]}]}}],
{{p, {0, 0}}, Locator, Appearance -> None},
Initialization :> (f[x_] := Sin[x])]